I have a multi selection bo box and a checkbox in a form.
I'd like the checkbox to be enabled only when user selects a particular value from the multi selection bo box.
Is this possible to do ...either by javascript or jQuery. I am already using jquery elsewhere.
Example:
to begin with checkbox will be disabled. it should only be enabled when user clicks on option 2
I have a multi selection bo box and a checkbox in a form.
I'd like the checkbox to be enabled only when user selects a particular value from the multi selection bo box.
Is this possible to do ...either by javascript or jQuery. I am already using jquery elsewhere.
Example: http://jsbin./ipomu
to begin with checkbox will be disabled. it should only be enabled when user clicks on option 2
Share Improve this question asked Feb 5, 2010 at 22:22 OmnipresentOmnipresent 30.4k48 gold badges148 silver badges189 bronze badges4 Answers
Reset to default 3A sample one. You just add the option values for which you want to enable the checkbox to the array object. In the following sample I have enabled the checkbox on click of 2, 3,5 and 7 options.
<script type="text/javascript">
$(function(){
var arrVal = [ "2","3", "5", "7" ];
$("#bobox").change(function(){
var valToCheck = String($(this).val());
if ( jQuery.inArray(valToCheck,arrVal) == -1 )
{
$("#check").attr("disabled", "true");
}
else
{
$("#check").removeAttr ( "disabled" );
}
});
});
</script>
<select id="bobox" size="9" id="reasons" multiple="multiple">
<option value="1">Option 1</option>
<option value="2">Option 2</option>
<option value="3">Option 3</option>
<option value="4">Option 4</option>
<option value="5">Option 5</option>
<option value="6">Option 6</option>
<option value="7">Option 7</option>
</select>
Working demo for your example.
I updated the jsbin link you provided with the proper jQuery needed to achieve the desired effect.
http://jsbin./ipomu/2
You can enable/disable an html element through javascript with:
document.getElementById('<the id of your checkbox here>').disabled = true;
So, you have to add OnChange event of your multi selection bo box and add logic in some function when to disable/enable your checkbox. Example:
<select onChange="myfunc(this)">
...
<script>
function myfunc(sel)
{
if (sel.selectedValue == "2")
document.getElementById('<the id of your checkbox here>').disabled = true;
}
</script>
Most simply, with straight Javascript, and no jQuery, you could add the following onchange
attribute to the select
element (assuming that the elements are both surrounded by the same form):
onchange="this.form['mycheck'].disabled = (this.value != 2)"
If they are not in the same form, or if you don't know the name of the intended element, or the elements are dynamically created, the .disabled = (this.value != 2)
will be the same, but the method of finding the right checkbox may be different.