Rene Brakus Rene Brakus - 3 months ago 21
HTML Question

only select one checkbox

I would like to build a javascript so a user can choose only one option between the the mentioned below. Could you give me some pointers how to do this since I am a javascript noob.

Thank you!

This is the picture of the part of a menu
enter image description here

<td><label for="dock_books_search_visible_online"> Visible online?</label></td>
<td><input type="checkbox" name="option" value="checkedVisibleOk" id="dock_books_visible_ok" /> </td>
<td><label for="dock_books_search_visible_online_yes"> Yes</label></td>
<td><input type="checkbox" name="option" value="checkedVisibleNok" id="dock_books_visible_nok" /> </td>
<td><label for="dock_books_search_visible_online_no"> No</label></td>

Answer

For single selection from multiple options we use Radio Buttons not CheckBoxes.

You should use some thing like this.

<input type="radio" name="option" value="Yes" id="yes" /> 
<input type="radio" name="option" value="No" id="no" /> 

But still if you want to go the other way round, Just add the following script in your head tag:

<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"></script>
<script>
$(document).ready(function(){
    $(':checkbox').bind('change', function() {
        var thisClass = $(this).attr('class');
        if ($(this).attr('checked')) {
            $(':checkbox.' + thisClass + ":not(#" + this.id + ")").removeAttr('checked');
        }
        else {
            $(this).attr('checked', 'checked');
        }
    });
});
</script>

Here is the fiddle for above.

Hope this helps.