I'm trying to get the title of an option element, but it keeps returning undefined. This also happens for $(this).attr("name")…and $(this).attr("value"), but curiously $(this).val() works (as expected). Yet, I'm able to set the value with $(this).attr("value", "baz").
Fiddle: http://jsfiddle.net/jshado1/JgAJC/1/
this points to the <select> element. For the selected option, use:
this.options[this.selectedIndex]
Full code (you can safely unwrap $opt's jquery wrapper, and use $opt.title and $opt.name, these are safe across all browsers):
$('select').change(function() {
var $opt = $(this.options[this.selectedIndex]),
t = $opt.attr("title"),
n = $opt.attr("name"),
v = this.value;
$("#name").text("name: "+n);
$("#title").text("title: "+n);
$("#value").text("value: "+v);
});
Another method, the jQuery-way is:
$('select').change(function() {
var $opt = $(this).children(':selected'),
t = $opt.attr("title"),
n = $opt.attr("name"),
v = this.value;
$("#name").text("name: "+n);
$("#title").text("title: "+n);
$("#value").text("value: "+v);
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With