Mach5
Mach5

Reputation: 1

Enable single or multiple checkboxes checked based on radio button

I have a simple form with radio buttons and checkboxes where user can choose between downloading single or multiple language packages. If single option is selected the checkboxes should behave just like radio buttons and only one checkbox can be ticked. If user selects multi option he/she can tick any number of checkboxes. How can I achieve this using JQuery/JavaScript? Any help would be greatly appreciated as I am totally new to this. Here is the simple HTML form:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org    /TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
        <title>Untitled Document</title>
    </head>
    <body>
        <p>Language options:</p>
        <form id="form1" name="form1" method="post" action="">
            <p>
                <label>
                <input type="radio" name="langOptionRadioBtn" value="Single" id="langOptionRadioBtn_0" />
                Single</label>

                <label>
                <input type="radio" name="langOptionRadioBtn" value="Multi" id="langOptionRadioBtn_1" />
                Multi</label>

                <br />
            </p>
        </form>
        <p>Languages: </p>
        <form id="form2" name="form2" method="post" action="">
            <p>
                <label>
                <input type="checkbox" name="langCheckBoxes" value="English" id="langCheckBoxes_0" />
                English</label>

                <br />
                <label>
                <input type="checkbox" name="langCheckBoxes" value="French" id="langCheckBoxes_1" />
                French</label>

                <br />
                <label>
                <input type="checkbox" name="langCheckBoxes" value="Spanish" id="langCheckBoxes_2" />
                Spanish</label>

                <br />
                <label>
                <input type="checkbox" name="langCheckBoxes" value="Russian" id="langCheckBoxes_3" />
                Russian</label>

                <br />
                <label>
                <input type="checkbox" name="langCheckBoxes" value="Arabic" id="langCheckBoxes_4" />
                Arabic</label>

                <br />
                <label>
                <input type="checkbox" name="langCheckBoxes" value="Chinese" id="langCheckBoxes_5" />
                Chinese</label>

                <br />
            </p>
        </form>
    </body>
</html>

Upvotes: 0

Views: 3717

Answers (6)

coffeeguy
coffeeguy

Reputation: 51

The way I have written is in the following steps:
1)Find which radio button is selected.
2)If the check boxes are selected previously and the count of selected check boxes is greater than 1, then clear all the check boxes.
3)When Single option is selected, then Call a method which deselects the rest of the check boxes.
4)When multi option is selected, then unbind the method which causes to deselect other check boxes enabling to check more than one check box.

I know that my code is lengthy bu however, I think it would get you started and it is readable as well.

Sample example from fiddle would be

$('.language_options').on('click', function() {


ClearCheckBoxes();

if(this.id=='langOptionRadioBtn_0')
{
    $('input[name="langCheckBoxes"]').on('change', function() {
        ClearOtherCheckBoxes(this,'single');

    });

}
else
{
     $('input[name="langCheckBoxes"]').unbind();
}

});

Here is the fiddle link.

http://jsfiddle.net/5wadfh3o/16/


This is been tested on FireFox 31.0

Thank you.

Upvotes: 0

meni181818
meni181818

Reputation: 1101

I see here answer, says change to radio, But it is also possible with checkbox:

var allowMultiLang = false;

$('#form1 input[type=radio]').on('change', function() {
  // get the selected radio
  var selectedRadio = $('input[type=radio]:checked');
  // if the selected is 'Single'
  if(selectedRadio.val() == 'Single') {
    allowMultiLang = false;
    // uncheck all
    $('#form2 input[type=checkbox]:checked').prop('checked', false);
  // if the selected is 'Multi'
  } else if(selectedRadio.val() == 'Multi') {
    allowMultiLang = true;
  }

});

$('#form2 input[type=checkbox]').on('change', function() {
  if(allowMultiLang === false) {
    if($(this).is(':checked')) {
      // uncheck all BUT this
      $('#form2 input[type=checkbox]').not(this).prop('checked', false);
    }
  }
});

demo: http://jsfiddle.net/b5Le3uLb/

Upvotes: 0

grammar
grammar

Reputation: 871

Firstly you don't need two separate forms for this. It sounds like all the data should be sent to the same place, and thus there's no reason to wrap the radio buttons and checkboxes in separate <form> tags. Your markup could look like this:

<p>Language options:</p>
<form id="form1" name="form1" method="post" action="">
  <p>
    <label>
      <input type="radio" name="langOptionRadioBtn" value="Single" id="langOptionRadioBtn_0" />
      Single</label>
    <label>
      <input type="radio" name="langOptionRadioBtn" value="Multi" id="langOptionRadioBtn_1" />
      Multi</label>
    <br />
  </p>
