In javascript how do I refer to this.form.checkbox[5].checked?

大城市里の小女人 提交于 2019-12-12 01:17:13

问题


I have a series of checkboxes and input type="text" areas, wherein I need to have the state of the checkbox set to true when the value in the text area changes. Simple enough. I've done this successfully:

<input name="fixed" type="checkbox">
<input name="stuff" type="text" onchange="this.form.fixed.checked=true">

Which works fine. You have to edit the field then click out of it, but that is fine for my needs:

...but when I switch to this:

<input name="fixed[0]" type="checkbox">
<input name="stuff" type="text" onchange="this.form.fixed[0].checked=true">
<input name="fixed[1]" type="checkbox">
<input name="stuff" type="text" onchange="this.form.fixed[1].checked=true">

I get no change to my checkboxes when I edit:

My only javascript know-how comes from googling this sort of thing, I'm afraid. Anyone have any better info on this than the Oracle of Google on The Mountain has in store?

thanks...


回答1:


Switch from dot notation to bracket notation!

this.form['fixed[0]'].checked



回答2:


It might be that you're mixing some shady practices in HTML, and when you do it in javascript, they're breaking.

So this.form.fixed[1] in javascript really says "The second item in the array this.form.fixed. So I think that's the problem. try naming your elements fixed0 and fixed1 and see if that works.

Edit: You could also use bracket notation, as illustrated by Peter, which should solve the problem without editing the names of the inputs.




回答3:


Make life easier on yourself.

Create unique ID's for the elements you are trying to reference and refer to them from the elements to which you bind your events:

<input name="fixed[0]" type="checkbox" id="fixed_0">
<input name="stuff" type="text" onchange="document.getElementById('fixed_0').checked=true">
<input name="fixed[1]" type="checkbox" id="fixed_1">
<input name="stuff" type="text" onchange="document.getElementById('fixed_1').checked=true">


来源:https://stackoverflow.com/questions/703126/in-javascript-how-do-i-refer-to-this-form-checkbox5-checked

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!