aocferreira
aocferreira

Reputation: 693

Enabling textbox by means of checkbox with JS

Can you explain me how can I enable/disable a text box (that means, can or cannot be edit) depending on a combobox? If the combobox value = 1 -> textbox enable; if combobox = 0 -> textbox disable.

Upvotes: 0

Views: 767

Answers (4)

Pranay Rana
Pranay Rana

Reputation: 176906

Yes, you can do it easily.

Make use of the disabled attribute of the text box like this

function enableField(val)
{
  document.form1.address2.disabled = val;
}

Note: address2 is a textfield

Upvotes: 0

rsbarro
rsbarro

Reputation: 27339

You want to use the onchange event of the select element. Here's an example:

<html>
<head>
<script type="text/javascript">
function select1changed()
{
    var select1 = document.getElementById('select1');
    var txt1 = document.getElementById('txt1');
    txt1.disabled = (select1.value == '0');
}
</script>
</head>
<body>
    <form>
    Combo: 
    <select id="select1" onchange="select1changed();">
        <option value="0">Option 0</option>
        <option value="1">Option 1</option>
    </select>
    Text: <input id="txt1" type="text" value="sometext" disabled="disabled" />
    </form>
</body>

Note: I marked txt1 as disabled to handle the initial state when the page is loaded and select1 is set to Option 0.

Upvotes: 1

Darin Dimitrov
Darin Dimitrov

Reputation: 1038850

var combo = document.getElementById('combo');
combo.onchange = function() {
    var value = document.getElementById('combo').value;
    var textBox = document.getElementById('textbox');
    if (value == '0') {
        textBox.setAttribute('readonly', 'readonly');
    } else if (value == '1') {
        textBox.removeAttribute('readonly');
    }    
};

and here's a live demo.

Upvotes: 3

Max
Max

Reputation: 1334

Check this,

<select id='abc' onChange="changeMe()">
  <option value="">--Select--</option>
  <option value="111">111</option>
  <option value="222">222</option>
</select>
<input type="text" name="abcText" />
<script>
function changeMe(){
    if(document.getElementById("abc").value == "111"){
        document.getElementById("abcText").disabled = true;
    }else{
        document.getElementById("abcText").disabled = false;
    }
}
</script>

Upvotes: 0

Related Questions