Question

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)
        } 
});
Was it helpful?

Solution

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.

OTHER TIPS

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

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top