akaJag akaJag - 3 months ago 8
HTML Question

HTML radio and checkbox input combined?

How do you combine a radio and checkbox input? With that I mean when you select the radio button it deselects the checkboxes and when you select a checkbox the radio input gets deselected.

Here's my example input form:

<input type="checkbox" name="d[]"> option 1<br/>
<input type="checkbox" name="d[]"> option 2<br/>
<input type="checkbox" name="d[]"> option 3<br/>
<input type="radio" name="d[]"> option 4<br/>


Which would look like this

Example render of code.

Now if I were to select
option 4
I want
option 2
and
option 3
to deselect. How do I as best do this? Is there some easy trick or do I have to include some javascript magic?

Answer

You need some JavaScript (jQuery):

$('input[name="d[]"]').on('change', function(){
    if ($(this).attr('type') == 'radio' ) {
        if ( $(this).prop('checked') ) {
            $('input[name="d[]"][type="checkbox"]').prop('checked', false);
        }else {
            $('input[name="d[]"][type="checkbox"]').prop('checked', true);
        }
    }
    else {
        if ( $(this).prop('checked') ) {
            $('input[name="d[]"][type="radio"]').prop('checked', false);
        }else {
            $('input[name="d[]"][type="radio"]').prop('checked', true);
        }
    }
});

Live demo -- http://jsfiddle.net/u2n8j5r2/1/

Comments