gpt4 book ai didi

javascript - 当jquery将变量插入该字段时,如何检查输入字段是否为空?

转载 作者:行者123 更新时间:2023-12-03 01:00:47 25 4
gpt4 key购买 nike

我想检查输入字段是否为空,然后从另一个元素(div)添加/删除类。因为现在我正在使用jquery“输入”处理程序,所以当有人在其中输入文本时,或者即使他在其中复制/粘贴某些内容时,我可以检查该字段是否为空。

我的问题是,当我尝试使用下面的代码在字段中传递文本时,它无法正常工作。

请检查下面我的代码:

$('.home-page-address-field').on('input', function(){
if($('#s').val() == '' ) {
$("#location-btn").addClass('disable2');
}else {
$("#location-btn").removeClass('disable2');
}

});

var cityA = "London";
alert('The var "cityA" will be inserted to the field and the class "disable2" should be removed from the Browse button but it is not !');

$(function () {
$('.home-page-address-field').val(cityA);
});
.home-page-address-field {
height:30px;
margin-right:15px;
border:1px solid #ccc;
padding:0px 8px;
}


.browse-button {
padding:5px;
height:25px;
background:#0088cc;
color:#fff;
display:inline-block;
width:120px;
text-align:center;
}

.disable2{
opacity:0.4;
pointer-events:none;
background:gray;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<input id="s" placeholder="Enter your city..." class="home-page-address-field"/>

<div id="location-btn" class="disable2 browse-button">BROWSE</div>

最佳答案

以编程方式更改 val() 不会触发任何事件处理程序。为此,您可以使用 .trigger():

$('.home-page-address-field').on('input', function(){
if($('#s').val() == '' ) {
$("#location-btn").addClass('disable2');
}else {
$("#location-btn").removeClass('disable2');
}

});

var cityA = "London";
alert('The var "cityA" will be inserted to the field and the class "disable2" should be removed from the Browse button but it is not !');

$(function () {
$('.home-page-address-field').val(cityA).trigger('input');
});
.home-page-address-field {
height:30px;
margin-right:15px;
border:1px solid #ccc;
padding:0px 8px;
}


.browse-button {
padding:5px;
height:25px;
background:#0088cc;
color:#fff;
display:inline-block;
width:120px;
text-align:center;
}

.disable2{
opacity:0.4;
pointer-events:none;
background:gray;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<input id="s" placeholder="Enter your city..." class="home-page-address-field"/>

<div id="location-btn" class="disable2 browse-button">BROWSE</div>

关于javascript - 当jquery将变量插入该字段时,如何检查输入字段是否为空?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52632368/

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