I have an HTML form with multiple inputs. Some have the class required
.
I want to show the "submit" button once all of these fields have a value.
I tried using:
$(document).ready(function() {
$("#submit_button").hide();
$('.required').on('keyup', function () {
if($(this).val() !== "") {
$("#submit_button").show();
} else {
$("#submit_button").hide();
}
});
});
but this shows the button if just one input is not blank.
Is it possible to do this for multiple inputs, once all the inputs with the required
class are not blank?
CheckRequired function
function CheckRequired(event) {
var $form = $(this);
var emptyElements = $form.find('.required').filter(function() {
return this.value === ''
});
if(emptyElements.length > 0) {
event.preventDefault();
emptyElements.addClass("EmptySelect").attr('title', 'This field is required');
//alert(emptyElements.attr("id"));
alert("One or more fields cannot be blank");
event.stopImmediatePropagation();
return false;
}
}
You have to pass the parameter in the request. Since you are having a form, and submitting the form, you can have a hidden field in the form called, say "submitType", and populate it whenever you click the button, using javascript. Then this will be available in the next request.
Given an HTML document and the task is to enable or disable the form submit button in jQuery. Approach: To enable or disable the form submit button, we use the below code snippet. $('#enabled'). click(function () { if ($('#submit-button').is(':disabled')) { $('#submit-button').
The logic is straightforward:
And don't just watch keyup
. That won't catch data pasted in via mouse/etc. I'd also watch change
and blur
, to be safe.
$(document).ready(function() {
// show submit button *only* when all
// .required fields have a value
//
var checkRequired = function() {
var allValid = true; // assume we're ready
$('.required').each(
function() {
if (this.value.trim() === "") {
// fail as soon as we hit an empty field
allValid = false;
return false; // this ends the each() loop
}
}
);
$('#submit_button').toggle(allValid);
}
$('.required').bind('keyup change blur', checkRequired);
checkRequired(); // start off in a correct state
});
.required {
border: 2px solid red;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form>
<input type="text" class="required" />
<input type="text" />
<input type="text" class="required" />
<input type=submit id=submit_button value="Submit" />
</form>
Note that we call checkRequired()
at startup, so that if the fields already have values, we'll show the button appropriately.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With