开发者

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 t开发者_Go百科est the value, but is there another way?


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/


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,,,,


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/

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