Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
332 views
in Technique[技术] by (71.8m points)

javascript - Get selected item value from Bootstrap DropDown with specific ID

I am "creating" my own "ComboBox" using Bootstrap 3 and JavaScript. Here is the JSFiddle for what I have so far:

HTML:

<div class="input-group">                                            
    <input type="TextBox" ID="datebox" Class="form-control"></input>
    <div class="input-group-btn">
        <button type="button" class="btn dropdown-toggle" data-toggle="dropdown">
            <span class="caret"></span>
        </button>
        <ul id="demolist" class="dropdown-menu">
            <li><a href="#">A</a></li>
            <li><a href="#">B</a></li>
            <li><a href="#">C</a></li>
        </ul>
    </div>
</div>

JavaScript:

$(document).on('click', '.dropdown-menu li a', function() {
    $('#datebox').val($(this).html());
}); 

This approach works great untill I want to repeat this "ComboBox" several times on the page. The issue is with the JQuery function looking for ANY/ALL '.dropdown-menu li a'.

How can I change my JQuery to look only for UL with ID demolist and get its selected value?

I have tried the following without success:

I tried '#demolist .dropdown-menu li a' but that will not fire the function:

$(document).on('click', '#demolist .dropdown-menu li a', function() {
    $('#datebox').val($(this).html());
}); 

I tried calling the Click of #demolist but #datebox gets the HTML of ALL list item of #demolist and not the selected innerHTML of item:

$('#demolist').on('click', function(){
    $('#datebox').val($(this).html());
});

UPDATE:

The working solutions are:

$('#demolist li a').on('click', function(){
    $('#datebox').val($(this).html());
});

OR

$('#demolist li').on('click', function(){
    $('#datebox').val($(this).text());
});
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)
$('#demolist li').on('click', function(){
    $('#datebox').val($(this).text());
});

http://jsfiddle.net/kcpma/18/


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...