我是jquery的新手,我的任务是创建一个onclick函数,该函数从下拉列表获取值并输入到搜索框中。对此有任何建议将非常感激。我在下面列出了我目前的代码。
<script>
function populateSearch(e) {
//alert('wibble')
var $selector = $(e.target);
var searchVal = $selector.attr('data-value');
//alert($selector.attr('data-value'));
var $originalSelects = $originalDiv.find('select');
}
</script>
<div class="col-md-6">
<button class="btn btn-primary dropdown-toggle" type="button" data-toggle="dropdown">
Dropdown Example
<span class="caret"></span>
</button>
<ul class="quickSearch dropdown-menu">
<li onclick="populateSearch(event);" data-value="Goodbye Mo">option 1</li>
<li onclick="populateSearch(event);" data-value="Hello Mo">option 2</li>
<li onclick="populateSearch(event);" data-value="adios Mo">option 3</li>
<li onclick="populateSearch(event);" data-value="Mo">option 4</li>
</ul>
</div>
答案 0 :(得分:0)
你快到了。您需要做的就是添加一个输入元素,然后使用以下内容设置其值:$("#myInput").val(searchVal);
此处myInput
是输入的ID。
另外,请注意我已在您的点击处理程序中注释掉了最后一行代码。这是因为您的Javascript中未定义$originalDiv
变量。所以留下它会导致错误。
function populateSearch(e) {
//alert('wibble')
var $selector = $(e.target);
var searchVal = $selector.attr('data-value');
//alert($selector.attr('data-value'));
$("#myInput").val(searchVal);
//var $originalSelects = $originalDiv.find('select');
}
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div class="col-md-6">
<button class="btn btn-primary dropdown-toggle" type="button" data-toggle="dropdown">
Dropdown Example
<span class="caret"></span>
</button>
<ul class="quickSearch dropdown-menu">
<li onclick="populateSearch(event);" data-value="Goodbye Mo">option 1</li>
<li onclick="populateSearch(event);" data-value="Hello Mo">option 2</li>
<li onclick="populateSearch(event);" data-value="adios Mo">option 3</li>
<li onclick="populateSearch(event);" data-value="Mo">option 4</li>
</ul>
</div>
<input id="myInput" type="text" />
&#13;
答案 1 :(得分:0)
//bind a click handler to all the lis
$('.quickSearch li').on('click', function(e){
//get the attribute value off the li clicked and put it in the target value
$('#target').val(e.target.getAttribute('data-value'));
});
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="col-md-6">
<ul class="quickSearch dropdown-menu">
<li data-value="Goodbye Mo">option 1</li>
<li data-value="Hello Mo">option 2</li>
<li data-value="adios Mo">option 3</li>
<li data-value="Mo">option 4</li>
</ul>
</div>
<input type="text" id="target" value="">
&#13;
答案 2 :(得分:0)
Thank you everyone for providing me with some answers. My manager was able to give me some good advice and I have listed the solution he proposed below:
<script>
function populateSearch(e) {
var $selector = $(e.target);
var searchVal = $selector.attr('data-value');
$('form[name="siteSearch"]').find('input#searchPhrase').val(searchVal);
$('form[name="siteSearch"]').submit();
}
</script>