2010-09-18 119 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); 
    } 
}