Reputation: 1218
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
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');
}
});
});
Upvotes: 0
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
Reputation: 5274
Try this:
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
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