选择值时,select2 alert selected选项 [英] select2 alert selected option when selecting the value
问题描述
在select2中如何提醒选择多重选择的选项?
这是我选择select2选项时的触发代码:
< script>
$(#list)。select2();
$('#list')。on(select2-selecting,function(e){
alert(this.value);
});
< / script>
这只会提醒已选择的值。不是我选择的选项。
我也不能这样做:
var test = $('#list')。val();
alert(test);
因为它只会提醒已选择的选项。
我想要的是提醒仍在被选中的选项。因此,如果您单击下拉列表并选择一个选项,它将提醒该选项的值。
默认选择第一个选项。对不起,我忘了提这个
选择值
: / p>
$(this).find('option:selected')
或多次
使用:
$(本).VAL();
像这样使用:
< script>
$('#list')。on(select2-selecting,function(e){
var val = $(this).val();
alert(val);
});
< / script>
示例:
$(#list)。select2(); $('#list')。on(change,function (e){var val = $(this).val(); alert(val);});
#list {width:200px;}
< script src =https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js>< / script>< link rel =stylesheethref =https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.5/css/select2.min.css/>< script src =https:// cdnjs .cloudflare.com / ajax / libs / select2 / 4.0.5 / js / select2.min.js>< / script>< select id =listmultiple> < option value =1selected> 1< / option> < option value =2> 2< / option> < option value =3> 3< / option>< / select>
In select2 how can I alert the option being selected for a multiple select?
This is my code for trigger when select2 option is being selected:
<script>
$("#list").select2();
$('#list').on("select2-selecting", function(e) {
alert(this.value);
});
</script>
This will only alert the already selected value. Not the option that I am selecting.
I can't also do this:
var test = $('#list').val();
alert(test);
Since it will only alert the already selected options as well.
What I want is to alert the option that is still being selected. So if you click the drop-down and select an option it will alert the value of that option.
The first option is selected by default. Sorry I forgot to mention this
Get selected value
with:
$(this).find('option:selected')
Or for multiple
use:
$(this).val();
Use like this:
<script>
$('#list').on("select2-selecting", function(e) {
var val = $(this).val();
alert(val);
});
</script>
Example:
$("#list").select2();
$('#list').on("change", function(e) {
var val = $(this).val();
alert(val);
});
#list {
width: 200px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.5/css/select2.min.css" />
<script src="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.5/js/select2.min.js"></script>
<select id="list" multiple>
<option value="1" selected>1</option>
<option value="2">2</option>
<option value="3">3</option>
</select>
这篇关于选择值时,select2 alert selected选项的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!