Hi I am poulating a list in ul - li HTML tag dynamically. All I need is to get value of selected li of corresponding ul. I tried all possible jquery methods I got but still i am getting undefined.I am populating ul - li as:
jQuery.get(url, function(data) {
for(i=0;i<data.length;i++){
//console.log(data[i]) //"+data[i]+"
msg = "<li> <a href=#>"+data[i]+"</a></li>";
document.querySelector('#option1').innerHTML += msg;
}
});
HTML section is as:
<body>
<div class="wrap">
<div class="content">
<div class="cate-map">
<ul id="option1" onclick="doSelection()">
</ul>
</div>
</div>
<div class="content2">
<div class="cate-map">
<ul id="option2">
</ul>
</div>
</div>
<div class="clear"></div>
<div class="content3"> <textarea id="content4"></textarea>
</div>
</div>
</body>
onclick method is as :
function doSelection(){
var id = $('#option1 li.selected').attr('value');
alert(id);
}
Problem is that I am getting 'undefined' for id value.
UPDATE
As you all suggested I changed my code as:
Populating ul as:
jQuery.get(url, function(data) {
for(i=0;i<data.length;i++){
msg = "<li data-input="+data[i]+" class='selected'> <a href=#>"+data[i]+"</a></li>";
document.querySelector('#option1').innerHTML += msg;
}
});
HTML ul as:
<div class="cate-map">
<ul id="option1" onclick="doSelection()">
</ul>
</div>
Onclick function as:
function doSelection(){
alert($('#option1 li.selected').attr('data-input'));
}
Now I am getting a value as alert but I am getting the first element as alert always. Whichever element I click still always getting the first element of list. Please do help.
<li>
elements do not havevalue
attributes. – Frédéric Hamidiselected
and avalue
to the wantedli
? – Ninitali
that has classnameselected
. – Leo<li>
actually hasvalue
attribute, if its parent is<ol>
w3.org/TR/html-markup/li.html#li.attrs.value off-topic though – Leo