简体   繁体   中英

Unexpected javascript output

I have a lot of table rows dynamically generated which generally take the form of the following

<td class="seatClass" >
    <label for="C" class="label-format" >
        <span > C0</span >
    </label >
    <input type = "checkbox" id = "C" name = "seats[US57][]" style = "display: inline-block;" value = "C"  class="terminalCheckbox" onchange = "parentNode.querySelector('span').classList.toggle('green');" />
</td>

Basically, my code displays a lot of labels and checkboxes in different rows. If X represents the checkbox, you can imagine something like this

LX IX DX JX
OX PX IX DX 
BX AX WX QX

Now sometimes these rows contain the same labels for instance I appears in both the first and second rows and the code for the two will almost be identical (because the values for their id's and names are dynamic).

Anyways, I am facing a weird problem. If you check a checkbox, I wanted its associated letter to turn green, hence the bit of javascript I added. This works fine. However, my problem is say I click on the letter I on the second row (not the checkbox). If I do this, the checkbox for the I in the first row gets checked and the I in the first row turns green. So checking a checkbox things work fine, but if I click a letter things are messed up.

Is there any reason looking at my code as to why this is happening? I have no other javascript on this, I can only think it is because labels and checkboxes are being replicated on other rows, but it still kind of confuses me as to why this would happen.

Thanks

Note that IDs have to be unique.

Instead of specifying the for attribute, wrap the input with the label. This makes it unnecessary to know the exact id of the nested control.

 .green{ color:green; } 
 <table> <tr> <td class="seatClass" > <label class="label-format" > <span > C0</span > <input type="checkbox" name="seats[US57][]" style="display: inline-block;" value="C" class="terminalCheckbox" onchange="parentNode.classList.toggle('green');" /> </label > </td> </tr> <tr> <td class="seatClass" > <label class="label-format" > <span > C0</span > <!-- note: change the onchange javascript to match the new layout. The label will now be the parent of the input. --> <input type="checkbox" name="seats[US57][]" style="display: inline-block;" value="C" class="terminalCheckbox" onchange="parentNode.classList.toggle('green');" /> </label > </td> </tr> </table> 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM