how to make a checkbox enable/disable based on selection in multiple box
I have a multi selection combo 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 combo box.开发者_开发知识库
Is this possible to do ...either by javascript or jQuery. I am already using jquery elsewhere.
Example: http://jsbin.com/ipomu
to begin with checkbox will be disabled. it should only be enabled when user clicks on option 2
A 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" ];
$("#combobox").change(function(){
var valToCheck = String($(this).val());
if ( jQuery.inArray(valToCheck,arrVal) == -1 )
{
$("#check").attr("disabled", "true");
}
else
{
$("#check").removeAttr ( "disabled" );
}
});
});
</script>
<select id="combobox" 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.com/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 combo 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.
精彩评论