tell what form a button pressed is coming from

时间:2018-06-04 17:43:07

标签: javascript html

I have a single page application that uses multiple forms to display data. Most of the forms have the same input fields. I used JavaScript to create the form input fields - done once for all forms.

I can tell what form and field has been changed by looking at the form element form1.elements["varietyName"].options[form1.elements["varietyName"].selectedIndex].text or if it has been changed on form2.

I know how to create a button via JavaScript and populate it on multiple forms, but how can I tell what form that button was pressed on?

I can't give my button an onclick event, as it will be on form1 and form2. I also don't want the form to be submitted to the server when the button is clicked, so I can't use that.

2 个答案:

答案 0 :(得分:1)

您可以使用closest()查找与当前元素最接近的表单。所以,例如:

Array.from(document.querySelectorAll('input')).forEach(input => {
  input.addEventListener('click', e => {
    console.log(e.currentTarget.closest('form').id)
  })
})
<form id="a">
  <input type="button" value="click me">
</form>
<form id="b">
  <input type="button" value="click me">
</form>

答案 1 :(得分:-1)

如果您的目的只是寻找封装按钮的表单,那么它很容易。考虑到你有buttonElement,你可以找到它的parentNode并递归检查它的TagName,直到找到formElement。

但实际上我认为你得到了错误的方法,你应该更好地跟踪提交事件然后按钮点击事件。

和平。