SOLVED! actually the problem was in $(document).ready(function(){//}); after i used it, it worked fine. thanks for your help and sorry because of such silly mistake.
I'm trying to get selected li from bootstrap dropdown menu. It works but when i want to get the text of selected li, it shows nothing.
<div class="btn-group">
<a class="btn dropdown-toggle" data-toggle="dropdown" href="#">
<font id="dropdownMenu" >inch</font>
<span class="caret"></span>
</a>
<ul id="dropdownList" class="dropdown-menu">
<li><a href="#">inch</a></li>
<li><a href="#">cm</a></li>
<li><a href="#">mm</a></li>
</ul>
</div>
js:
$('#dropdownList li').click(function () {
console.log($(this).text());
document.getElementById('dropdownMenu').innerHTML = $(this).text();
});
May i know why it's not working?
Thanks!
Get the text of an anchor tag inside. That's the element with text.
$('#dropdownList li').click(function () {
console.log($(this).find('a').text());
document.getElementById('dropdownMenu').innerHTML = $(this).find('a').text();
});
Use Jquery:
$('#dropdownList li').click(function () {
console.log($(this).text());
$('#dropdownMenu').text($(this).text());
});
You should try to limit DOM reading/writing, like using .find()
and the .text()
etc. I would add some data in the markup
HTML:
<ul id="dropdownList" class="dropdown-menu">
<li data-value="inch"><a href="#">inch</a></li>
<li data-value="cm"><a href="#">cm</a></li>
<li data-value="mm"><a href="#">mm</a></li>
</ul>
JS:
$('#dropdownList li').click(function () {
console.log($(this).data('value'))
})
Two things:
data-*
are valid HTML5 tags that you can use to fit your needs. var dropdownValue = $('#value')
.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.