2010-09-18 86 views
8

我有一个问题试图实现这个结果,我需要的几乎是禁用提交按钮,直到在输入字段中输入文本。我尝试了一些功能,但没有结果。请如果你能帮助我,这将是非常感激。如何在输入字段中输入文本之前禁用提交按钮?

HTML标记

<form action="" method="get" id="recipename"> 
<input type="text" id="name" name="name" class="recipe-name" 
    value="Have a good name for it? Enter Here" 
    onfocus="if (this.value == 'Have a good name for it? Enter Here') {this.value = '';}" 
    onblur="if (this.value == '') {this.value = 'Have a good name for it? Enter Here';}" 
/> 
<input type="submit" class="submit-name" value="" /> 
</form> 

谢谢提前。

回答

5

您可以使用此javascript函数:

var initVal = "Have a good name for it? Enter Here"; 
$(document).ready(function(){ 
    $(".submit-name").attr("disabled", "true"); 
    $(".recipe-name").blur(function(){ 
     if ($(this).val() != initVal && $(this).val() != "") { 
      $(".submit-name").removeAttr("disabled"); 
     } else { 
      $(".submit-name").attr("disabled", "true");   
     } 
    });  
}); 

jsfiddle

+0

这是我一直在寻找的答案,非常感谢您的帮助。 – Ozzy 2010-09-18 14:59:16

+1

@Ozzy:不客气 – Topera 2010-09-18 15:03:20

1

调用一些像下面(例如给jQuery的)在onkeyup事件

function handleSubmit() 
{ 
if($.trim($('#name').val() == '')) 
{ 
$('.submit-name').attr('disabled','disabled'); 
} 
else 
{ 
$('.submit-name').attr('disabled',''); 
} 
} 
0
$("#textField").keyup(function() { 
    var $submit = $(this).next(); // or $("#submitButton"); 
    if(this.value.length > 0 && this.value != "Default value") { 
     $submit.attr("disabled", false); 
    } else { 
     $submit.attr("disabled", true); 
    } 
}); 
1

你可以试试这个:

var nameText = $("#name"); 

nameText.attr("disabled", "disabled"); 

nameText.change(function() { 
    if(nameText.val().length > 0) { 
    nameText.attr("disabled", ""); 
    } else { 
    nameText.attr("disabled", "disabled"); 
    } 

}); 
+1

不要忘记在检查长度前先调整数值 – 2013-10-17 07:21:32

5

与accpeted解决方案的唯一的问题是,焦点从文本字段中删除后,才按钮被激活(在之后进入它当然数据)。一旦在该字段中输入任何文本,该按钮是否应该启用?这是实现这个的解决方案。

链接到其他的解决方案:Keep button disabled if text is not entered

是这样的:

$('.recipe-name').on("keyup", action); 
function action() { 
    if($('.recipe-name').val().length > 0) { 
     $('#submit-name').prop("disabled", false); 
    }else { 
     $('#submit-name').prop("disabled", true); 
    } 
}