我有一个表单,有几种不同类型的输入(复选框、文本、数字等),我希望能够找到用户正在单击/键入的表单的当前元素的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>the JavaScript
var form = document.getElementById("myForm");
form.addEventListener("keyup", store);
form.addEventListener("click",store);
function store() {
console.log(this.id);
console.log(this.value);
}发布于 2015-12-24 21:09:59
当将事件绑定到窗体并依赖于事件的冒泡时,this将成为事件处理程序中的窗体。
要获取在其上触发事件的元素,可以改用event.target
function store(event) {
console.log(event.target.id);
console.log(event.target.value);
}发布于 2015-12-24 21:24:15
跨浏览器解决方案:
function store(e) {
var target = (e.target)? e.target : e.srcElement;
console.log(target.id);
console.log(target.value);
}https://stackoverflow.com/questions/34453283
复制相似问题