I have a simple JQuery code.
$(document).ready(function() {
$( ".translanguage" ).change(function() {
var value = $(this).attr("langid");
alert(value);
});
});
and i have html code.
<select name="translanguage" class="translanguage">
<option value="0">Please Select Language</option>
<option class="transoption" value="1" langid="1">Urdu</option>
<option class="transoption" value="2" langid="2">English</option>
<option class="transoption" value="3" langid="3">Arabic</option>
<option class="transoption" value="4" langid="4">Sindhi</option>
</select>
When i run this program, it is giving undefined error in alert box. I need the value of langid as given in my option tage.
So what is the problem in my code. ?
Secondly what is the cause of undefined error in JQuery.
Thanks
I have a simple JQuery code.
$(document).ready(function() {
$( ".translanguage" ).change(function() {
var value = $(this).attr("langid");
alert(value);
});
});
and i have html code.
<select name="translanguage" class="translanguage">
<option value="0">Please Select Language</option>
<option class="transoption" value="1" langid="1">Urdu</option>
<option class="transoption" value="2" langid="2">English</option>
<option class="transoption" value="3" langid="3">Arabic</option>
<option class="transoption" value="4" langid="4">Sindhi</option>
</select>
When i run this program, it is giving undefined error in alert box. I need the value of langid as given in my option tage.
So what is the problem in my code. ?
Secondly what is the cause of undefined error in JQuery.
Thanks
Share Improve this question asked Nov 28, 2013 at 12:17 Muhammad Rizwan Kaim KhaniMuhammad Rizwan Kaim Khani 2,0803 gold badges30 silver badges38 bronze badges 1 |4 Answers
Reset to default 11Inside the change handler this
refers to the select
element, but the langid
is in the selected option
element. So you need to find the selected option
and then call .attr("langid")
on that element
jQuery(function () {
$(".translanguage").change(function () {
var value = $(this).find('option:selected').attr("langid");
alert(value);
});
})
Demo: Fiddle
This script will work for you. See jsfiddle
$(function () {
$(".translanguage").change(function () {
var value = $( "select option:selected" ).attr("langid");
alert(value);
});
})
try something like this
$( ".translanguage" ).change(function() {
alert(this.options[this.selectedIndex].getAttribute('langid'));
});
try this:
// jquery wont find the attr of langid, change the langid to id in html.
$(document).ready(function() {
$( ".translanguage" ).change(function() {
var value = $(this).attr("id");
alert(value);
});
});
data-
in front of your custom attributes:data-langid="1"
. Then it's valid HTML5 – nbar Commented Nov 28, 2013 at 12:36