需要帮助从列表项中获取文本并放入输入框

时间:2015-02-23 21:30:28

标签: javascript jquery html css

我有以下html代码,下拉列表是

                        <div class="input-group m-bot15">
                            <input type="text" class="form-control round-input" id="textbox1">
                            <div class="input-group-btn">

                                <button tabindex="-1" data-toggle="dropdown" class="btn btn-info dropdown-toggle" type="button">
                                    <span class="caret"></span>
                                </button>
                                <ul role="menu" class="dropdown-menu pull-right">
                                    <li><a href="#">1</a></li>

                                    <li class="divider"></li>
                                    <li><a href="#" >2</a></li>
                                    <li><a href="#">3</a></li>
                                    <li><a href="#">4</a></li>
                                    <li class="divider"></li>

                                    <li><a href="#">5</a></li>
                                    <li class="divider"></li>
                                    <li><a href="#">6</a></li>
                                    <li><a href="#">7</a></li>
                                    <li class="divider"></li>
                                </ul>
                            </div>
                        </div>
                    </div>
                </div>

我正试图这样做,当我点击1时,它会将“1”放入使用Javascript推荐的人中。

这是我到目前为止所尝试的:

<li onmousedown="transferText(one)" id="one">1</li>

现在也添加输入文本和id,例如textBox

<script>
function transferText(listItem) {
    document.getElementById(textBox).innerHTML = document.getElementById(listItem).innerHTML;
}
</script>

2 个答案:

答案 0 :(得分:0)

var inputGroup = $('.input-group');

// Bind a click event to all elements with the selector ".dropdown-menu a" 
// within ".input-group" to an anonymous function that will insert the text
// value into the input. 
inputGroup.on('click', '.dropdown-menu a', function(event)
{
    // event = jQuery click event
    // this = The anchor that was clicked
    event.preventDefault();

    // Get the text value of the anchor and set it as the input value
    inputGroup.find('#textbox1').val($(this).text());
}

答案 1 :(得分:0)

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script>
<script>
    $(document).ready(function() {
        $('a', 'ul.dropdown-menu').click(function() {
            $('#textbox1').val($(this).text());
            return false;
        });
    });
</script>