我知道可以为HTML Select元素动态设置选定的选项,例如
$('#choose option:eq(2)').attr("selected", "selected");
,但是在特定情况下,我需要显式单击select的选项并将其选中。这可以实现吗,我在做错什么呢?
$("#clickme").on("click",function(){
var se=$("#choose");
se.show();
se[0].size=5;
//$('#choose option:eq(2)').attr("selected", "selected").change();
$('#choose option:eq(2)').click();
});
$('body').on('change','#choose', function() {
$('body').css('background', this.value);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<button id="clickme">Click Me To Open Select Box</button>
<select id="choose" name="choose" style=display:none;"">
<option value="red">Red</option>
<option value="blue">blue</option>
<option value="gold">gold</option>
</select>
答案 0 :(得分:0)
首先,您需要添加右键选择的道具。
$('#choose option:eq(2)').prop('selected', true).click();
第二,您需要将事件扩展(单击)到.ON,以更改背景颜色。
$('body').on('change, click','#choose', function() {
答案 1 :(得分:0)
我想这样做:
//<![CDATA[
/* external.js */
$(function(){
var choose = $('#choose'), bod = $('body');
choose.change(function(){
bod.css('background', $(this).val());
});
$('#clickme').click(function(){
choose.val('blue'); choose.show().change();
});
}); // end jQuery ready
/* external.css */
*{
box-sizing:border-box; padding:0; margin:0;
}
html,body{
width:100%; height:100%;
}
body{
position:relative; background:#ccc;
}
#test{
padding:10px;
}
#clickme{
padding:3px 5px; border:1px solid #aaa; border-radius:3px; margin-bottom:5px;
}
#choose{
display:none; clear:left;
}
#clickme,#choose{
float:left; cursor:pointer;
}
<!DOCTYPE html>
<html xmlns='http://www.w3.org/1999/xhtml' xml:lang='en' lang='en'>
<head>
<meta charset='UTF-8' /><meta name='viewport' content='width=device-width, height=device-height, initial-scale:1' />
<title>Test Template</title>
<link type='text/css' rel='stylesheet' href='external.css' />
<script src='https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js'></script>
<script type='text/javascript' src='external.js'></script>
</head>
<body>
<div id='test'>
<input id='clickme' type='button' value='Click Me To Open Select Box' />
<select id='choose' size='3'>
<option value='red'>Red</option>
<option value='blue'>Blue</option>
<option value='gold'>Gold</option>
</select>
</div>
</body>
</html>
答案 2 :(得分:0)
I have faced problem to that after alert message in the drop down, not able to re-populate previous value. Below is the solution, as we are dealing with Jquery then code should be in jquery only
function testfn()
{
$('#test').multiselect({
multiple : false,
header : false,
selectedList : 3,
minWidth : 100,
// noneSelectedText:"--Select--",
height : 100
});
}