user906153
user906153

Reputation: 1218

Check a checkbox on a dropdown selection

I'm looking for a way to automatically check a checkbox when a selection is made from a dropdown. The HTML code looks something like this:

<table>
    <tr>
        <td>
            <input type="checkbox" name="check1" />Process 1:</td>
        <td>
            <select id="process1" name="process1">
                <option value="null">--Select Process--</option>
                <option value="NameA">NameA</option>
                <option value="NameB">NameB</option>
                <option value="NameC">NameC</option>
            </select>
        </td>
    </tr>
</table>

If possible, if the user goes back and selects --Select Process--, the checkbox would uncheck

What would the Javascript code look like for this?

Upvotes: 0

Views: 6188

Answers (4)

Silver_Clash
Silver_Clash

Reputation: 405

This answer is really cool!

But if you open that would use jQuery then the code would look like this:

jQuery(document).ready( function() {
    jQuery('#process1').on('change', function() {
        var selectedVal = jQuery(this).find('option:selected').val(),
            checkbox = jQuery('input[name="check1"]');
        if (selectedVal !== 'null') {
            checkbox.attr('checked', 'checked');
        } else {
            checkbox.removeAttr('checked');
        }
    });
});

Demo

Upvotes: 0

Jack Pettinger
Jack Pettinger

Reputation: 2755

jQuery would be easier, but in Javascript, try adding an onchange attribute to the select:

onchange="checkValue()"

Then in javascript:

function checkValue() {
   var e = document.getElementById("process1");
   var value = e.options[e.selectedIndex].value;
   if (value == "null") {
      document.getElementById("check1").checked=false;
   } else {
      document.getElementById("check1").checked=true;
   }
}

Just add an id to the checkbox id="check1"

Upvotes: 1

Mate
Mate

Reputation: 5274

Try this:

DEMO

JS

function setChk(value){
    var chk = document.getElementById('check1');
    chk.checked = (value != 'null');
}

HTML

<table>
    <tr>
        <td>
            <input type="checkbox" name="check1" id="check1"/>Process 1:</td>
        <td>
            <select id="process1" name="process1" onchange="setChk(this.value);">
                <option value="null">--Select Process--</option>
                <option value="NameA">NameA</option>
                <option value="NameB">NameB</option>
                <option value="NameC">NameC</option>
            </select>
        </td>
    </tr>
</table>

Upvotes: 2

oleron
oleron

Reputation: 483

$(function(){
    $('#process1').change(function() {
        var selected = $('#process1 option:selected');
        if (selected.val() == "null") {
            $('input[name="check1"]').prop('checked', false);
        }
        else {
            $('input[name="check1"]').prop('checked', true);
        }
    });
});

Upvotes: 2

Related Questions