我有一个包含几种不同类型输入(复选框、文本、数字等)的表单我希望能够找到用户正在单击/键入的表单的当前元素的 ID 以及它们的值输入。
我目前令人惊讶地使用 undefined
作为值。我真的不知道从哪里开始(我不想使用 jQuery)
HTML
<form id = "myForm" >
<input type="text" id="name" name="name" placeholder ="Name" />
<input type="email" id="mail" name="email" placeholder ="Email" />
<input type="number" id="phoneNumber" name ="phone" placeholder = "Phone Number" />
<label for ="emailFormat">Email Signup Format:</label>
<select name="newsletter" id = "plain">
<option value = "Plain">Plain Text</option>
<option value = "HTML">HTML</option>
</select>
<label for="pets">Cars owned:</label>
<input type = "checkbox" id="mini" class = "ck" name ="mini">I have a mini.
<input type = "checkbox" id="motorbike" class = "ck" name ="motorbike">I have a motorbike.
<input type = "checkbox" id="thundercar" class = "ck" name ="thundercar">I have a thundercar.
<input type = "checkbox" id="brum" class = "ck" name ="brum">I have a brum.
<input type = "checkbox" id="roadrunner" class = "ck" name ="roadrunner">I have a roadrunner.
<button type="submit" id ="button">SUBMIT</button>
</form>
JavaScript
var form = document.getElementById("myForm");
form.addEventListener("keyup", store);
form.addEventListener("click",store);
function store() {
console.log(this.id);
console.log(this.value);
}
最佳答案
当将事件绑定(bind)到表单并依赖于事件冒泡时,this
将成为事件处理程序中的表单。
要获取触发事件的元素,您可以改用 event.target
function store(event) {
console.log(event.target.id);
console.log(event.target.value);
}
关于javascript - 在 keyup/click 上查找表单的 ID 和值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34453283/