FORM won't submit even though input fields are not empty - javascript

it wont submit even though the fields are not empty
here's the form:
<form id="form" role="form" method='POST' action="user_add-post.php">
<div class="form-group">
<p><label class="control-label">Title</label><br />
<input style="width: 40%" class="form-control" type="text" name="postTitle"/>
</div>
<div class="form-group">
<p><label lass="control-label">Description</label><br />
<textarea name="postDesc" cols="60" rows="10"></textarea>
</div>
<div class="form-group">
<p><label>Content</label></p>
<textarea name="postCont" cols="60" rows="10"></textarea>
</div>
<input type='submit' name="submit" class='btn btn-primary' value='Submit'></form>
and here's my jquery to check if the input fields are empty:
$('#form').submit(function() {
if ($.trim($("#postTitle").val()) === "" || $.trim($("#postDesc").val()) === "" || $.trim($("#postCont").val()) === "") {
alert('All fields required');
return false;
} });
now why won't it submit? it keeps on saying that all fields are required even though I already fill up the fields.

You have missed to add id in input boxes,
<input style="width: 40%" class="form-control" type="text" name="postTitle"/>
Change it to
<input style="width: 40%" class="form-control" type="text" id="postTitle" name="postTitle"/>
for next text box aswell ,Please Refer

you do not have define the ids so change the condition to
if ($.trim($('[name="postTitle"]').val()) === "" || $.trim($('[name="postDesc"]').val()) === "" || $.trim($('[name="postCont"]').val()) === "")

You have not given the ids to any of your form field, use global selector with condition
here is the working fiddle of your task
`$("input[name=postTitle]").val()` //name selector instead of id

