Hi, I am dynamically changing the list in the ul-li HTML tag. All I need to do is get the value of the selected li corresponding to ul. I tried all the possible jquery methods that I have, but still I get undefined. I inhabit 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:
<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:
function doSelection(){ var id = $('#option1 li.selected').attr('value'); alert(id); }
The problem is that I get 'undefined' for the id value.
UPDATE
As you all suggested, I changed my code as:
Filling ul like:
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 like:
<div class="cate-map"> <ul id="option1" onclick="doSelection()"> </ul> </div>
Onclick function like:
function doSelection(){ alert($('#option1 li.selected').attr('data-input')); }
Now I get the value as a warning, but always get the first element as a warning. Whatever item I choose, I always get the first item in the list. Please, help.
source share