Link to home
Start Free TrialLog in
Avatar of Gregory3
Gregory3

asked on

Linking 2 HTML checkboxes

I have two checkboxes in seperate basic html tables.  I'm trying to get an easy javascript if statement to link the two together. So if checkbox1 is checked, so is checkbox2.
Thanks!


<table class="table1">
<tr>
                            <td>
                                <input type='checkbox' class='list_item' name="checkbox1" id=2 value=2 onclick='updateLayerVisibility();' />
                            </td>
                           
                        </tr>
</table>
<table class="table2">
                        <tr>
                            <td>
                                <input type='checkbox' class='list_item' name="checkbox2" id='2' value=2 onclick='updateLayerVisibility();' />
                            </td>
                           
                        </tr>
                       
</table>

Open in new window

Avatar of Eddie Shipman
Eddie Shipman
Flag of United States of America image

First, you need distinct id values. The first one can't be id=2 because it must be enclosed in quotes.

Once you get that squared away, you can do something this in your function:
(document.getElementById("2").checked ? document.getElementById("2").checked = document.getElementById("1").checked : document.getElementById("1").checked = document.getElementById("2").checked);

Open in new window

ASKER CERTIFIED SOLUTION
Avatar of Kim Walker
Kim Walker
Flag of United States of America image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
if (document.getElementsByName("checkbox1")[0].checked) {
document.getElementsByName("checkbox2")[0].checked=true;
}
Avatar of Gregory3
Gregory3

ASKER

Thanks for your responses.  
I have a variant of Sar1973's example working, but that is only for checking them both. The trick is getting them both checked and unchecked by clicking either one.  Hope that makes sense.  

EddieShipman I like your ternary  operator example but I can't get it to jive with my function.
Did you try my example?
Sorry about that, I missed that one.  That worked!  Much appreciated.
You're welcome. Glad it worked.