views:

466

answers:

4

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: 

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>
anthares
A: 

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.

Renesis
+1  A: 

I updated the jsbin link you provided with the proper jQuery needed to achieve the desired effect.

http://jsbin.com/ipomu/2

T B
what if it needs to be changed for option 2 and option 3
Omnipresent
Do you mean if option 2 and 3 are both selected it becomes activated? or just 1 or the other?
T B
+1  A: 

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.

rahul