سؤال

I have a form with a select field. When the user select a value, I want to display this value.

html is:

<select name="number" id="number">
        <option value="1">2</option>
        <option value="2">4</option>
</select>

<div id="test">2</div>

and jquery is

$(function() {
    $('#number').change(function() {
        var test = $('#test');
        if($('select[name="number"]').val() == '4'){
            test.html('select 4');
        }else{
            test.html('select 2');
        }
    });    
});

It's just working for the fist select (with the wrong value though) then it doesn't want to work.

here a jsFiddle: http://jsfiddle.net/tomlazada/4sRmG/

هل كانت مفيدة؟

المحلول

You don't have any option with value 4

if($('select[name="number"]').val() == '4'){

change it to

Fiddle Demo

if($('select[name="number"]').val() == '2'){

Problem

<option value="2">4</option>
//             ^ value is 2 not 4

Or

Fiddle Demo

If you want to do it with text of option

if ($('select[name="number"] option:selected').text() == '4') 

نصائح أخرى

Try below its working fine. You wrote lot of unnecessary code

$('#number').change(function(){
    $('#test').html('Selected: ' + $('#number').val());
});

You confuse the text inside the <option> (which is 4) with the value of that <option> (which is 2).

To solve your problem do one of 3:

1). Change your html to (so option will have value 4, not just inner text 4):

<option value="1">2</option>
<option value="4">4</option>

2). Or your jQuery code (so you select option with value 2):

if($('select[name="number"]').val() == '2'){

3). Or your jQuery code (better not check by text, but if you want to keep the html "as is" and still use 4 for some reason):

if($('select[name="number"] option:selected').text() == '4'){

Also, as @Dinu mentionted, consider the shorter notation.

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top