Javascript 如果使用prop在输入框中输入空格,则禁用按钮
我创建了一个函数,当按钮为空时禁用按钮,但如果输入只有空格,我想禁用它。下面是我的代码,但我无法理解如何将其添加到jquery代码中 HTMLJavascript 如果使用prop在输入框中输入空格,则禁用按钮,javascript,jquery,Javascript,Jquery,我创建了一个函数,当按钮为空时禁用按钮,但如果输入只有空格,我想禁用它。下面是我的代码,但我无法理解如何将其添加到jquery代码中 HTML <input type="text" maxlength="200" style="margin-left: 0;" name="Name" id="Name" value="" /> <button type="add" name="btnadd" class="actionButton" disabled="disabled">
<input type="text" maxlength="200" style="margin-left: 0;" name="Name" id="Name" value="" />
<button type="add" name="btnadd" class="actionButton" disabled="disabled">
<span>Add Name</span></button>
对该值使用trim删除所有尾随空格。这样你就可以随时检查它是否是空的
If (!$("#Name").val().trim().length) {
// disable button
}
Trim删除字符串开头或结尾的所有空白。因此,您只需要检查修剪值是否有任何长度,并且它应该处理空值和仅带空格的值
更新 如果要在输入字符串开头有空格时禁用该按钮,则需要一个正则表达式
var val = $('#Name').val()
// this condition checks if there's whitespace at the beginning
// or if the string is empty
// if either is true we disable the button
if (/^\s/.test(val) || !val.trim().length) {
// disable the button
}
使用此新条件,您无需检查
val==''
。这是由处理的!val.trim().length
短正则表达式可以测试输入字符串是否包含除空格以外的任何内容
if (/[^\s]/.test($('#Name').val()))
$('button.actionButton').prop('disabled', false);
else
$('button.actionButton').prop('disabled', true);
或者对于单行表达式
$('button.actionButton').prop('disabled', !(/[^\s]/.test($('#Name').val())));
使用.attr()尝试类似的操作。
$(文档).ready(函数(){
$('input[type=“submit”]”)。attr('disabled',true);//最初按钮被禁用
$('#Name')。在('keyup',function()上{
var text_value=$(“#Name”).val();
如果(!text_value.trim().length){
$('input[type=“submit”]”)。attr('disabled',true);
}否则{
$('input[type=“submit”]”)。attr('disabled',false);
}
});
});代码>
也发布您的HTML。我们需要一个函数,您需要在$('#Name').val().trim()之后添加trim()方法;要删除字符串两侧的空白,我曾尝试添加if($('#Name').val()=''|$('#Name').val().trim()){
,但没有效果。还有其他选择吗?@j08691根据您的请求更新了我的描述您输入的代码不是纯javascript,而是jquery。我曾尝试添加if($('#Name').val()==''||$('#名称').val().trim()){
但这对我来说不起作用。还有其他选择吗?对不起,我没有添加整个条件。更新答案以反映。这是可行的,但如果在几个空格后,如果文本输入按钮被启用。我如何解决这个问题。我已经更新了我的描述以显示我是如何做的。如果他们输入了非空白字符,那么输入就可以s是一个值,因此应该启用该按钮。您是说如果输入值中的任何位置都有空格,则希望禁用该按钮吗?如果字符示例“text”前面有空格,则不在任何位置,但至少在/[^\s]/.test($('#Name').val()时,您的第一个代码段是错误的
按钮被启用,而不是禁用。但如果您输入的空格很少,则如果您输入的文本按钮将被启用。如何解决此问题,请忽略文本开头的空格。
$('button.actionButton').prop('disabled', !(/[^\s]/.test($('#Name').val())));