Disable button unless specific fields have values - javascript

I have an ASPX form and I need to disable the submit button if any one of six specific fields are empty. I'm trying to do this via Javascript or jQuery, but so far I can only find examples of either a single field on the form being empty, or ALL fields on the form. In my case, I don't care about several fields - only the six specific ones.
So basically, I have six conditions and one action. I found one example, but it was stringing together six different IF statements. I'd like to find a more streamlined way if possible. So, for example, I might do THIS for a single field... but how to do it for field2, field3, field4, etc. as well?
$(document).ready(function(){
$('#submit_btn').prop('disabled',true);
$('#field1').keyup(function(){
$('#submit_btn').prop('disabled');
})
});
Using Javascript or jQuery, what's the most efficient way to disable an input button if any of six input fields is blank?

You can add the same class name to all the elements and then do a validation foreach class element. Like in below code, i added the same class name to all the input for which the validation is required using class="valid" and then use the jquery class selector and the keyup method that you used to control the state of the button.
(function() {
$('.valid').keyup(function() {
var isEmpty = false;
$('.valid').each(function() {
if ($(this).val() == '') {
isEmpty = true;
}
});
if (isEmpty) {
$('#button1').attr('disabled', 'disabled');
} else {
$('#button1').removeAttr('disabled');
}
});
})()
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form>
1<input type="text" class="valid" /><br />
2<input type="text" class="valid" /><br />
3<input type="text" class="valid" /><br />
4<input type="text" class="valid" /><br />
5<input type="text" class="valid" /><br />
6<input type="text" class="valid" /><br />
<input type="button" id="button1" value="Test Me!" disabled="disabled" />
</form>

If your requirements will allow it, you can use HTML 5 field validation. The browser will not allow the form to submit.
<form>
<label for="choose">Foo</label>
<input name="bar" required>
<input type="submit" /> <!-- <--- This will generate an error message if the user clicks it when the field is empty -->
</form>

