jQuery get value of select onChange

2018-12-31 14:11发布

I was under the impression that I could get the value of a select input by doing this $(this).val(); and applying the onchange parameter to the select field.

It would appear it only works if I reference the ID.

How do I do it using this.

标签: jquery select
13条回答
旧人旧事旧时光
2楼-- · 2018-12-31 14:34
jQuery(document).ready(function(){

    jQuery("#id").change(function() {
      var value = jQuery(this).children(":selected").attr("value");
     alert(value);

    });
})
查看更多
忆尘夕之涩
3楼-- · 2018-12-31 14:38

This is helped for me.

For select:

$('select_tags').on('change', function() {
    alert( $(this).find(":selected").val() );
});

For radio/checkbox:

$('radio_tags').on('change', function() {
    alert( $(this).find(":checked").val() );
});
查看更多
深知你不懂我心
4楼-- · 2018-12-31 14:39

For all selects, invoke this function.

$('select').on('change', function()
{
    alert( this.value );
});

For only one select:

$('#select_id') 
查看更多
梦醉为红颜
5楼-- · 2018-12-31 14:39
$('select_id').on('change', function()
{
    alert(this.value); //or alert($(this).val());
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>

<select id="select_id">
    <option value="1">Option 1</option>
    <option value="2">Option 2</option>
    <option value="3">Option 3</option>
    <option value="4">Option 4</option>
</select>
查看更多
不流泪的眼
6楼-- · 2018-12-31 14:41

You can try this (using jQuery)-

$('select').on('change', function()
{
    alert( this.value );
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>

<select>
    <option value="1">Option 1</option>
    <option value="2">Option 2</option>
    <option value="3">Option 3</option>
    <option value="4">Option 4</option>
</select>

Or you can use simple Javascript like this-

function getNewVal(item)
{
    alert(item.value);
}
<select onchange="getNewVal(this);">
    <option value="1">Option 1</option>
    <option value="2">Option 2</option>
    <option value="3">Option 3</option>
    <option value="4">Option 4</option>
</select>

查看更多
柔情千种
7楼-- · 2018-12-31 14:42

Look for jQuery site

HTML:

<form>
  <input class="target" type="text" value="Field 1">
  <select class="target">
    <option value="option1" selected="selected">Option 1</option>
    <option value="option2">Option 2</option>
  </select>
</form>
<div id="other">
  Trigger the handler
</div>

JAVASCRIPT:

$( ".target" ).change(function() {
  alert( "Handler for .change() called." );
});

jQuery's example:

To add a validity test to all text input elements:

$( "input[type='text']" ).change(function() {
  // Check input( $( this ).val() ) for validity here
});
查看更多
登录 后发表回答