最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - How do you monitor a select tag? - Stack Overflow

programmeradmin4浏览0评论

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 bees disabled.

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

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 bees disabled.

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

Share Improve this question asked Jul 4, 2011 at 23:59 mowwwalkermowwwalker 17.4k30 gold badges108 silver badges165 bronze badges
Add a ment  | 

3 Answers 3

Reset to default 7

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/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 remend 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/tB2Am/2/

发布评论

评论列表(0)

  1. 暂无评论