how to disable submit button until form is filled - javascript

I know there is a lot answers for that out-there, but from some reason it not working for me.
You can view the code on JSFiddle
There is mistake on the position of the script? with one of the inputs id ?
The problem: after fill the text fields, the button still disabled.
HTML
<form class="form" name="contactform" method="post" action="https://lp.outit.co.il/LA-FACE/send_form_email.php">
<input placeholder="Your Name*" type="text" name="name" maxlength="50">
<input placeholder="Phone *" type="text" name="telephone" maxlength="30">
<input placeholder="Email *" type="email" name="email" maxlength="80">
<input class="send" id="register" type="submit" value="Send" disabled="disabled">
<p>* = Requierd fields</p>
</form>
JQUERY ON HEAD
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script>
(function() {
$('form > input').keyup(function() {
var empty = false;
$('form > input').each(function() {
if ($(this).val() === '') {
empty = true;
}
});
if (empty) {
$('#register').attr('disabled', 'disabled');
} else {
$('#register').removeAttr('disabled');
}
});
})();
</script>

I posted working fiddle ,Is this what u want ? http://jsfiddle.net/qqwcu/2/
Note its preferred to use: $('#register').prop("disabled", false);
Check this Remove disabled attribute using JQuery?
$(document).ready(function(){
$('form > input').keyup(function() {
var empty1 = false;
$('form > input').each(function() {
if ($(this).val() === '') {
empty1 = true;
}
});
if (empty1) {
$('#register').attr('disabled', 'disabled');
} else {
$('#register').prop("disabled", false);
}
});
});

Your fiddle is fine, although ,You havent included jQuery there. Did that solve the problem?

Your code is run, when the DOM is not yet ready.
Sor wrap it with
$(document).ready()

Related

empty check for multiple form in a page separately