<p>Languages: </p>
  <p>
    <label>
      <input type="checkbox" name="langCheckBoxes" value="English" id="langCheckBoxes_0" />
      English</label>
    <br />
        <label>
      <input type="checkbox" name="langCheckBoxes" value="French" id="langCheckBoxes_1" />
      French</label>
    <br />
    <label>
      <input type="checkbox" name="langCheckBoxes" value="Spanish" id="langCheckBoxes_2" />
      Spanish</label>
    <br />
    <label>
      <input type="checkbox" name="langCheckBoxes" value="Russian" id="langCheckBoxes_3" />
      Russian</label>
    <br />
    <label>
      <input type="checkbox" name="langCheckBoxes" value="Arabic" id="langCheckBoxes_4" />
  Arabic</label>
    <br />
    <label>
      <input type="checkbox" name="langCheckBoxes" value="Chinese" id="langCheckBoxes_5" />
      Chinese</label>
    <br />
   </p>
</form>

Here is the jQuery code you can use to do what you proposed. The idea is that every time the user clicks a checkbox, we check if multi was selected. If it is, then we don't have to change the behaviour of the checkboxes, but if it is not, then we clear all checkboxes except the one the user actually selected.

var $form = $('#form1');
var $checkboxes = $('input[type=checkbox]');
var $selectionType = $('input[type=radio]');
var $output = $('#output');
var isMulti = false;



// Listen to change event on the radio buttons and set isMulti
$selectionType.on('change', function( e ) {
    // Check the value of what radio button was clicked
    isMulti = $( e.target ).val() === 'Multi';

    // Clear all selected checkboxes if user clicked "single"
    if( !isMulti ) {
        $checkboxes.each( function( idx, item ) {
            $( item ).prop( 'checked', false );
        });
    }
});

// Listen to clicks on checkboxes
$checkboxes.on('change', function( e ) {

    // Store what was just clicked
    var $this = $( e.target );

    // If Multi is not selected, then remove the check from all other checkboxes
    if( !isMulti ) {

        $checkboxes.each( function( idx, item ) {

            var $item = $( item );

            // Do not un check if this is the checkbox the user clicked
            if( $item.attr('id') === $this.attr('id') ) {
                return true;
            }

            $item.prop('checked', false );
        });
    }
});

Here's a JS fiddle with it working: http://jsfiddle.net/grammar/pdx8gccu/2/

Hope this helps!

Upvotes: 1

Amin Jafari
Amin Jafari

Reputation: 7207

here you go: DEMO

$('input[type=checkbox]').change(function(e){
    if($('input[type=radio]:checked').length==0){ 
        $(this).prop('checked',!$(this).prop('checked'));
        return false;
    }
    else if($('input[type=radio]:checked').val()=='Single'){
        $('input[type=checkbox]').not(this).prop('checked',false);
    }
});
$('input[type=radio]').click(function(){
    $('input[type=checkbox]').prop('checked',false);
});

here if you click any of the radio buttons, all the checkboxes get deselected, and if none of the radio buttons are selected, the user can not select a checkbox, the rest is as requested in the question.

Upvotes: 0

Blake A. Nichols
Blake A. Nichols

Reputation: 870

A quick and simple way is to change the types when you select one or the other.

<label>
    <input type="radio" name="langOptionRadioBtn" value="Single" id="langOptionRadioBtn_0" onclick="updateBoxes('radio');" />
    Single
</label>
<label>
      <input type="radio" name="langOptionRadioBtn" value="Multi" id="langOptionRadioBtn_1" onclick="updateBoxes('checkbox');" />
Multi

Then the function to update the boxes

function updateBoxes(type) {
    var boxes = document.getElementById( 'form2' ).getElementsByTagName( 'input' );
    for( var i=0; i<boxes.length; i++ ) {
        boxes[i].type=type;
        boxes[i].checked = false;
    }
}

Upvotes: 0

Duane
Duane

Reputation: 4499

You just need to switch the input types on click:

$("#langOptionRadioBtn_0").click(function(){
    $('#form2 input[type="checkbox"]').each(function(){
        $(this).prop("type", "radio");
    });
});

$("#langOptionRadioBtn_1").click(function(){
    $('#form2 input[type="radio"]').each(function(){
        $(this).prop("type", "checkbox");
    });
});

You can test the code live here at http://jsfiddle.net/um1qgexr/.

Upvotes: 1

Related Questions