简体   繁体   中英

HTML Select Tag with Javascript

I want to alert the value of a specific option in my dropdown when it is clicked. Here is my code:

$("select").change(function () {
    alert($("option").html());
});

I've tried using .text() and .val() , but neither seems to work.

Assuming you're not using a select[multiple] element, "The jQuery Way™" to get the value is:

$('select').change(function () {
  console.log($(this).val());
});

which really might as well be:

console.log(this.value);

The problem with your existing code is that $('option') selects all option elements, and then .html() gets the innerHTML of the first option element in the collection.

You don't want the first option on the page, you want the current value of the select element.

alert($(this).val());

我想这应该工作,如果您想要值而不是文本

Simple enough

$("select").change(function () {
    alert($(this).val());
});

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