I have two forms (consist with input,textarea,checkbox) in a page. I want check emptiness of these forms separately on click seperate button.
I use the following script. But it shows empty message if any of these form input is empty.
$('#submit').click(function(e) {
var empty = false;
$('input, textarea').each(function() {
if ($(this).val() == '') {
empty = true;
}
});
if (empty) {
alert("empty");
e.preventDefault();
}
else {
document.getElementById("contact").submit();
}
})()
Never assign stuff to submit buttons
Do not submit a form from a submit button if you have chosen to use preventDefault if something wrong. It could submit the form twice
$(function() {
// on the submit event NOT the button click
$('form').on("submit", function(e) { // any form - use .formClass if necessary to specific forms
var empty = false;
$("input, textarea", this).each(function() { // this form's inputs incl submit
if ($.trim($(this).val()) == "") { // trim it too
console.log(this.name,"empty")
empty = true;
return false; // no need to continue
}
});
if (empty) {
alert(this.id + " is empty"); // or set a class on the div
e.preventDefault(); // cancel submission
}
});
});
div {
border: 1px solid black;
width:500px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<form id="form1">
<div>
<input type="text" value="" name="field1" /><br/>
<textarea name="field2"></textarea><br/>
<input type="submit" value="Submit" />
</div>
</form>
<hr/>
<form id="form2">
<div>
<input type="text" value="" name="field3" /><br/>
<textarea name="field4"></textarea><br/>
<input type="submit" value="Submit" />
</div>
</form>
You could also add required to the fields
You need to restrain the handler to the form containing the clicked button:
$('#submit').click(function(e) {
var form = $(this).parents('form:first');
var empty = false;
$('input, textarea', form).each(function() {
// the rest is the same
I'd also like to point out that you cannot have the same ID on multiple controls, so
$('#submit')
should always return exactly one button. You should do something like this, where you distinguish the buttons by class instead:
<input type="submit" id="submitA" class="submitButton">
<input type="submit" id="submitB" class="submitButton">
and select with
$('.submitButton')
you know you can also use jquery to reset the form like so
form.resetForm();

How to disable a button when the input field is empty? [duplicate]

I have this HTML:
<input type="text" name="textField" />
<input type="submit" value="send" />
How can I do something like this:
When the text field is empty the submit should be disabled (disabled="disabled").
When something is typed in the text field to remove the disabled attribute.
If the text field becomes empty again(the text is deleted) the submit button should be disabled again.
I tried something like this:
$(document).ready(function(){
$('input[type="submit"]').attr('disabled','disabled');
$('input[type="text"]').change(function(){
if($(this).val != ''){
$('input[type="submit"]').removeAttr('disabled');
}
});
});
…but it doesn't work. Any ideas?
The problem is that the change event fires only when focus is moved away from the input (e.g. someone clicks off the input or tabs out of it). Try using keyup instead:
$(document).ready(function() {
$(':input[type="submit"]').prop('disabled', true);
$('input[type="text"]').keyup(function() {
if($(this).val() != '') {
$(':input[type="submit"]').prop('disabled', false);
}
});
});
$(function() {
$(":text").keypress(check_submit).each(function() {
check_submit();
});
});
function check_submit() {
if ($(this).val().length == 0) {
$(":submit").attr("disabled", true);
} else {
$(":submit").removeAttr("disabled");
}
}
This question is 2 years old but it's still a good question and it was the first Google result, but all of the existing answers recommend setting and removing the HTML attribute (removeAttr("disabled")) "disabled", which is not the right approach. There is a lot of confusion regarding attribute vs. property.
HTML
The "disabled" in <input type="button" disabled> in the markup is called a boolean attribute by the W3C.
HTML vs. DOM
Quote:
A property is in the DOM; an attribute is in the HTML that is parsed into the DOM.
https://stackoverflow.com/a/7572855/664132
jQuery
Related:
Nevertheless, the most important concept to remember about the checked attribute is that it does not correspond to the checked property. The attribute actually corresponds to the defaultChecked property and should be used only to set the initial value of the checkbox. The checked attribute value does not change with the state of the checkbox, while the checked property does. Therefore, the cross-browser-compatible way to determine if a checkbox is checked is to use the property.
Relevant:
Properties generally affect the dynamic state of a DOM element without changing the serialized HTML attribute. Examples include the value property of input elements, the disabled property of inputs and buttons, or the checked property of a checkbox. The .prop() method should be used to set disabled and checked instead of the .attr() method.
$( "input" ).prop( "disabled", false );
Summary
To [...] change DOM properties such as the [...] disabled state of form elements, use the .prop() method.
(http://api.jquery.com/attr/)
As for the disable on change part of the question: There is an event called "input", but browser support is limited and it's not a jQuery event, so jQuery won't make it work. The change event works reliably, but is fired when the element loses focus. So one might combine the two (some people also listen for keyup and paste).
Here's an untested piece of code to show what I mean:
$(document).ready(function() {
var $submit = $('input[type="submit"]');
$submit.prop('disabled', true);
$('input[type="text"]').on('input change', function() { //'input change keyup paste'
$submit.prop('disabled', !$(this).val().length);
});
});
To remove disabled attribute use,
$("#elementID").removeAttr('disabled');
and to add disabled attribute use,
$("#elementID").prop("disabled", true);
Enjoy :)
or for us that dont like to use jQ for every little thing:
document.getElementById("submitButtonId").disabled = true;
eric, your code did not seem to work for me when the user enters text then deletes all the text. i created another version if anyone experienced the same problem. here ya go folks:
$('input[type="submit"]').attr('disabled','disabled');
$('input[type="text"]').keyup(function(){
if($('input[type="text"]').val() == ""){
$('input[type="submit"]').attr('disabled','disabled');
}
else{
$('input[type="submit"]').removeAttr('disabled');
}
})
It will work like this:
$('input[type="email"]').keyup(function() {
if ($(this).val() != '') {
$(':button[type="submit"]').prop('disabled', false);
} else {
$(':button[type="submit"]').prop('disabled', true);
}
});
Make sure there is an 'disabled' attribute in your HTML
We can simply have if & else .if suppose your input is empty we can have
if($(#name).val() != '') {
$('input[type="submit"]').attr('disabled' , false);
}
else we can change false into true
you can also use something like this :
$(document).ready(function() {
$('input[type="submit"]').attr('disabled', true);
$('input[type="text"]').on('keyup',function() {
if($(this).val() != '') {
$('input[type="submit"]').attr('disabled' , false);
}else{
$('input[type="submit"]').attr('disabled' , true);
}
});
});
here is Live example
For form login:
<form method="post" action="/login">
<input type="text" id="email" name="email" size="35" maxlength="40" placeholder="Email" />
<input type="password" id="password" name="password" size="15" maxlength="20" placeholder="Password"/>
<input type="submit" id="send" value="Send">
</form>
Javascript:
$(document).ready(function() {
$('#send').prop('disabled', true);
$('#email, #password').keyup(function(){
if ($('#password').val() != '' && $('#email').val() != '')
{
$('#send').prop('disabled', false);
}
else
{
$('#send').prop('disabled', true);
}
});
});
Here's the solution for file input field.
To disable a submit button for file field when a file is not chosen, then enable after the user chooses a file to upload:
$(document).ready(function(){
$("#submitButtonId").attr("disabled", "disabled");
$("#fileFieldId").change(function(){
$("#submitButtonId").removeAttr("disabled");
});
});
Html:
<%= form_tag your_method_path, :multipart => true do %><%= file_field_tag :file, :accept => "text/csv", :id => "fileFieldId" %><%= submit_tag "Upload", :id => "submitButtonId" %><% end %>
If the button is itself a jQuery styled button (with .button()) you will need to refresh the state of the button so that the correct classes are added / removed once you have removed/added the disabled attribute.
$( ".selector" ).button( "refresh" );
The answers above don't address also checking for menu based cut/paste events. Below's the code that I use to do both. Note the action actually happens with a timeout because the cut and past events actually fire before the change happened, so timeout gives a little time for that to happen.
$( ".your-input-item" ).bind('keyup cut paste',function() {
var ctl = $(this);
setTimeout(function() {
$('.your-submit-button').prop( 'disabled', $(ctl).val() == '');
}, 100);
});
Disable: $('input[type="submit"]').prop('disabled', true);
Enable: $('input[type="submit"]').removeAttr('disabled');
The above enable code is more accurate than:
$('input[type="submit"]').removeAttr('disabled');
You can use both methods.
Vanilla JS Solution. It works for a whole form not only one input.
In question selected JavaScript tag.
HTML Form:
var form = document.querySelector('form')
var inputs = form.querySelectorAll('input')
var required_inputs = form.querySelectorAll('input[required]')
var register = document.querySelector('input[type="submit"]')
form.addEventListener('keyup', function(e) {
var disabled = false
inputs.forEach(function(input, index) {
if (input.value === '' || !input.value.replace(/\s/g, '').length) {
disabled = true
}
})
if (disabled) {
register.setAttribute('disabled', 'disabled')
} else {
register.removeAttribute('disabled')
}
})
<form action="/signup">
<div>
<label for="username">User Name</label>
<input type="text" name="username" required/>
</div>
<div>
<label for="password">Password</label>
<input type="password" name="password" />
</div>
<div>
<label for="r_password">Retype Password</label>
<input type="password" name="r_password" />
</div>
<div>
<label for="email">Email</label>
<input type="text" name="email" />
</div>
<input type="submit" value="Signup" disabled="disabled" />
</form>
Some explanation:
In this code we add keyup event on html form and on every keypress check all input fields. If at least one input field we have are empty or contains only space characters then we assign the true value to disabled variable and disable submit button.
If you need to disable submit button until all required input fields are filled in - replace:
inputs.forEach(function(input, index) {
with:
required_inputs.forEach(function(input, index) {
where required_inputs is already declared array containing only required input fields.
I had to work a bit to make this fit my use case.
I have a form where all fields must have a value before submitting.
Here's what I did:
$(document).ready(function() {
$('#form_id button[type="submit"]').prop('disabled', true);
$('#form_id input, #form_id select').keyup(function() {
var disable = false;
$('#form_id input, #form_id select').each(function() {
if($(this).val() == '') { disable = true };
});
$('#form_id button[type="submit"]').prop('disabled', disable);
});
});
Thanks to everyone for their answers here.
Please see the below code to enable or disable Submit button
If Name and City fields has value then only Submit button will be enabled.
<script>
$(document).ready(function() {
$(':input[type="submit"]').prop('disabled', true);
$('#Name').keyup(function() {
ToggleButton();
});
$('#City').keyup(function() {
ToggleButton();
});
});
function ToggleButton() {
if (($('#Name').val() != '') && ($('#City').val() != '')) {
$(':input[type="submit"]').prop('disabled', false);
return true;
} else {
$(':input[type="submit"]').prop('disabled', true);
return false;
}
} </script>
<form method="post">
<div class="row">
<div class="col-md-4">
<h2>Getting started</h2>
<fieldset>
<label class="control-label text-danger">Name</label>
<input type="text" id="Name" name="Name" class="form-control" />
<label class="control-label">Address</label>
<input type="text" id="Address" name="Address" class="form-control" />
<label class="control-label text-danger">City</label>
<input type="text" id="City" name="City" class="form-control" />
<label class="control-label">Pin</label>
<input type="text" id="Pin" name="Pin" class="form-control" />
<input type="submit" value="send" class="btn btn-success" />
</fieldset>
</div>
</div>
</form>
take look at this snippet from my project
$("input[type="submit"]", "#letter-form").on("click",
function(e) {
e.preventDefault();
$.post($("#letter-form").attr('action'), $("#letter-form").serialize(),
function(response) {// your response from form submit
if (response.result === 'Redirect') {
window.location = response.url;
} else {
Message(response.saveChangesResult, response.operation, response.data);
}
});
$(this).attr('disabled', 'disabled'); //this is what you want
so just disabled the button after your operation executed
$(this).attr('disabled', 'disabled');
Al types of solution are supplied. So I want to try for a different solution. Simply it will be more easy if you add a id attribute in your input fields.
<input type="text" name="textField" id="textField"/>
<input type="submit" value="send" id="submitYesNo"/>
Now here is your jQuery
$("#textField").change(function(){
if($("#textField").val()=="")
$("#submitYesNo").prop('disabled', true)
else
$("#submitYesNo").prop('disabled', false)
});
Try
let check = inp=> inp.nextElementSibling.disabled = !inp.value;
<input type="text" name="textField" oninput="check(this)"/>
<input type="submit" value="send" disabled />
I Hope below code will help someone ..!!! :)
jQuery(document).ready(function(){
jQuery("input[type=submit]").prop('disabled', true);
jQuery("input[name=textField]").focusin(function(){
jQuery("input[type=submit]").prop('disabled', false);
});
jQuery("input[name=textField]").focusout(function(){
var checkvalue = jQuery(this).val();
if(checkvalue!=""){
jQuery("input[type=submit]").prop('disabled', false);
}
else{
jQuery("input[type=submit]").prop('disabled', true);
}
});
}); /*DOC END*/

How to disable submit button until all text fields are full and file is selected

I'm new to javascript / jquery so I may be missing something obvious, but I've found solutions that disable the submit button until all text fields are filled, and I've found solutions that disable it until a file is chosen. However, my form consists of a file input and 3 text fields and I cannot find a way of it being disabled until all text fields AND a file is chosen.
The distilled version of the code I'm working with is here:
HTML
<div>
<input type="file" /><br />
<input type="text" /><br />
<input type="text" /><br />
<input type="text" /><br />
<input type="submit" value="Upload" class="submit" id="submit" disabled="disabled" />
</div>
JS
$('.submit').click(function() {
var empty = $(this).parent().find("input").filter(function() {
return this.value === "";
});
if(empty.length) {
$('.submit').prop('disabled', false);
}
});
})()
Thanks for your help
https://jsfiddle.net/xG2KS/482/
Try capture the event on those field and checking the empty values by using another function, see below code :
$(':input').on('change keyup', function () {
// call the function after
// both change and keyup event trigger
var k = checking();
// if value inc not 0
if (k) $('.submit').prop('disabled', true);
// if value inc is 0
else $('.submit').prop('disabled', false);
});
// this function check for empty values
function checking() {
var inc = 0;
// capture all input except submit button
$(':input:not(:submit)').each(function () {
if ($(this).val() == "") inc++;
});
return inc;
}
This is just an example, but the logic somehow like that.
Update :
Event Delegation. You might need read this
// document -> can be replaced with nearest parent/container
// which is already exist on the page,
// something that hold dynamic data(in your case form input)
$(document).on('change keyup',':input', function (){..});
DEMO
Please see this fiddle https://jsfiddle.net/xG2KS/482/
$('input').on('change',function(){
var empty = $('div').find("input").filter(function() {
return this.value === "";
});
if(empty.length>0) {
$('.submit').prop('disabled', true);
}
else{
$('.submit').prop('disabled', false);
}
});
[1]:
The trick is
don’t disable the submit button; otherwise the user can’t click on it and testing won’t work
only when processing, only return true if all tests are satisfied
Here is a modified version of the HTML:
<form id="test" method="post" enctype="multipart/form-data" action="">
<input type="file" name="file"><br>
<input type="text" name="name"><br>
<input type="text" name="email"><br>
<button name="submit" type="submit">Upload</button>
</form>
and some pure JavaScript:
window.onload=init;
function init() {
var form=document.getElementById('test');
form.onsubmit=testSubmit;
function testSubmit() {
if(!form['file'].value) return false;
if(!form['name'].value) return false;
if(!form['email'].value) return false;
}
}
Note that I have removed all traces of XHTML in the HTML. That’s not necessary, of course, but HTML5 does allow a simpler version of the above, without JavaScript. Simply use the required attribute:
<form id="test" method="post" enctype="multipart/form-data" action="">
<input type="file" name="file" required><br>
<input type="text" name="name" required><br>
<input type="text" name="email" required><br>
<button name="submit" type="submit">Upload</button>
</form>
This prevents form submission if a required field is empty and works for all modern (not IE8) browsers.
Listen for the input event on file and text input elements, count number of unfilled inputs and, set the submit button's disabled property based on that number. Check out the demo below.
$(':text,:file').on('input', function() {
//find number of unfilled inputs
var n = $(':text,:file').filter(function() {
return this.value.trim().length == 0;
}).length;
//set disabled property of submit based on number
$('#submit').prop('disabled', n != 0);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div>
<input type="file" /><br />
<input type="text" /><br />
<input type="text" /><br />
<input type="text" /><br />
<input type="submit" value="Upload" class="submit" id="submit" disabled="disabled" />
</div>
For my approach, I'd rather use array to store if all the conditions are true. Then use every to make sure that all is true
$(function(){
function validateSubmit()
{
var result = [];
$('input[type=file], input[type=text]').each(function(){
if ($(this).val() == "")
result.push(false);
else
result.push(true);
});
return result;
}
$('input[type=file], input[type=text]').bind('change keyup', function(){
var res = validateSubmit().every(function(elem){
return elem == true;
});
if (res)
$('input[type=submit]').attr('disabled', false);
else
$('input[type=submit]').attr('disabled', true);
});
});
Fiddle

Populating form on keydown ENTER and preventing form from submitting

JS
$('.add_to_list').live('keydown',function (e){
if(e.keyCode == '13'){
var holder=$(this).attr('hold'),
val=$(this).val();
if(holder == 'mf' ||holder == 'mp'){
var v='#'+holder;
h='<li class="entery deletable"><input type="hidden" name="'+holder+'[]" value="'+val+'">'+val+'</li>';
$(v).append(h);
$(this).val('');
}
e.prevent_default();
return false;
}
$('#save_clinic').submit(function(){return false;});
});
HTML
<form accept-charset="utf-8" method="post" id="save_clinic" action="#">
<p>
<b>Findings</b>
<ol id='mf'></ol>
<input type="text" hold="mf" class="add_to_list" value="" name="">
<!--the input hv no name cause i dont want it to be submitted, this is for adding only-->
</p>
<p>
<b>Medical Procedures:</b>
<ol id=mp></ol>
<input type="text" hold="mp" class="add_to_list" value="" name="">
<!--the input hv no name cause i dont want it to be submitted, this is for adding only-->
</p>
<input type=submit>
</form>
Problem:
I want to prevent submit on keypress ENTER and only allow submit on submit button click,
but my current js prevent submit for both and if I remove
$('#save_clinic').submit(function(){return false;});
from js then the form auto submit when user is trying to populate the form.
Can some one please tell me what is the problem here?
example
The function is called preventDefault (no underscore, capital 'D'), not prevent_default. Give that a try and remove this line:
$('#save_clinic').submit(function(){return false;});
I think this should be outside:
$('.add_to_list').live('keydown',function (e){
if(e.keyCode == '13'){
var holder=$(this).attr('hold'),
val=$(this).val();
if(holder == 'mf' ||holder == 'mp'){
var v='#'+holder;
h='<li class="entery deletable"><input type="hidden" name="'+holder+'[]" value="'+val+'">'+val+'</li>';
$(v).append(h);
$(this).val('');
}
}
e.prevent_default(); // take this out from the if
$('#save_clinic').submit(function(){return false;});
});
$('.add_to_list').live('keydown',function (e){
if(e.keyCode == '13'){
var holder=$(this).attr('hold'),
val=$(this).val();
if(holder == 'mf' ||holder == 'mp' ||holder == 'orders'){
var v='#'+holder;
h='<li class="entery deletable"><input type="hidden" name="'+holder+'[]" value="'+val+'">'+val+'</li>';
$(v).append(h);
$(this).val('');
}
//return false;
e.preventDefault();
AND
http://www.bloggingdeveloper.com/post/Disable-Form-Submit-on-Enter-Key-Press.aspx
both works fine now.. thanks all

jQuery disable/enable submit button

I have this HTML:
<input type="text" name="textField" />
<input type="submit" value="send" />
How can I do something like this:
When the text field is empty the submit should be disabled (disabled="disabled").
When something is typed in the text field to remove the disabled attribute.
If the text field becomes empty again(the text is deleted) the submit button should be disabled again.
I tried something like this:
$(document).ready(function(){
$('input[type="submit"]').attr('disabled','disabled');
$('input[type="text"]').change(function(){
if($(this).val != ''){
$('input[type="submit"]').removeAttr('disabled');
}
});
});
…but it doesn't work. Any ideas?
The problem is that the change event fires only when focus is moved away from the input (e.g. someone clicks off the input or tabs out of it). Try using keyup instead:
$(document).ready(function() {
$(':input[type="submit"]').prop('disabled', true);
$('input[type="text"]').keyup(function() {
if($(this).val() != '') {
$(':input[type="submit"]').prop('disabled', false);
}
});
});
$(function() {
$(":text").keypress(check_submit).each(function() {
check_submit();
});
});
function check_submit() {
if ($(this).val().length == 0) {
$(":submit").attr("disabled", true);
} else {
$(":submit").removeAttr("disabled");
}
}
This question is 2 years old but it's still a good question and it was the first Google result, but all of the existing answers recommend setting and removing the HTML attribute (removeAttr("disabled")) "disabled", which is not the right approach. There is a lot of confusion regarding attribute vs. property.
HTML
The "disabled" in <input type="button" disabled> in the markup is called a boolean attribute by the W3C.
HTML vs. DOM
Quote:
A property is in the DOM; an attribute is in the HTML that is parsed into the DOM.
https://stackoverflow.com/a/7572855/664132
jQuery
Related:
Nevertheless, the most important concept to remember about the checked attribute is that it does not correspond to the checked property. The attribute actually corresponds to the defaultChecked property and should be used only to set the initial value of the checkbox. The checked attribute value does not change with the state of the checkbox, while the checked property does. Therefore, the cross-browser-compatible way to determine if a checkbox is checked is to use the property.
Relevant:
Properties generally affect the dynamic state of a DOM element without changing the serialized HTML attribute. Examples include the value property of input elements, the disabled property of inputs and buttons, or the checked property of a checkbox. The .prop() method should be used to set disabled and checked instead of the .attr() method.
$( "input" ).prop( "disabled", false );
Summary
To [...] change DOM properties such as the [...] disabled state of form elements, use the .prop() method.
(http://api.jquery.com/attr/)
As for the disable on change part of the question: There is an event called "input", but browser support is limited and it's not a jQuery event, so jQuery won't make it work. The change event works reliably, but is fired when the element loses focus. So one might combine the two (some people also listen for keyup and paste).
Here's an untested piece of code to show what I mean:
$(document).ready(function() {
var $submit = $('input[type="submit"]');
$submit.prop('disabled', true);
$('input[type="text"]').on('input change', function() { //'input change keyup paste'
$submit.prop('disabled', !$(this).val().length);
});
});
To remove disabled attribute use,
$("#elementID").removeAttr('disabled');
and to add disabled attribute use,
$("#elementID").prop("disabled", true);
Enjoy :)
or for us that dont like to use jQ for every little thing:
document.getElementById("submitButtonId").disabled = true;
eric, your code did not seem to work for me when the user enters text then deletes all the text. i created another version if anyone experienced the same problem. here ya go folks:
$('input[type="submit"]').attr('disabled','disabled');
$('input[type="text"]').keyup(function(){
if($('input[type="text"]').val() == ""){
$('input[type="submit"]').attr('disabled','disabled');
}
else{
$('input[type="submit"]').removeAttr('disabled');
}
})
It will work like this:
$('input[type="email"]').keyup(function() {
if ($(this).val() != '') {
$(':button[type="submit"]').prop('disabled', false);
} else {
$(':button[type="submit"]').prop('disabled', true);
}
});
Make sure there is an 'disabled' attribute in your HTML
We can simply have if & else .if suppose your input is empty we can have
if($(#name).val() != '') {
$('input[type="submit"]').attr('disabled' , false);
}
else we can change false into true
you can also use something like this :
$(document).ready(function() {
$('input[type="submit"]').attr('disabled', true);
$('input[type="text"]').on('keyup',function() {
if($(this).val() != '') {
$('input[type="submit"]').attr('disabled' , false);
}else{
$('input[type="submit"]').attr('disabled' , true);
}
});
});
here is Live example
For form login:
<form method="post" action="/login">
<input type="text" id="email" name="email" size="35" maxlength="40" placeholder="Email" />
<input type="password" id="password" name="password" size="15" maxlength="20" placeholder="Password"/>
<input type="submit" id="send" value="Send">
</form>
Javascript:
$(document).ready(function() {
$('#send').prop('disabled', true);
$('#email, #password').keyup(function(){
if ($('#password').val() != '' && $('#email').val() != '')
{
$('#send').prop('disabled', false);
}
else
{
$('#send').prop('disabled', true);
}
});
});
Here's the solution for file input field.
To disable a submit button for file field when a file is not chosen, then enable after the user chooses a file to upload:
$(document).ready(function(){
$("#submitButtonId").attr("disabled", "disabled");
$("#fileFieldId").change(function(){
$("#submitButtonId").removeAttr("disabled");
});
});
Html:
<%= form_tag your_method_path, :multipart => true do %><%= file_field_tag :file, :accept => "text/csv", :id => "fileFieldId" %><%= submit_tag "Upload", :id => "submitButtonId" %><% end %>
If the button is itself a jQuery styled button (with .button()) you will need to refresh the state of the button so that the correct classes are added / removed once you have removed/added the disabled attribute.
$( ".selector" ).button( "refresh" );
The answers above don't address also checking for menu based cut/paste events. Below's the code that I use to do both. Note the action actually happens with a timeout because the cut and past events actually fire before the change happened, so timeout gives a little time for that to happen.
$( ".your-input-item" ).bind('keyup cut paste',function() {
var ctl = $(this);
setTimeout(function() {
$('.your-submit-button').prop( 'disabled', $(ctl).val() == '');
}, 100);
});
Disable: $('input[type="submit"]').prop('disabled', true);
Enable: $('input[type="submit"]').removeAttr('disabled');
The above enable code is more accurate than:
$('input[type="submit"]').removeAttr('disabled');
You can use both methods.
Vanilla JS Solution. It works for a whole form not only one input.
In question selected JavaScript tag.
HTML Form:
var form = document.querySelector('form')
var inputs = form.querySelectorAll('input')
var required_inputs = form.querySelectorAll('input[required]')
var register = document.querySelector('input[type="submit"]')
form.addEventListener('keyup', function(e) {
var disabled = false
inputs.forEach(function(input, index) {
if (input.value === '' || !input.value.replace(/\s/g, '').length) {
disabled = true
}
})
if (disabled) {
register.setAttribute('disabled', 'disabled')
} else {
register.removeAttribute('disabled')
}
})
<form action="/signup">
<div>
<label for="username">User Name</label>
<input type="text" name="username" required/>
</div>
<div>
<label for="password">Password</label>
<input type="password" name="password" />
</div>
<div>
<label for="r_password">Retype Password</label>
<input type="password" name="r_password" />
</div>
<div>
<label for="email">Email</label>
<input type="text" name="email" />
</div>
<input type="submit" value="Signup" disabled="disabled" />
</form>
Some explanation:
In this code we add keyup event on html form and on every keypress check all input fields. If at least one input field we have are empty or contains only space characters then we assign the true value to disabled variable and disable submit button.
If you need to disable submit button until all required input fields are filled in - replace:
inputs.forEach(function(input, index) {
with:
required_inputs.forEach(function(input, index) {
where required_inputs is already declared array containing only required input fields.
I had to work a bit to make this fit my use case.
I have a form where all fields must have a value before submitting.
Here's what I did:
$(document).ready(function() {
$('#form_id button[type="submit"]').prop('disabled', true);
$('#form_id input, #form_id select').keyup(function() {
var disable = false;
$('#form_id input, #form_id select').each(function() {
if($(this).val() == '') { disable = true };
});
$('#form_id button[type="submit"]').prop('disabled', disable);
});
});
Thanks to everyone for their answers here.
Please see the below code to enable or disable Submit button
If Name and City fields has value then only Submit button will be enabled.
<script>
$(document).ready(function() {
$(':input[type="submit"]').prop('disabled', true);
$('#Name').keyup(function() {
ToggleButton();
});
$('#City').keyup(function() {
ToggleButton();
});
});
function ToggleButton() {
if (($('#Name').val() != '') && ($('#City').val() != '')) {
$(':input[type="submit"]').prop('disabled', false);
return true;
} else {
$(':input[type="submit"]').prop('disabled', true);
return false;
}
} </script>
<form method="post">
<div class="row">
<div class="col-md-4">
<h2>Getting started</h2>
<fieldset>
<label class="control-label text-danger">Name</label>
<input type="text" id="Name" name="Name" class="form-control" />
<label class="control-label">Address</label>
<input type="text" id="Address" name="Address" class="form-control" />
<label class="control-label text-danger">City</label>
<input type="text" id="City" name="City" class="form-control" />
<label class="control-label">Pin</label>
<input type="text" id="Pin" name="Pin" class="form-control" />
<input type="submit" value="send" class="btn btn-success" />
</fieldset>
</div>
</div>
</form>
take look at this snippet from my project
$("input[type="submit"]", "#letter-form").on("click",
function(e) {
e.preventDefault();
$.post($("#letter-form").attr('action'), $("#letter-form").serialize(),
function(response) {// your response from form submit
if (response.result === 'Redirect') {
window.location = response.url;
} else {
Message(response.saveChangesResult, response.operation, response.data);
}
});
$(this).attr('disabled', 'disabled'); //this is what you want
so just disabled the button after your operation executed
$(this).attr('disabled', 'disabled');
Al types of solution are supplied. So I want to try for a different solution. Simply it will be more easy if you add a id attribute in your input fields.
<input type="text" name="textField" id="textField"/>
<input type="submit" value="send" id="submitYesNo"/>
Now here is your jQuery
$("#textField").change(function(){
if($("#textField").val()=="")
$("#submitYesNo").prop('disabled', true)
else
$("#submitYesNo").prop('disabled', false)
});
Try
let check = inp=> inp.nextElementSibling.disabled = !inp.value;
<input type="text" name="textField" oninput="check(this)"/>
<input type="submit" value="send" disabled />
I Hope below code will help someone ..!!! :)
jQuery(document).ready(function(){
jQuery("input[type=submit]").prop('disabled', true);
jQuery("input[name=textField]").focusin(function(){
jQuery("input[type=submit]").prop('disabled', false);
});
jQuery("input[name=textField]").focusout(function(){
var checkvalue = jQuery(this).val();
if(checkvalue!=""){
jQuery("input[type=submit]").prop('disabled', false);
}
else{
jQuery("input[type=submit]").prop('disabled', true);
}
});
}); /*DOC END*/

Categories

Resources