Jump to content

Single checkbox


dotkpay

Recommended Posts

Hello,

Am trying to come up with js that allows only one checkbox in a group to be selected. My idea is that the js would deselect the currently checked box upon the user clicking another checkbox.

For example:

 

<form action="process.php" method="GET">

What is your favourite car brand?

 

<br><input type="checkbox" name="choice" value="audi">Audi

<br><input type="checkbox" name="choice" value="bmw">BMW

<br><input type="checkbox" name="choice" value="jaguar">Jaguar

<br><input type="checkbox" name="choice" value="mercedes">Mercedes

<br><input type="checkbox" name="choice" value="vw">VW

 

<br><input type="submit"></form>

 

How do I get only one answer submitted. If a user happens to turn off js in the browser and select multiple choices the php processing script (process.php) will generate an error and call exit() so that issue is already taken care of.

 

Thanks in advance

Link to comment
Share on other sites

I'm feeling kind of lazy right now so I won't write the code but i'll tell you how it can be done..create an onclick function that will disable the rest of the radio buttons so they cannot be clicked after one is clicked..something like

 

<script type="text/javascript">

function disableField()
{
document.form1.address2.disabled=true;
}

</script>

Link to comment
Share on other sites

I don't understand your reasoning. But if you're using a lot of JavaScript, use jQuery as it'll alleviate a lot of cross browser issues. Should be simple enough in jQuery.

 

$(document).ready(function(){
   $('input[name=choice]').click(function(){
      $('input[name=choice]').removeAttr('checked'); // uncheck all the checkboxes
      $(this).attr('checked', 'checked'); // check the clicked checkbox
   });
});

 

Something like that should suffice.

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.