Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery: Change dropdown select when checkbox is checked/unchecked

I have this form:

<input type="checkbox" value="First" />First
<input type="checkbox" value="Second" />Second
<input type="checkbox" value="Third" />Third

<select name="first-drop">
    <option value="---">---</option>
    <option value="Option1">Option1</option>
    <option value="Option2">Option2</option>
</select>

​Is there a way (using JS/jQuery) I can change the value of first-drop to --- whenever the First check box is unchecked?

like image 428
gabmadrid Avatar asked Dec 30 '25 22:12

gabmadrid


2 Answers

$('input[type="checkbox"][value="First"]').change(function (){
    $('select[name="first-drop"]').toggle();
});​

LIVE DEMO

Note that I fixed you markup:

<input type="checkbox" value="First" checked="checked" >First
<input type="checkbox" value="Second" />Second
<input type="checkbox" value="Third" />Third

<select name="first-drop">
    <option value="">---</option>
    <option value="Option1">Option1</option>
    <option value="Option2">Option2</option>
</select>​

Update:

What you want now is:

$('input[type="checkbox"][value="First"]').change(function() {
    if (!this.checked) {
        $('select[name="first-drop"] option:first').prop('selected', 'selected');
    }
});

​LIVE DEMO

If you will give your DOM elements ids it can be simple as that:

$('#first').change(function() {
    if (!this.checked) 
        $('#nothing').prop('selected', 'selected');
});

Updated DOM:

<input type="checkbox" value="First" id="first" >First
<input type="checkbox" value="Second">Second
<input type="checkbox" value="Third">Third

<select name="first-drop">
    <option value="" id="nothing" >---</option>
    <option value="Option1" >Option1</option>
    <option value="Option2">Option2</option>
</select>​

LIVE DEMO

like image 194
gdoron is supporting Monica Avatar answered Jan 02 '26 12:01

gdoron is supporting Monica


I added an ID to the first checkbox

<input id="first" type="checkbox" value="First">First</input>
<input type="checkbox" value="Second">Second</input>
<input type="checkbox" value="Third">Third</input>

<select name="first-drop">
    <option value="">---</option>
    <option value="Option1">Option1</option>
    <option value="Option2">$Option2</option>
</select>

<script type="text/javascript">
    $(function () {
        $("#first").click(function () {
            if ($(this)[0].checked == true) {
                $("[name='first-drop'] option:first").attr("selected", "selected");
            }
        });
    });​
</script>

Demo:

http://jsfiddle.net/8BtYc/2/

Edit: Fixed my code so that it doesn't toggle when you uncheck the first checkbox

like image 25
mattytommo Avatar answered Jan 02 '26 11:01

mattytommo



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!