If condition should be like this:
if ($("#postTitle").val().trim() == "" || $("#postDesc").val().trim() == "" || $("#postCont").val().trim() == "") {

See for any JS errors if you are getting. Also , try it on various browsers. You are not using ID attribute, but Name attritute, so it may not work on Firefox,Chrome and may work on IE7 and below. Hope this helps you

Provide Id to input element in html code.
Jquery code is fine
here is the correct code of html
<input style="width: 40%" class="form-control" type="text" name="postTitle" id="postTitle"/>

Yes like everyone else is saying if you are going to use selectors then you need those id's on the form fields. Or you can use the names like this:
$("[name=postTitle]").val()
$("[name=postDesc]").val()
$("[name=postCont]").val()
Here is your jquery with the above:
$('#form').submit(function() {
if ($("[name=postTitle]").val().trim() == "" || $("[name=postDesc]").val().trim() == "" || $("[name=postCont]").val().trim() == "") {
alert('All fields required');
return false;
} });

As others have said, the selectors are based on ID but using name attribute values. So you can add ID attributes, change the selector or use a different strategy.
Since the listener is on the form, this within the function references the form and all form controls with a name are available as named properties of the form. So you can easily test the value contains something other than whitespace with a regular expression, so consider:
var form = this;
var re = /^\s*$/;
if (re.test(form.postTitle.value) || re.test(form.postDesc.value) || re.test(form.postCont.value) {
/* form is not valid */
}
which is a lot more efficient than the OP.
Given the above, a form control with a name of submit will mask the form's submit method so you can't call form.submit() or $('#formID').submit().

Related

Need to evaluate content in drop-down in Javascript

As stated in the topic I need to evaluate two fields, one from a drop-down menu item, and one for a text input type field. both in HTML of course. I want to test if the fields are empty, zero, whatever in that context.
I have tried to alter the code, but cannot seem to find the right code.
$(document).ready(function() {
$(function() {
$("#companyDialog").dialog({
autoOpen: false
});
$("#companyButton").on("click", function() {
$("#companyDialog").dialog("open");
});
});
// Validating Form Fields.....
$("#companySubmit").click(function(e) {
var comnpanyname = $("#companyname").val();
var editcompanyscombo = $("#editcompanyscombo").val();
if (companyname === '' || editcompanyscombo === '') {
alert("Please fill all fields marked with an *!");
e.preventDefault();
} else if (editcompanyscombo === '0') {
alert("Select comany to update!");
e.preventDefault();
} else {
alert("Form Submitted Successfully.");
}
});
});
<div class="container">
<div class="main">
<div id="companyDialog" title="Edit company">
<form action="" method="post">
<## CompanyEditCombo ##><br>
<label>New company name:</label>
<input id="companyname" name="companyname" type="text">
<input id="companySubmit" type="submit" value="Submit">
</form>
</div>
<input id="companyButton" type="button" value="Open Company Edit Dialog Form">
</div>
</div>
The fields pop up, but they do not alert if the values are zero or empty.
So far I could see from these snippets, please replace === '' and === '0' by == null
(Double equality comparison operator does not aimed to compare the types. That is why, one should use it because null is type object. s. Developer Mozilla)

Check if input is empty, if not, add class to parent div

I have a number of inputs like this:
<div class="fg-line">
<input type="text" class="form-control fg-input place-edit placeInformation" id="place_name">
<label class="fg-label">Place Name</label>
</div>
<div class="fg-line">
<input type="text" class="form-control fg-input place-edit placeInformation" id="place_address">
<label class="fg-label">Place Address</label>
</div>
I get some data from an API and then append to these inputs (so the user can edit).
This works fine. The issue is that I want to add a class to this:
<div class="fg-line">
This is simple enough if I only have one of these and one input, but since I have multiple, I need some way to check each input and if not empty add the class fg-toggled such that the line becomes:
<div class="fg-line fg-toggled">
If I had just one input, I'd do this:
if (('#place_name').value != '' || ('#place_name').value != ('#place_name').defaultValue) {
$('.fg-line').addClass('fg-toggle')
}
But I don't know how to do this without writing this out for every class (there are 30+). Is there a way to iterate this somehow? I tried checking .place-edit but since it's a class, if any of the inputs with the class are not empty then they all get the new class added.
Simply loop through each input and find the parent using .closest().
$('.placeInformation').each(function() {
var $input = $(this);
if ($input.val()) {
var $parent = $input.closest('.fg-line');
$parent.addClass('fg-toggled')
}
});
Sample plunkr
Can use filter()
$('.fg-line').has('.placeInformation').filter(function(){
return !$(this).find('.placeInformation').val()
}).addClass('fg-toggled')
Not sure what "default" should be or how it is declared. Could be set in a data attribute and add an || to above filter condition
Use each() and closest()
Try this :
$(".fg-input").each(function() {
if ($(this).val() != '') {
$(this).closest(".fg-line").addClass('fg-toggle');
}
})
.fg-toggle
{
color:green;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="fg-line">
<input type="text" class="form-control fg-input place-edit placeInformation" id="place_name">
<label class="fg-label">Place Name</label>
</div>
<div class="fg-line">
<input type="text" class="form-control fg-input place-edit placeInformation" id="place_address">
<label class="fg-label">Place Address</label>
</div>
You could just loop through the .place-edit class and then check the values and add the class to the parents, like this:
$('.place-edit').each(function(){
if($(this).val() != '' || $(this).val() != $(this).defaultValue) {
$(this).parent().addClass('fg-toggle');
}
})
Try this.. I'm assuming they all have the same class
if (('#place_name').value != '' || ('#place_name').value != ('#place_name').defaultValue) {
$('.fg-line').each(function(){
$(this).addClass('fg-toggle')
});
}

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*/

Disable or Enable buttons based on some conditions

In my app I have multiple divs which look like (The divs are created dynamically):
<div class="form-group clearfix">
<div class="form-group first-name">
<input type="text" id="firstName0" class="signup-input firstName required" name="first[0]" placeholder="">
</div>
<div class="form-group last-name">
<input type="text" id="lastName0" class="signup-input lastName" name="last[0]" placeholder="optional">
</div>
<div class="form-group email">
<input type="text" data-index="0" id="inputMail0" class="signup-input mail" name="email[0]" placeholder="e.g. example#url.com" aria-invalid="true">
<span class="common-sprite sign-up-cross first"></span>
</div>
</div>
The names are dynamically generated according to the index (For example the are email[1], email[2].....).
I have a button which should be disabled in case the field of the first name is not empty and the field of the email is empty and the span hasn't a class of disNone.
How should I disable the button according to above condition?
If I understand you correctly, you want to disable the button if all of the following conditions are met:-
First name field is NOT empty - $('#firstName0').val() != ''
Email field IS empty - $('#inputMail0').val() == ''
Span does NOT have class of disNone - !$('span').hasClass('disNone')
So I would check that condition this way by wrapping it in a listener on the keyup event upon the form:
$('.form-group').on('keyup', function () {
console.log('keyup');
if ($('#firstName0').val() !== '' && $('#inputMail0').val() === '' && !$('.email span').hasClass('disNone')) {
//Now do whatever with your button.
$('.mybutton').prop('disabled', true);
} else {
$('.mybutton').prop('disabled', false);
}
});
Demo: http://jsfiddle.net/ajj87Lg3/
Hope this condition works out for you.
Store the jQuery objects in variables and use that variables instead, which is a much better way to do it.
$(function(){
var firstName = $('#firstName0').val();
var inputMail = $('#inputMail0').val();
var checkClass = $('span').hasClass('disNone');
if( firstName!=='' && inputMail==='' && !checkClass ) {
$('button').attr('disabled','disabled'); //in the fiddle you would see an alert, you just have to replace that code with this one
}
});
EDIT: If your DIVS are being generated dynamically you can use the each() jquery function to loop through them.
$(function(){
$('#mainDiv').children('div').each(function(index,element){
var nameDiv = $(element).find(":nth-child(1)");
var firstName = $(nameDiv).find('input').val();
var emailDiv = $(element).find(":nth-child(3)");
var inputMail = $(emailDiv).find('input').val();
var spanElem = $(emailDiv).find("span");
var checkClass = $(spanElem).hasClass('disNone');
if(firstName!=='' && inputMail==='' && !checkClass){
$('button').attr('disabled','disabled');
//in the fiddle you would see a console.log('hi'), you just have to replace that code with this one for whatever button you want to disable
}
});
});
Checkout the FIDDLE LINK
In the fiddle I have left out one SPAN tag with class disNone and other SPAN tag without class disNone. So only once the condition executes

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