选中jQuery选择框

时间:2014-04-23 09:15:44

标签: javascript jquery select onchange

我正在尝试检查选择框值。我知道这个问题早先在Stack上被问过,但我无法解决这些问题。

这是我选择的表格:

<ul id="config-steps">
    <span class="step-number">4</span>
    <select id="type">
       <option value="">-- <?php _e( 'Select glasstype' ); ?> --</option>
       <option value="1"><?php _e( 'Mat' ); ?></option>
       <option value="2"><?php _e( 'Glossy' ); ?></option>
    </select>
</ul><!--End config-steps-->

jQuery的:

$( "#config-steps #type" ).change( function() {
    var slct = $( this );
    var type = slct.children( ":selected" ).val()

    if( type === "" ) {
        slct.parents('li').find('.step-number').removeClass( 'unvalid-step' ).addClass( 'valid-step' ); 
    } else {
        slct.parents('li').find('.step-number').removeClass( 'valid-step' ).addClass( 'unvalid-step' );
    }

});

4 个答案:

答案 0 :(得分:0)

您需要使用控件上的val()而不是其子项。

替换以下代码:

var type = slct.children( ":selected" ).val()

有了这个:

var type = slc.val();

所以你将会:

$( "#config-steps #type" ).change( function() {
    var slct = $( this );
    var type = slct.val();

    if( type === "" ) {
        input.parents('li').find('.step-number').removeClass( 'unvalid-step' ).addClass( 'valid-step' );    
    } else {
        input.parents('li').find('.step-number').removeClass( 'valid-step' ).addClass( 'unvalid-step' );
    }

});

答案 1 :(得分:0)

你必须使用val()。它会为您提供所选的选项值。

这样做:

$( "#config-steps #type" ).change( function() {
    var slct = $(this);
    var type = slct.val();

    if( type === "" ) {
        input.parents('li').find('.step-number').removeClass( 'unvalid-step' ).addClass( 'valid-step' );    
    } else {
        input.parents('li').find('.step-number').removeClass( 'valid-step' ).addClass( 'unvalid-step' );
    }

});

你可以删除这样的额外变量:

var type = $(this).val();

<强>修:

$( "#config-steps #type" ).change( function() {


        if($(this).val() === "" ) {
            input.parents('li').find('.step-number').removeClass( 'unvalid-step' ).addClass( 'valid-step' );    
        } else {
            input.parents('li').find('.step-number').removeClass( 'valid-step' ).addClass( 'unvalid-step' );
        }

    });

答案 2 :(得分:0)

你应该只在你的选择元素上调用val()

尝试Fiddle

代码:

<select id="type">
       <option value="0">A</option>
       <option value="1">B</option>
       <option value="2"><?php _e( 'Glossy' ); ?></option>
    </select>

<input type="button" class="btn" value="Press"/>

$('.btn').click(function () {
  alert($("#type").val());
});

答案 3 :(得分:0)

通过 id

获取选择框值

<强>即

var type = $(“#type”)。val();

$( "#config-steps #type" ).change( function() {
    var type = $("#type").val(); //get Value by using its id

    if( type === "" ) {
        input.parents('li').find('.step-number').removeClass( 'unvalid-step' ).addClass( 'valid-step' );    
    } else {
        input.parents('li').find('.step-number').removeClass( 'valid-step' ).addClass( 'unvalid-step' );
    }

});
相关问题