Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jquery $(this).attr(…) returns undefined

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/

like image 686
Jakob Jingleheimer Avatar asked Jul 11 '26 10:07

Jakob Jingleheimer


1 Answers

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);
});
like image 71
Rob W Avatar answered Jul 14 '26 01:07

Rob W



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!