So, I am trying to grab the value of selected option when user selects something as shown in the JSFiddle below:
Let’s say I select Jack or Nicole and run the script, it always prints Peter which I think is because page is getting refreshed. How can I make sure that it prints the one I selected?
Your event is firing on page load, and at pageload, a select element without a predefined “selected” option will default to having the value of the first option selected for display.
As chorn points out, your script should be called after a change has occured to the select element, or at some later point in the execution cycle, once the select box has been updated.
Note on Fiddle: Clicking the ‘Run’ button re-renders the page, meaning the select will have returned to its default state before your code runs.
Currently the script is running before you have the opportunity to interact with the select element.
You need to tell the script to only run when you’ve changed the select element.
You can do with with:
$(".owner-name").on("change", function () {
var option = $("option:selected", this);
alert(option.text());
});
Or possibly even more readable is to use the find method:
$(".owner-name").on("change", function () {
var option = $(this).find("option:selected");
alert(option.text());
});
However I prefer to do it without the this keyword, for clarity, so we can use the event target instead:
$(".owner-name").on("change", function (evt) {
var option = $(evt.target).find("option:selected");
alert(option.text());
});