You have the start of it correct; create an array with six variables, one for each of the fields, and create a new function to validate everything that is called on each keyup. So you would have
var[] array
$('#field1').keyup(function() {
array[0] = $('#field1').val();
validate();
}
${'#field2').keyup(function() {
array[1] = $('#field2').val();
validate();
}
...create one each for each field
function validate() {
for (var i = 0; i < array.length; i++) {
if(!arrays[i]) {
$('#submit_btn').prop('disabled');
return;
}
}
$('#submit_btn').prop('enabled'):
}
What this does is it listens to the fields for changes and updates the array. A blank value is falsy so you can just go through the array and disable the button if it's blank or null or something. Break out of the for loop in that case; you don't care about whatever else. If nothing disables the button and breaks the for loop then it's valid and the button is enabled.
This approach is useful because it's easily extendable. You can just push extra things into the array if you want to check them without rewriting the validation function.
This assumes you do not want to just use standard form validation and do it manually.

Add a common class to each of the required inputs. Then check the length of that object against the length of a filtered object where value is not empty. Then you can use that condition to set the prop value of the button to true/false.
http://api.jquery.com/filter/
JQuery:
$('form .required-valid').on('input paste change', function() {
var $required = $('form .required-valid');
//filter required inputs to only ones that have a value.
var $valid = $required.filter(function() {
return this.value != '';
});
//set disabled prop to false if valid input count is != required input count
$('#submit_btn').prop('disabled', $valid.length != $required.length);
});
HTML:
<form>
<label>Field1</label>
<input type="text" id="field1" class="required-valid" />
<label>Field2</label>
<input type="text" id="field2" class="required-valid" />
<label>Field3</label>
<input type="text" id="field3" class="required-valid" />
<label>Field4</label>
<input type="text" id="field4" class="required-valid" />
<label>Field5</label>
<input type="text" id="field5" class="required-valid" />
<label>Field6</label>
<input type="text" id="field6" class="required-valid" />
<label>Field7</label>
<input type="text" id="field7" class="not-required" placeholder="not required" />
<button id="submit_btn" disabled>
Submit
</button>
</form>
Example:
https://jsfiddle.net/SeanWessell/q2msc80L/

$(document).ready(function() {
$('#submit_btn').prop('disabled', true);
$('#field1').keyup(function() { // on keyup
var value = $(this).val(); // retrieve the value of the input
if (value.length == 0) // if the value's length is 0 (empty)
$('#submit_btn').prop('disabled', true); // disable the button
else // if not
$('#submit_btn').prop('disabled', false); // enable it
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form>
<input id="field1"/>
<input id="submit_btn" type="submit"/>
</form>
Just note that the form can be submitted using enter key, so instead of checking on every keyup, it would be better if you check onsubmit instead.

Related

Associate a checkbox with an input field and make it mandatory only if input value exists

I am trying to make a manual verification system and want the user to check each checkbox associated with individual inputs if a value exists before submission else the form would throw an error.
I have implemented this, but it does not seem to work. Also, I was wondering if there was a better way of achieving the same wherein we avoid passing the parameters to the function.
Similar to how we can associate a submit button for a form using form by supplying the id.
<form>
<input type="text" name="inputFieldOne">
<input type="checkbox" onblur="makeSureItIsSelected('inputFieldOne', 'inputCheckboxOne')" name="inputCheckboxOne">
<input type="text" name="inputFieldTwo">
<input type="checkbox" onblur="makeSureItIsSelected('inputFieldTwo', 'inputCheckboxTwo')" name="inputCheckboxTwo">
<input type="submit" value="Submit">
</form>
<script>
function makeSureItIsSelected(field, checkbox){
let fieldBox = document.getElementsByName(field)[0];
if(fieldBox.value != ''){
checkBox = document.getElementsByName(checkbox)[0];
checkBox.required = true;
}
}
</script>
If you want to set the checkbox to be required when the field has a value, you should hook an event on the field, not the checkbox. input would make a good event for this:
function makeSureItIsSelected(field, checkbox){
let fieldBox = document.getElementsByName(field)[0];
let checkBox = document.getElementsByName(checkbox)[0];
// Require the checkbox when the field has a value
checkBox.required = fieldBox.value != '';
}
<form>
<input type="text" name="inputFieldOne" oninput="makeSureItIsSelected('inputFieldOne', 'inputCheckboxOne')">
<input type="checkbox" name="inputCheckboxOne">
<input type="text" name="inputFieldTwo" oninput="makeSureItIsSelected('inputFieldTwo', 'inputCheckboxTwo')">
<input type="checkbox" name="inputCheckboxTwo">
<input type="submit" value="Submit">
</form>
Note that there's no need for those calls to getElementsByName: Just pass this into the function, and use nextElementSibling to access the checkbox:
function makeSureItIsSelected(field){
// Require the checkbox when the field has a value
field.nextElementSibling.required = field.value != '';
}
<form>
<input type="text" name="inputFieldOne" oninput="makeSureItIsSelected(this)">
<input type="checkbox" name="inputCheckboxOne">
<input type="text" name="inputFieldTwo" oninput="makeSureItIsSelected(this)">
<input type="checkbox" name="inputCheckboxTwo">
<input type="submit" value="Submit">
</form>
That said, it seems odd to have the checkboxes at all. The presence of the field in the form data should be sufficient. But if the checkbox's value has to be in the form data, simply add it on submit without having a checkbox at all.

JS input validation submit disabled for separate instances

I need each instance of input and submit to operate independently. What is the best way to handle multiple instances where each submit is connected to it's own set of inputs?
Since they are unrelated, would data-attributes be the best solution?
$(document).ready(function() {
validate();
$('input').on('keyup', validate);
});
function validate() {
var inputsWithValues = 0;
var myInputs = $("input:not([type='submit'])");
myInputs.each(function(e) {
if ($(this).val()) {
inputsWithValues += 1;
}
});
if (inputsWithValues == myInputs.length) {
$("input[type=submit]").prop("disabled", false);
} else {
$("input[type=submit]").prop("disabled", true);
}
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="item1">
<div><input type="text" name="name" autocomplete="off" required/></div>
<input type="submit" value="Submit 1" />
</div>
<div class="item2">
<div><input type="text" name="name" autocomplete="off" required/></div>
<div><input type="text" name="name" autocomplete="off" required/></div>
<input type="submit" value="Submit 2" />
</div>
I think your intuition about using data attributes works great here.
var allButtons = document.querySelectorAll("input[type=submit]");
allButtons.forEach(button => {
button.addEventListener("click", () => {
var inputSet = button.getAttribute("data-input-set");
var inputs = document.querySelectorAll("input[type='text'][data-input-set='" + inputSet + "']");
});
});
In the following code, when an input button is pressed, it will fetch all the inputs with the corresponding "input-set" tag.
Preferred way
I think best solution would be use form -tag as it is created for just this use case HTML Forms.
<form id="form-1">
<input type="text"/>
<input type="submit>
</form>
<form id="form-2">
<input type="text"/>
<input type="submit>
</form>
You can also bind custom Form on submit event handlers and collect form data this way.
$('#form-1').on('submit', function(event){
event.preventDefault(); // Prevent sending form as defaulted by browser
/* Do something with form */
});
Possible but more bolt on method
Alternative methods to this would be to create your own function's for collecting all relevant data from inputs and merge some resonable data object.
I would most likely do this with giving desired class -attribute all inputs I would like to collect at once eg. <input type="text" class="submit-1" /> and so on. Get all elements with given class, loop through all them and save values into object.
This requires much more work tho and form -tag gives you some nice validation out of the box which you this way have to do yourself.

How to check if textbox is empty and display a popup message if it is using jquery?

I'm trying to check if the textbox is empty for my form. However, whenever I try to hit submit instead of an alert box message, telling me Firstname is empty I get "Please fill out filled".
('#submit').click(function() {
if ($('#firstname').val() == '') {
alert('Firstname is empty');
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form id="elem" autocomplete="on">
First Name:
<br>
<input type="text" name="firstname" id="firstname" required placeholder="Enter the first name" pattern="[A-Za-z\-]+" maxlength="25"><br>
<input type="submit" id="submit" value="Submit" />
</form>
Firstly I'm assuming that the missing $ is just a typo in the question, as you state that you see the validation message appear.
The reason you're seeing the 'Please fill out this field' notification is because you've used the required attribute on the field. If you want to validate the form manually then remove that attribute. You will also need to hook to the submit event of the form, not the click of the button and prevent the form submission if the validation fails, something like this:
$('#elem').submit(function(e) {
if ($('#firstname').val().trim() == '') {
e.preventDefault();
alert('Firstname is empty');
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form id="elem" autocomplete="on">
First Name:
<br>
<input type="text" name="firstname" id="firstname" placeholder="Enter the first name" pattern="[A-Za-z\-]+" maxlength="25"><br>
<input type="submit" id="submit" value="Submit" />
</form>
Personally I'd suggest you use the required attribute as it saves all of the above needless JS code - unless you need more complex logic than just checking all required fields have been given values.
Because you have the required property set.It is giving you Please fill out field validation as the error message.It is the validation that HTML5 is performing.
For this please make one function like :
function Checktext()
{
if ($('#firstname').val() == '') {
alert('Firstname is empty');
return false;
}
else
{
return true;
}
}
now call this function on submit button click like :
<input type="submit" id="submit" value="Submit" onclick="return check();" />

jquery validate either checkbox or input field

I had a form that can send message and user need to select group from checkbox or manual input the group name. Now i want validate this form, if user not check any checkbox or insert any value in text field this form cannot sumbit.
Below is my form and here is my jsfiddle (already validate textarea).
<form action="" method="post" name="myform" id="myform">
<input type="checkbox" name="group_list[]" value="1" />Group 1<br />
<input type="checkbox" name="group_list[]" value="1" />Group 1<br />
<input type="checkbox" name="group_list[]" value="1" />Group 1<br />
<input type="checkbox" name="group_list[]" value="1" />Group 1<br />
<input type="text" name="manual_group" value="" placeholder="Group Name" /><br />
<textarea name="message" placeholder="Your Message"></textarea> <br />
<input type="submit" name="submit" value="Send Message" />
</form>
User need to check one of checkbox or insert group name before submit.So the question is how to create condition for this rule?
*Remember this form still can submit if i not check one of the checkbox but key-in some name in manual_group , this form also can sumbit if i not key-in any name but check for checkbox.
You can achieve this by setting a rule on the textbox that it is required only if none of the checkboxes are checked. This uses the type of required specification that takes a function as a parameter.
rules: {
manual_group: {
required: function () {
return $('[name=group_list\\[\\]]:checked').length === 0;
}
}
}
The other thing you need to do is force a re-validation when either the checkboxes or the textbox are changed. I have done it like this,
$('form input').on('click focusin focusout keyup', function () {
$('form').validate().form();
});
The full script is below, and in this fiddle
$(function () {
$("form").validate({
rules: {
manual_group: {
required: function () {
return $('[name=group_list\\[\\]]:checked').length === 0;
}
}
},
messages: {
manual_group: "Please check a checkbox or fill in this field"
},
submitHandler: function () {
alert('form ok');
}
});
$('form input').on('click focusin focusout keyup', function () {
$('form').validate().form();
});
});
with reference to your Fiddle
you can add it in the same way just like the validation you'hv added for message
e.g.
"group_list[]": {required:true}...
May be this will work
$("#submit").click(function(){
if($('#myform input:checked').length >= 1 || $("#manual_group").val() !=""){
return true ;
}
return false;
}

Check all input fields have been filled out with jQuery

I have 3 divs, each with a dfew input fields and next button on.
I want to write a snippet of jQuery that when the next button is clicked it checks to ensure all input fields WITHIN the same div as the button, are not null.
I've tried the following with no luck but Im 100% certain its wrong, only I cant find the relevant information online...
http://jsfiddle.net/xG2KS/1/
You could use filter to reduce the set of all input elements to only those that are empty, and check the length property of what remains:
$(".next").click(function() {
var empty = $(this).parent().find("input").filter(function() {
return this.value === "";
});
if(empty.length) {
//At least one input is empty
}
});
Note that the definition of empty in the above code is an empty string. If you want to treat blank spaces as empty too, you may want to trim the value before comparing.
Also note that there is no need to pass this into jQuery inside the filter function. The DOM element itself will have a value property, and it's much faster to access that instead of using val.
Here's an updated fiddle.
$('.next').click(function() {
var emptyInputs = $(this).parent().find('input[type="text"]').filter(function() { return $(this).val() == ""; });
if (emptyInputs.length) {
alert('Fail!');
}
});
Because there is no jQuery selector for this case you can extend jQuery’s selector capabilities.
Assuming you select all :text elements, the extension is:
$.extend($.expr[':'],{
isEmpty: function(e) {
return e.value === '';
}
});
Hence, you can select all empty text fields:
$(this).closest('div').find(':text:isEmpty');
$.extend($.expr[':'], {
isEmpty: function (e) {
return e.value === '';
}
});
$('.next').click(function () {
var missingRequired = $(this).closest('div').find(':text:isEmpty');
console.log('Empty text fields: ' + missingRequired.length);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div>
<input type="text" /><br />
<input type="text" /><br />
<input type="text" /><br />
<input type="submit" value="next" class="next" />
</div>
<div>
<input type="text" /><br />
<input type="text" /><br />
<input type="text" /><br />
<input type="submit" value="next" class="next" />
</div>
<div>
<input type="text" /><br />
<input type="text" /><br />
<input type="submit" value="next" class="next" />
</div>
$('.next').click(function() {
var inputs = $(this).parent().find('input[value=""]');
if (!inputs.length) {
// you have empty fields if this section is reached
}
});

Categories