My function SelectBeatle checks input#FindBeatle and sets the selectedIndex of select#Beatles to the value of input#FindBeatle

However, for some odd reason, it seems as though the my loop won't run:
http://jsfiddle.net/js_test/M9ty7/

Am I missing something?



Here is the HTML:

<input id="FindBeatle" type="text" />

<select id="Beatles">
    <option>John</option>
    <option>Paul</option>
    <option>George</option>
    <option>Ringo</option>
</select>

<input type="button" onclick="SelectBeatle()" value="Submit" />

and here is my JS:

var SelectBeatle = function(){
    var sel = document.getElementById('Beatles'),
        val = document.getElementById('FindBeatle').value;

        for(var i = 0, j = sel.options.length; i < j; i++) {
            if(sel.options[i].innerHTML === val) {
                sel.selectedIndex = i;
                break;
            }else{
                alert("Try Again!");
            }
        }
};
有帮助吗?

解决方案 2

well, the console said SelectBeatle is undefined... so your function is probably not visible in the html scope when you click the button.

When you say var, in js, that var only exists inside the current scope. JSFiddle adds a function wrapper in its javascript, limiting your scope.

Of course the best option is to capture the click event of the button:

var btn = document.getElementById('submit');
btn.addEventListener('click',function(event){
    SelectBeatle();
});

Here's a fiddle: http://jsfiddle.net/M9ty7/15/

其他提示

Your js is breaking when you set the initial txt value.

txt = sel.options[i].innerHTML;

i doesn't yet exist

Take out the var before your function definition. At least in jsfiddle, this is causing your function definition to not be available to your button click

$('#FindBeatle').val($('#Beatles').val());

OR

$('#FindBeatle').val($('#Beatles :selected').text());
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top