mowwwalker
mowwwalker

Reputation: 17334

How do you monitor a select tag?

I'm sure there is a very simple solution, I just don't know it...

I have a text box and a selector. The first option in the selection is custom, where they can input with the text box. If they select something else, the text box becomes disabled.

I'm guessing the solution will be to put an onclick to test the value, but is there another way?

Upvotes: 4

Views: 7617

Answers (3)

Matt Ball
Matt Ball

Reputation: 359786

Use the change event, not the click event.

var select = document.getElementById('mySelect'),
    textbox = document.getElementById('myTextbox');

function onSelectChanged()
{
    console.log(select.selectedIndex);
    textbox.disabled = select.selectedIndex !== 0;
}

if (select.addEventListener)
{
    select.addEventListener('change', onSelectChanged, false);
}
else
{
    // !@#$ing IE support, of course
    select.attachEvent('onchange', onSelectChanged, false);
}

Demo: http://jsfiddle.net/mattball/pJMWN/

Upvotes: 7

aroth
aroth

Reputation: 54806

You would use an onchange listener on your select element. I also recommend using an onkeyup listener because some browsers do not fire onchange events when the user changes the select-box value using the keyboard. Here is some example code:

<select id="mySelect" name="name" onkeyup="this.onchange();" onchange="selectChanged(this);">
    <option value="-1">(custom value)</option>
    <option value="1">1</option>
    <option value="2">2</option>
</select>
<input type="text" id="customText" name="customOption" value="" />

<script>
    window.selectChanged = function(theSelect) {
        var textInput = document.getElementById("customText");
        if (theSelect.selectedIndex == 0) {
            textInput.disabled = undefined;
        }
        else {
            textInput.disabled = true;
            textInput.value = "";
        }
    };
</script>

Example: http://jsfiddle.net/tB2Am/2/

Upvotes: 0

Dinash
Dinash

Reputation: 3047

dont think onclick will serve your purpose better use onchange event in the selection and check for the selected value not equal to custom and then enable/disable your text box...

Hope this helps you,,,,

Upvotes: 0

Related Questions