gpt4 book ai didi

javascript - 如何避免文本框中出现空值

转载 作者:行者123 更新时间:2023-11-28 04:45:28 25 4
gpt4 key购买 nike

    $(document).on("click", "label.radeem-textbox", function () {
var txt = $(".mytxt").text();
$(".radeem-textbox").replaceWith("<input class='radeem-textbox redeem-textbox'/>");
$(".radeem-textbox").val(txt);
return false;
});

$(document).on("blur", "input.radeem-textbox", function () {
var txt = $(this).val();
$(this).replaceWith("<label class='radeem-textbox'></label>");
$(".radeem-textbox").text(txt);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.3/jquery.min.js"></script>
<a href="javascript:void(0)" class="right-side-margin-top right-side-margin-bottom display-block add-to-wishlist">

<label class="add-to-wish radeem-textbox">Redeem a Coupon</label>
</a>

我有 jquery 代码,用于在单击时将标签转换为文本框。但是当我没有在文本框上输入任何内容时,文本框和标签没有显示..那么如果没有输入任何内容如何使文本框聚焦..

<label  class="add-to-wish radeem-textbox">Redeem a Coupon</label>



<script type="text/javascript">
$(document).on("click", "label.radeem-textbox", function () {
var txt = $(".mytxt").text();
$(".radeem-textbox").replaceWith("<input class='radeem-textbox'/>");
$(".radeem-textbox").val(txt);
return false;
});

$(document).on("blur", "input.radeem-textbox", function () {
var txt = $(this).val();
$(this).replaceWith("<label class='radeem-textbox'></label>");
$(".radeem-textbox").text(txt);
});

最佳答案

添加 if(txt.trim())trim()它将验证输入框是否为空。它只允许它不是 empty,null

$(document).on("click", "label.radeem-textbox", function () {
var txt = $(".mytxt").text();
$(".radeem-textbox").replaceWith("<input class='radeem-textbox'/>");
$(".radeem-textbox").val(txt);
return false;
});

$(document).on("blur", "input.radeem-textbox", function () {
var txt = $(this).val();
if(txt.trim()){
$(this).replaceWith("<label class='radeem-textbox'></label>");
$(".radeem-textbox").text(txt);
}
else{
console.log('enter text please')

}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<label class="add-to-wish radeem-textbox">Redeem a Coupon</label>

替代 方法是:使用标签更新 contenteditable和你的一样

<label contenteditable="true">Click me to edit me</label>

关于javascript - 如何避免文本框中出现空值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40988627/

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