Reputation: 15374
I am trying to implement some Jquery that basically says "If this text field is filled in then disable the submit button so that the form cannot be delivered/submitted"
So far I have come up with this, but it is not working
$(document).ready(function(){
$this = $("#inputValue");
if($this.val().length>0){
$('input[type=submit]').attr('disabled', 'disabled');
}
});
When i fill in the form and include text within the field I am not supposed to the form still gets submitted, what am i doing wrong?
Thanks
Upvotes: 0
Views: 1575
Reputation: 21
Try using this code.
$('input[type=submit]').attr("disabled", true);
Upvotes: -2
Reputation: 881
Your code only runs once on runtime. After that, it doesn't get checked again.
$(document).ready(function (){
$("#inputValue").on('change', function (){
if($(this).val().length > 0){
$('input[type=submit]').attr('disabled', 'disabled');
} else {
$('input[type=submit]').removeAttr('disabled');
}
});
});
Or, as @thomasfedb suggested:
$(document).ready(function (){
$('#inputValue').on('change', function() {
$("input[type=submit]").prop('disabled', $(this).val().length > 0);
});
});
Upvotes: 3
Reputation: 20250
Since you're using a hidden
field it might be better to bind the change
event:
$('#inputValue').on('change', function() {
$('input[type="submit"]').prop('disabled', this.value.length > 0);
}).change();
Upvotes: 1
Reputation: 145398
I'd suggest you to bind a keyup
event to do the check every time when user enters something to #inputValue
field:
$(document).ready(function() {
$("#inputValue").on("keyup", function() {
$("input[type=submit]").prop("disabled", !!$.trim(this.value).length);
}).trigger("keyup");
});
Upvotes: 1