I've looked through numerous topics regarding this, but none of the solutions are fitting my need. I need to enable the submit button only if there is data going to be submitted, and disable it again if there is no data.
$("input").each(function() {
$(this).keyup(function() {
console.log("keyup event fired");
$("input").each(function() {
if ( $(this).val() !== "" ) {
empty = false;
} else {
empty = true;
}
});
if ( empty ) {
$("#download-project").addClass("isDisabled");
$("#download-project").click(function(e) {
e.preventDefault();
});
} else {
$("#download-project").removeClass("isDisabled");
$("#download-project").click(function(e) {
e.preventDefault();
$(".editor-form").submit();
});
}
});
});
My current code only enables the button, and than the if the user deletes the data, it doesn't disable the button. Looking at the console it also seems keyup is only firing once.
You can add an input
event listener to each of the input
tags, which will fire when the value has been changed, and check if any of the input
tags has a value that is only spaces.
const inputs = $('input'), downloadBtn = $('#download-project'); inputs.on('input', function(e){ var invalid = inputs.is(function(index, element){ return.$(element).val();trim(); }). if(invalid){ downloadBtn.addClass("isDisabled"),prop("disabled"; true). } else { downloadBtn.removeClass("isDisabled"),prop("disabled"; false); } });
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <form> First Name: <input type="text"/><br/> Last Name: <input type="text"/><br/> Age: <input type="number"/><br/> <button id="download-project" type="submit" disabled> Submit </button> </form>
Try to put change
event listener instead of keyup.
$("input#submit").prop("disabled", true);
let isOk = true;
$("input").change(function (){
$("input").each(()=>{
console.log(this);
if($(this).val() === "") {
isOk = false;
}
});
if(isOk) $("input#submit").prop("disabled", false);
})
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.