gpt4 book ai didi

javascript - 选择下拉菜单时触发 Jquery 事件(而不是更改下拉菜单值)

转载 作者:行者123 更新时间:2023-12-03 04:56:41 24 4
gpt4 key购买 nike

嗨,我有一个 jquery 函数,我想在选择下拉值时触发该函数(不是在单击它时,也不是在更改它时 - 而是在选择任何值时)

这是 html

<select class="addpropertyinput" name="property_availablefor" id="property_availablefor" required>
<option value="">Available for</option>
<option value="Rent">Rent</option>
<option value="Sale">Sale</option>
</select>
<div class="errormsg" id="errormsg3"></div>

Jquery

var validate_property_availablefor = function()
{
var item3 = $("#property_availablefor").val();
$("#errormsg14").html("")
$("#errormsg21").html("")
if (item3 == '')
{
$("#errormsg3").html("Please Select Available For")
property_availablefor = "";
}
else
{
$("#errormsg3").html("")
property_availablefor = item3;
}
}

$("#property_availablefor").on('change', validate_property_availablefor);

现在我可以用“单击”或“聚焦”替换“更改”,但这并不能完美解决问题,因为一旦单击或聚焦,它就会触发。当在下拉列表中选择值时我需要触发它。未更改,单击下拉菜单时未更改。仅当选择下拉值时。

最佳答案

<option>并非所有浏览器都支持事件(我只确认它适用于 Firefox)。保留当前的更改事件,但还添加一个仅在选择为空白时响应的单击事件:

var validate_property_availablefor = function()
{
var item3 = $("#property_availablefor").val();
$("#errormsg14").html("")
$("#errormsg21").html("")
if (item3 == '')
{
$("#errormsg3").html("Please Select Available For")
property_availablefor = "";
}
else
{
$("#errormsg3").html("")
property_availablefor = item3;
}
}

$("#property_availablefor").on('change', validate_property_availablefor);

$("#property_availablefor option").on('click', function(event){
var selectedVal = $(this).val();
console.log(selectedVal);
if (selectedVal === '')//only do something when it's blank
{
$("#errormsg3").html("Please Select Available For")
property_availablefor = "";
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select class="addpropertyinput" name="property_availablefor" id="property_availablefor" required>
<option value="">Available for</option>
<option value="Rent">Rent</option>
<option value="Sale">Sale</option>
</select>
<div class="errormsg" id="errormsg3"></div>

关于javascript - 选择下拉菜单时触发 Jquery 事件(而不是更改下拉菜单值),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42406275/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com