📌  相关文章
📜  jquery select change get selected value - Javascript(1)

📅  最后修改于: 2023-12-03 15:16:44.088000             🧑  作者: Mango

Jquery Select Change Get Selected Value - JavaScript

When working with forms in JavaScript or jQuery, it is often necessary to retrieve the selected value of a dropdown list or select box. This can be done using the jQuery change event and the .val() method.

Using the jQuery Change Event

The jQuery change event is triggered when the selected option of a select box is changed.

$('select').on('change', function() {
  // code to retrieve selected value
});

In the example above, we are attaching the change event handler to all select elements on the page. When the change event is triggered, the anonymous function will be executed. This is where we can retrieve the selected value of the select box.

Retrieving the Selected Value

To retrieve the selected value of a select box, we can use the .val() method.

$('select').on('change', function() {
  var selectedValue = $(this).val();
});

In this example, $(this) refers to the select box that triggered the change event. We are then using the .val() method to retrieve the selected value and storing it in the selectedValue variable.

Putting it All Together

Here's a full example that shows how to use the jQuery change event and .val() method to retrieve the selected value of a select box:

// attach change event to all select elements on the page
$('select').on('change', function() {
  // retrieve selected value
  var selectedValue = $(this).val();

  // do something with selected value
  console.log(selectedValue);
});

In this example, we are attaching the change event handler to all select elements on the page. When the change event is triggered, we retrieve the selected value and log it to the console. You can replace the console.log(selectedValue) line with any code that needs to use the selected value.

By using the jQuery change event and .val() method, you can easily retrieve the selected value of a select box in JavaScript or jQuery.