简体   繁体   中英

How to alert the selected option using javascript or jquery?

I am using a select tag in my code, here is my code,

<select onchange="test(this);">
    <option value="0">Select</option>
    <option value="1">Select1</option>
    <option value="2">Select2</option>
    <option value="3">Select3</option>
</select>

and javascript code is here,

<script>
  function test(obj)
  {
     alert($(obj).val()); 
  }
</script>

I want to alert the selected text here, If I use the above code the value of the selected option is coming, but I want to alert the text of the selected option can anyone tell to achive this one. I want to alert it without using any class or id.
I want to alert it only through the obj.

I am waiting for your help.

Thanks In advance

This should do the trick...

alert($(obj).find("option:selected").text());

That uses the jQuery object $(obj) , like you already had, but does a find() which searches the child elements, in this case the selected option .

jQuery find()

:selected pseudo-selector

尝试这个..

alert($(obj).find("option:selected").text());

you can try this:

alert($(obj).find('option').eq(obj.value).text()); 

Working jsFiddle

<select id="someid" onchange="test();">
    <option value="0">Select</option>
    <option value="1">Select1</option>
    <option value="2">Select2</option>
    <option value="3">Select3</option>
</select>

javascript>

function test(){
   var elem = document.getElementById("someid"),

    var selectedNode = elem.options[elem.selectedIndex].text;
    alert(selectedNode );
}

jQuery>

$("#someid").change(){
    alert($(this).find("option:selected").text());
 }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM