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
https://forums.phpfreaks.com/topic/242353-single-checkbox/
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
https://forums.phpfreaks.com/topic/242353-single-checkbox/#findComment-1244753
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
https://forums.phpfreaks.com/topic/242353-single-checkbox/#findComment-1244759
Share on other sites

Archived

This topic is now archived and is closed to further replies.

×
×
  • 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.