質問

I'm trying to build a control function to check that at least an expected option from a select list is selected by the user.

I've built this function that works, except that it always returns me the first option value for the first element from the loop.

Example : for a select list with 1 : 'foo' and 2 : 'bar', the alert returns me 'foo' even if I chose 'bar' in the first select list, but it's right for the next select values.

$( document ).on( "click", "#submit", function() {
        var n = 0;
        for (var p = 0; p < index; p++) {
            var selectValue = $('#multiple_answer_'+p+'_option :selected').val();
            n++;
            alert('option '+n+' : '+selectValue)
        } 
});
役に立ちましたか?

解決

If your'e using .val() to retrieve the value of a select there is no need for :selected

var selectValue = $('#multiple_answer_'+p+'_option').val();

JS Fiddle: http://jsfiddle.net/aAURL/1/

Also note, the array is zero indexed so the id elements must start with multiple_answer_0_option.

他のヒント

That is because you are selecting $('#multiple_answer_'+p+'_option' ... which is only one on your page. '#' is added before id value of the item, and this value should be unique.

You should rather use 'class' or other attribute, which does not have to be unique, to make selections.

Try this

$('#submit').change(function(){ 
    var text = $(this).val();
    alert(text);
});

Fiddle Demo

ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top