function validate(){
var cekLengthError = 0;
$(".not-empty").each(function(i, obj) {
if ($(this).children('input').val() == "") {
$(this).children('input').next().addClass("show");
$(this).children('input:first').focus();
cekLengthError = cekLengthError+1;
} else {
$(this).next().removeClass("show");
}
});
if(cekLengthError == 0){
alert("success")
}
}
When I click validate. Instead it checked the last element first. how to check the first element first? Maybe I was wrong when using this in each function.
Please Check in my fiddle: https://jsfiddle.net/dedi_wibisono17/a7be9zso/50/
Thank you
$(".add").click(function(){
$(".test").append(`
<div class="not-empty"><input type="text" placeholder="name" class="name" /><div class="error">error</div></div>
`)
})
function validate(){
var cekLengthError = 0;
$(".not-empty").each(function(i, obj) {
if ($(this).children('input').val() == "") {
$(this).children('input').next().addClass("show");
//$(this).children('input:first').focus();
if($("input.email").val() ==""){
$(".email").focus();
}else if ($("input.name").val() ==""){
$(".name").focus();
}else if ($("input.city").val() ==""){
$(".city").focus();
}else {
}
cekLengthError = cekLengthError+1;
}else{
$(this).next().removeClass("show");
}
});
if(cekLengthError == 0){
alert("success")
}
}
.error{
display:none;
}
.show{
display:block !important
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="lala not-empty">
<input type="text" class="email" placeholder="email" requird>
<div class="error">Error</div>
</div>
<div class="test not-empty">
<input type="text" class="name" placeholder="name">
<div class="error">Error</div>
</div>
<div class="test not-empty">
<input type="text" class="city" placeholder="name">
<div class="error">Error</div>
</div>
<br>
<button class="add">add</button>
<button class="validasi" onclick="validate();">validate</button>
You are always focusing to an element when iterating over the element list. So if you have 5 elements with an error, you are one by one validating then and focusing on them as well due to which last item in the list is getting focus.
Update your code to fix so that you are focusing only on first invalid field:
function validate() {
let cekLengthError = 0;
let foundElemWithError = false;
$(".not-empty").each(function(i, obj) {
if ($(this).children('input').val() == "") {
$(this).children('input').next().addClass("show");
if (!foundElemWithError) { // only focus on first invalid field
foundElemWithError = true;
$(this).children('input:first').focus();
}
cekLengthError = cekLengthError + 1;
} else {
$(this).next().removeClass("show");
}
});
if (cekLengthError == 0) {
alert("success")
}
}
I have a textbox called 'Label' and another select box called 'Validation'. When I click on the add button, the value of the textbox 'Label' appends to the form on left with a newly created textbox like this.
Now what I am trying to do is, I'm trying to add validation to the dynamically created textbox from the list of validation options available in the select box in the form on right(alphabets or numbers).
ie, when I type 'New Age' and select 'Numeric' as validation, the 'New Age:' text box created on the left form should only submit if it input is a number. Otherwise display error.
Thanks in advance.
<!DOCTYPE html>
<html>
<head>
<!--<link rel="stylesheet" href="styless.css">-->
<script src="https://code.jquery.com/jquery-3.3.1.js"></script>
<script>
var Errors = [];
</script>
<script src="newfunc.js"></script>
<script>
$(document).ready(function () {
$("#name").on("input", function () {
nameCheck();
});
$("#age").on("input", function () {
ageCheck();
});
$("#gender").on("input", function () {
genderCheck();
});
$("#vehicle").on("input ", function () {
vehicleCheck();
});
$("#cars").on("input", function () {
carsCheck();
});
var x = 1;
function appendRow() {
var d = document.getElementById('divis');
d.innerHTML += "<input type='text' id='tst" + x++ + "'><br >";
}
$("form[name='form1']").on("submit", function (event) {
if (!nameCheck()) {
Errors.push("Please enter a valid name");
event.preventDefault();
}
if (!ageCheck()) {
Errors.push("Please enter a valid age");
event.preventDefault();
}
if (!genderCheck()) {
Errors.push("Please select gender");
event.preventDefault();
}
if (!carsCheck()) {
Errors.push("Please select a valid make");
event.preventDefault();
console.log(Errors);
}
if (!vehicleCheck()) {
Errors.push("Please check a mode");
event.preventDefault();
} else {
$(this).trigger("submit");
}
});
$("form[name='form2']").on("submit", function (event) {
var lab = $("#label").val();
$('#divis').append(lab);
appendRow();
$('#ol_div').append($('#todd'));
// $('#dono').remove();
event.preventDefault();
});
});
</script>
<style>
.error p {
display: inline-block;
color: red;
}
form p {
display: none;
}
.inlineinput div {
display: inline;
}
.one {
display: inline;
}
.two {
display: inline;
}
</style>
</head>
<body>
<div class="main" style="width:100%;">
<div id="old_div" style="float:left; width:50%;">
<form name="form1" action="fun.php" method="post" onsubmit="validateAllInputBoxes(event);">
<div class="name">
<label>Name : </label>
<input id='name' name='dedede' type='text'><br>
<p id="p1"></p>
</div>
<br>
<div class="age">
<label>Age : </label>
<input id='age' name='subject' type='text'><br>
<p id="p2"></p>
</div>
<br>
<div class="gender">
<label>Gender : </label>
<input id='gender' type='radio' name='sel' value='male'>Male
<input id='gender' type='radio' name='sel' value='female'>Female<br>
<p id="p3"></p>
</div>
<br>
<div class="vehicle">
<label>Vehicle : </label>
<input type="checkbox" id="vehicle" name='vehicle' value="Car">Car
<input type="checkbox" id="vehicle" name='vehicle' value="Bike">Bike
<input type="checkbox" id="vehicle" name='vehicle' value="Other">Other<br>
<p id="p4"></p>
</div>
<br>
<div class="cars">
<label>Car Make:</label>
<select name="cars" id="cars" ">
<option value="-1" selected disabled="disabled">Choose an option</option>
<option value="volvo">Volvo</option>
<option value="saab">Saab</option>
<option value="fiat">Fiat</option>
<option value="audi">Audi</option>
</select>
<br>
<p id="p5"></p>
</div>
<br>
<div id="ol_div">
</div>
<div>
<button id="submit" class="sendButton">Submit</button>
</div>
</form>
<br/>
</div>
<div style="float:right; width:50%; ">
<div id="new_div">
<form name="form2" method="post">
<span class="inlineinput">
<div class="name">
<label>Label : </label>
<input id='label' name='dedede' type='text'>
</div>
</span>
<span class="inlineinput">
<div class="name">
<label>Validation:</label>
<select name="vali" id="vali" ">
<option value="-1" selected disabled="disabled">Choose an option</option>
<option value="1">Numerics</option>
</select>
</div>
</span>
<span class="inlineinput">
<div>
<button id="dono" class="newButton">Add</button>
</div>
</span>
<br>
<br>
<div id="todd">
<div class="one" id="labe"></div>
<div class="two" id="divis"></div>
<br><br>
</div>
<br>
</form>
</div>
</div>
</body>
</html>
newfunc.js
function nameCheck() {
var name = $('#name').val();
var name_regex = /^[A-z]+$/;
if (!name_regex.test(name)) {
$('#p1').text("* Please enter a valid name *");
$("#name").parents(".name").addClass("error");
return false;
} else {
$("#name").parents(".name").removeClass("error");
return true;
}
}
function ageCheck() {
var age = $('#age').val();
var age_regex = /^[0-9]+$/;
if (!age_regex.test(age)) {
//Errors.push("Please enter a valid age");
$('#p2').text("* Please enter a valid age *");
$("#age").parents(".age").addClass("error");
return false;
} else {
$("#age").parents(".age").removeClass("error");
return true;
}
}
function labelCheck() {
var label = $('#label');
if (label.val().length > 0) {
//Errors.push("Please enter a valid age");
$('#p2').text("* Please enter a valid label *");
$("#label").parents(".label").addClass("error");
return false;
} else {
$("#label").parents(".label").removeClass("error");
return true;
}
}
function genderCheck() {
var gender = $('#gender').val();
if ($('input[type=radio]:checked').length <= 0) {
//Errors.push("Please select Gender");
$('#p3').text("* Please select the Gender *");
$("#gender").parents(".gender").addClass("error");
return false;
} else {
$("#gender").parents(".gender").removeClass("error");
return true;
}
}
function vehicleCheck() {
var vehicle = $('#vehicle').val();
if ($('input[id=vehicle]:checked').length == 0)
{
//Errors.push("Please select a vehicle");
$('#p4').text("* Please select a vehicle *");
$("#vehicle").parents(".vehicle").addClass("error");
return false;
} else {
$("#vehicle").parents(".vehicle").removeClass("error");
return true;
}
}
function carsCheck() {
var cars = $('#cars').val();
if (document.form1.cars.value == "-1")
{
//Errors.push("Please select one car make");
$('#p5').text("* Please select one car make *");
$("#cars").parents(".cars").addClass("error");
return false;
} else {
$("#cars").parents(".cars").removeClass("error");
return true;
}
}
(function ($) {
$.fn.selected = function (fn) {
return this.each(function () {
$(this).focus(function () {
this.dataChanged = false;
}).change(function () {
this.dataChanged = true;
fn(this);
}).blur(function (e) {
if (!this.dataChanged) {
fn(this);
}
});
});
};
})(jQuery);
In your case, I would probably add an array called validations and push a new validation function on it every time you add a new text box. On submit, I'd check each function in the validations array and output possible errors. If there was no error, submit, otherwise show the errors.
You could create a function that returns a validation function. For example:
function createNumericValidationForField($yourNewElement) {
return function () {
// your logic here, for example:
try {
return { result: parseInt($yourNewElement.value()) };
} catch (err) {
return { error: err };
}
};
}
Then you can go through the validations array, call each of these functions and check if there is a result or error inside the returned objects.
Well, you can do this in multiple ways.
1. Write a validation for every input field you want to implement
The most efficient way for this would be to write checks with RegEx like this:
Numbers
const numbers = new RegExp(/^[0-9]+$/);
numbers.test(yourString)
Characters
const characters = new RegExp(/^[a-zA-Z]*$/);
characters.test(yourString);
The test() function returns either true or false when checking your variable against the specified RegExp.
You can do this on every onChange() event the input calls to have a nice and fast response for the user, or you can use it right before submitting the form.
You can add this to the onChange() event while constructing your input field, like this:
var newObject = document.createElement('input');
newObject.onchange = numberValidation();
2. Change the input type when you construct it
As you are dynamically create your label and input fields you can easily change that inputs type:
var newObject = document.createElement('input');
newObject.type = 'password'; // can be password, number, tel, etc.
These input types prevent typing wrong values.
I wrote the below code for changing the text of div that called active yes, based on value of each input with type hidden.
i want to change the text of this div if input with id enable to "Enable List" and if input with classname delete has value changes the div text to "Deleted list" and if both of them was null show "list".
my code does not work correctly.
what is my problem?
here is my snippet :
$(document).ready(function() {
tmpval = $('#enable').val();
if (tmpval == '') {
$('.activeyes').text('list');
} else {
$('.activeyes').text('Enable List');
}
tmpval2 = $('#delete').val();
if (tmpval2 == '') {
$('.activeyes').text('List');
} else {
$('.activeyes').text('Deleted List');
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.1/jquery.min.js"></script>
<input type="text" value="aa" id="enable" />
<input type="text" value="" id="delete" />
<h1 class="activeyes"> List</h1>
You are overwriting effect of the first check by the second check; you need to check the 2 inputs value together. Still, it is unclear what will happen if both are non-empty.
$(document).ready(function() {
tmpval = $('#enable').val();
tmpval2 = $('#delete').val();
if (tmpval == '' && tmpval2 == '') {
$('.activeyes').text('list');
} else if( tmpval!='' ){
$('.activeyes').text('Enable List');
} else if( tmpval2!='' ){
$('.activeyes').text('Deleted List');
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.1/jquery.min.js"></script>
<input type="text" value="aa" id="enable" />
<input type="text" value="" id="delete" />
<h1 class="activeyes"> List</h1>
what is my problem?
You need to check the value of input when it changes its value, so capture the change event.
$(document).ready(function() {
$('#enable, #delete').change(function() {
var $this = $(this);
var id = $this.attr("id");
var value = $this.val();
if (value.length == 0)
{
$('.activeyes').text('list');
}
else
{
id == "enable" ? $('.activeyes').text('Enable List') : $('.activeyes').text('Deleted List');
}
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.1/jquery.min.js"></script>
<input type="text" value="aa" id="enable" />
<input type="text" value="" id="delete" />
<h1 class="activeyes"> List</h1>
html
<form action="" id="formsave">
<div class="row">
<input type="text" id="test1"name="test1">
<input type="text" id="test2"name="test2">
</div>
</form>
I have two input fields, If test1 have a value it required test2 if not it would not required. It means if test1 is have a value, you cannot save the form without test2 value. if test1 is null test2 is not required.
Try this
<html>
<head>
<script>
function check() {
var test1 = document.getElementById("test1").value
var test2 = document.getElementById("test2").value
if ((!!test1 && !!test2) || !test1) {
return true
} else {
document.getElementById("errmsg").innerHTML = "test2 required"
return false
}
}
</script>
</head>
<body>
<form onsubmit="return check()">
<input type="text" id="test1">
<input type="text" id="test2">
<input type="submit">
<div id="errmsg"></div>
</form>
</body>
</html>
Check the value of test1 when the form is saved.
$("#save").on('click', function() {
if($("#test1").val()) {
alert("please enter all data");
} else {
$("#formsave").submit();
}
});
Something like that
var form = document.getElementById('formsave'),
check = function() {
var input1 = document.getElementById('test1'),
input2 = document.getElementById('test2');
if (input1.value !== '' && input2.value === '') {
return false;
} else return true;
};
form.addEventListener('submit', function(e) {
if (check()) {
// do stuff here
} else e.preventDefault();
});
I have a form containing various fields.
See jsFiddle demo.
My aim is to enable the submit button only when the user has filled in all fields.
So far, I'm able to force the title field to have content before submit button is enabled. How do I make it so that all other fields need to be filled too before submit button is enabled.
jQuery("input[type='text']").on("keyup", function () {
if (jQuery(this).val() != "" ) {
if (jQuery("#titlenewtide").val() != '')
{
jQuery("#subnewtide").removeAttr("disabled");
}
} else {
jQuery("#subnewtide").attr("disabled", "disabled");
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form action="#" method="post" id="new_tide">
Title: <input id="titlenewtide" type="text" name="title" required> <br>
Description: <textarea name="description" id="description"></textarea> <br>
Tag: <input id="newtag" type="text" name="newtag" required> <br>
Category: <input type="radio" name="category" value="19" required> Animation
<button type="submit" value="Submit" name="subnewtide" id="subnewtide" disabled="disabled">Submit</button>
</form>
Note that I am loading the JavaScripts in my footer.
Make the changes take effect after changing inputs values:
On each input change, test the values of other inputs and checked state of radio, if all inputs has been entered it will make the submit button enabled:
var validateInputs = function validateInputs(inputs) {
var validForm = true;
inputs.each(function(index) {
var input = $(this);
if (!input.val() || (input.type === "radio" && !input.is(':checked'))) {
$("#subnewtide").attr("disabled", "disabled");
validForm = false;
}
});
return validForm;
}
inputs.change(function() {
if (validateInputs(inputs)) {
$("#subnewtide").removeAttr("disabled");
}
});
Demo:
var inputs = $("form#myForm input, form#myForm textarea");
var validateInputs = function validateInputs(inputs) {
var validForm = true;
inputs.each(function(index) {
var input = $(this);
if (!input.val() || (input.type === "radio" && !input.is(':checked'))) {
$("#subnewtide").attr("disabled", "disabled");
validForm = false;
}
});
return validForm;
}
inputs.change(function() {
if (validateInputs(inputs)) {
$("#subnewtide").removeAttr("disabled");
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form action="#" method="post" id="myForm">
Title:
<input id="titlenewtide" type="text" name="title" required>
<br>Description:
<textarea name="description" id="description"></textarea>
<br>Tag:
<input id="newtag" type="text" name="newtag" required>
<br>Category:
<input type="radio" name="category" value="19" required>Animation
<button type="submit" value="Submit" name="subnewtide" id="subnewtide" disabled="disabled">Submit</button>
</form>
Also it uses the form id="myForm", so you can use it to validate only specific forms in your pages.
Note: This is tested and working on Chrome, Firefox and IE.
EDIT:
Make the changes take effect when we type in the inputs:
In the previous code we are using onchange event handler to call the function so it's only called when we click outside a given input (after change).
To perform the call automatically when the user enters a character in a field (the last one) we need to use the onkeyup event so we don't need to click outside of it.
This is the changed code you need :
var inputs = $("form#myForm input, form#myForm textarea");
var validateInputs = function validateInputs(inputs) {
var validForm = true;
inputs.each(function(index) {
var input = $(this);
if (!input.val() || (input.type === "radio" && !input.is(':checked'))) {
$("#subnewtide").attr("disabled", "disabled");
validForm = false;
}
});
return validForm;
}
inputs.each(function() {
var input = $(this);
if (input.type === "radio") {
input.change(function() {
if (validateInputs(inputs)) {
$("#subnewtide").removeAttr("disabled");
}
});
} else {
input.keyup(function() {
if (validateInputs(inputs)) {
$("#subnewtide").removeAttr("disabled");
}
});
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form action="#" method="post" id="myForm">
Title:
<input id="titlenewtide" type="text" name="title" required>
<br>Description:
<textarea name="description" id="description"></textarea>
<br>Tag:
<input id="newtag" type="text" name="newtag" required>
<br>Category:
<input type="radio" name="category" value="19" required>Animation
<button type="submit" value="Submit" name="subnewtide" id="subnewtide" disabled="disabled">Submit</button>
</form>
Use this code below. On each input, it will check all the form fields by using this function validate().
jQuery("input[type='text'], textarea").on("input", function () {
var isValid = validate();
if (isValid) {
jQuery("#subnewtide").removeAttr("disabled");
} else {
jQuery("#subnewtide").attr("disabled", "disabled");
}
});
function validate() {
var isValid = true;
$('input, textarea').each(function() {
if ($(this).val() === '')
isValid = false;
});
return isValid;
}
Fiddle
Update
To make it validate if the form has id="new_tide" and fix about the radio button.
$("input[type='text'], textarea").on("change input", function() {
validate($(this));
});
$("input:radio[name='category']").on("change", function() {
validate($(this));
});
function validate(self) {
if (self.parents("form:first").attr("id") == "new_tide") {
var isValid = true;
$('input[type="text"], textarea').each(function() {
if ($(this).val() === '')
isValid = false;
});
if (!$("input:radio[name='category']").is(':checked'))
isValid = false;
if (isValid) {
$("#subnewtide").removeAttr("disabled");
} else {
$("#subnewtide").attr("disabled", "disabled");
}
}
}
Fiddle
Here's how you can do it:
$(document).ready(function () {
var $inputs = $("#new_tide input:not([type=hidden]), #new_tide textarea");
$inputs.on("input change", function () {
valid = true;
$inputs.each(function () {
valid *= this.type == "radio" ? this.checked : this.value != "";
return valid;
});
$("#subnewtide").prop("disabled", !valid);
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script>
<form action="#" method="post" id="new_tide">
Title: <input id="titlenewtide" type="text" name="title" required> <br>
Description: <textarea name="description" id="description"></textarea> <br>
Tag: <input id="newtag" type="text" name="newtag" required> <br>
Category: <input type="radio" name="category" value="19" required> Animation
Hidden: <input type="hidden">
<button type="submit" value="Submit" name="subnewtide" id="subnewtide" disabled="disabled">Submit</button>
</form>
Try utilizing .siblings() , .map() to compile values of form elements , Array.prototype.every() to return Boolean representation of input , textarea values , set disabled property of form input[type=submit] element
$("form *[required]").on("input change", function(e) {
$(this).siblings("[type=submit]").prop("disabled"
, !$(this).siblings(":not([type=submit])").add(this).map(function(_, el) {
return el.type === "radio" ? el.checked : el.value
}).get().every(Boolean)
);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js">
</script>
<form action="#" method="post" id="new_tide">
Title: <input id="titlenewtide" type="text" name="title" required> <br>
Description: <textarea name="description" id="description" required></textarea> <br>
Tag: <input id="newtag" type="text" name="newtag" required> <br>
Category: <input type="radio" name="category" value="19" required> Animation
<button type="submit" value="Submit" name="subnewtide" id="subnewtide" disabled="disabled">Submit</button>
</form>
By far the easiest, would be to rely on the HTML5 validation you're already using.
You'd have to add required to all form controls if you want to require all of them, and that can easily be done by using jQuery's :input selector and setting the property, like so
$(':input:not(#subnewtide)').prop('required', true)
We'll exclude the submit button, as that doesn't have to be required, obviously, not that it would matter in this case.
Then we'll listen for the input event, which covers all sorts of inputs, like typing, pasting etc, and the change event as well to cover the radio button.
Using form.checkValidity() tells us if the form is valid, and returns a boolean, so we could use it directly to set the disabled property of the submit button.
All together it looks like this, and that's all you need, a few lines of really simple code
$(':input:not(#subnewtide)').prop('required', true).on('input change', function() {
$('#subnewtide').prop( 'disabled', !this.form.checkValidity() );
});
FIDDLE
If you have to support old browsers that don't have HTML5 validation, you can use the H5F polyfill
My solution is base on standard JavaScript.
HTML form
<form action="#" method="post" id="new_tide" name="form1">
Title: <input onkeyup="myBtnActivator(1)" id="titlenewtide" name="title" type="text" required> <br>
Description: <textarea onkeyup="myBtnActivator(2)" id="description" name="description"></textarea> <br>
Tag: <input id="newtag" onkeyup="myBtnActivator(3)" name="newtag" type="text" required> <br>
Category: <input name="category" onchange="myBtnActivator(4)" type="radio" value="19" required> Animation
<button id="subnewtide" name="subnewtide" type="submit" value="Submit">Submit</button>
</form>
JavaScript
<script>
document.getElementById("subnewtide").disabled = true;
var input1 = false;
var input2 = false;
var input3 = false;
var input4 = false;
function myBtnActivator(i) {
switch (i) {
case 1:
input1 = true;
if (document.form1.title.value == "")
input1 = false;
break;
case 2:
input2 = true;
if (document.form1.description.value == "")
input2 = false;
break;
case 3:
input3 = true;
if (document.form1.newtag.value == "")
input3 = false;
break;
case 4:
input4 = true;
if (document.form1.subnewtide.value == "")
input4 = false;
break;
}
trigger();
}
function trigger() {
if (input1 == true && input2 == true && input3 == true && input4 == true) {
document.getElementById("subnewtide").disabled = false;
} else {
document.getElementById("subnewtide").disabled = true;
}
}
</script>
Why don't you use jquery validate . It's a good plugin .
The logic works like, any change in the form it will check the form is valid or not. And also using the errorplacement function it will disable the default error message also.
$().ready(function() {
// validate signup form on keyup and submit
$("#contactForm").validate({
rules: {
title: "required",
description: {
required: true
},
newtag: {
required: true
},
category: {
required: true
}
},
errorPlacement: function(error, element) {
return true;
},
submitHandler: function() {
}
});
$('#contactForm').change(function() {
if ($("#contactForm").valid()) {
$("#subnewtide").removeAttr("disabled");
}
});
});
Fiddle
There's actually a pretty easy approach. I'm using native JavaScript, but I think it is applicable in jQuery as well:
var form = document.getElementById("new_tide");
form.onchange = function onChange() {
var enable = true;
var inputs = form.getElementsByTagName("input");
var textareas = form.getElementsByTagName("textarea");
for (var i in inputs) {
enable = enable && inputs[i].value != "";
}
for (var i in textareas) {
enable = enable && textareas[i].value != "";
}
enable = enable && textarea.value != "";
document.getElementById("subnewtide").disabled = !enable;
}
The change event on form is always called, when any input or textarea element was changed (click in element, type, click somewhere else or lose focus).
Edit:
Regarding hidden fields, you can exclude them by surrounding the enable calculation with an if-condition:
if (!inputs[i].hidden) {
enable = enable && inputs[i].value != "";
}
Note:
This will work in any browser (even Internet Explorer 5.5). Check on MDN:
for ..in Loop
element.getElementsByTagName()
document.getElementById()
Thought I might chip in. Assuming as little as possible.
jQuery("input, textarea").on("keyup click", function () { // going vanilla after easy-mode attach
var sub = document.getElementById('subnewtide');
if (require_all(find_form(this))) {
sub.removeAttribute('disabled');
sub.disabled = false;
} else {
sub.setAttribute('disabled', 'disabled');
sub.disabled = true;
}
});
function concat(a, b) { // concating Array-likes produces Array
var slice = [].slice; // not assuming Array.prototype access
return [].concat.call(
slice.call(a, 0),
slice.call(b, 0)
);
}
function find_form(e) { // shim input.form
if (e) do {
if (e.tagName === 'FORM') return e;
} while (e = e.parentNode);
return null;
}
function require_all(form, dontIgnoreHidden) { // looks at textareas & inputs (excluding buttons)
var inp = concat(form.getElementsByTagName('input'), form.getElementsByTagName('textarea')),
rad = {}, // not assuming Object.create
i, j,
has = {}.hasOwnProperty; // not assuming Object.prototype access
for (i = 0; i < inp.length; ++i) {
switch ((inp[i].type || '').toLowerCase()) {
default: // treat unknown like texts
case 'text':
if (!inp[i].value) return false; break;
case 'checkbox':
if (!inp[i].checked) return false; break;
case 'radio':
j = inp[i].getAttribute('name');
if (!rad[j]) rad[j] = inp[i].checked;
break;
case 'hidden':
if (dontIgnoreHidden && !inp[i].value) return false; break;
case 'button':
case 'submit':
break;
}
}
for (j in rad) if (!has || has.call(rad, j)) // not assuming hasOwnProperty
if (!rad[j]) return false;
return true;
}
Here is a quick way to accomplish that. It involves attaching a change event listener to :radio and :checkbox elements and an input event listener to other elements. These can both use a common predefined handler that will count the number of unfilled element each time each of these events fires on the appropriate element.
function checkForm() {
//define and initialize variables
var unfilled = 0,
form = $(this.form);
//disable submit button if enabled
$(':submit', form).prop('disabled', true);
//count number of unfilled elements
$(':input', form).each(function() {
if( $(this).is(':radio,:checkbox') ) {
$('input[name=' + this.name + ']:checked').length || unfilled++;
} else {
$('[name=' + this.name + ']').val() || unfilled++;
}
});
//enable submit button if no unfilled element is found
unfilled || $(':submit', form).prop('disabled', false);
}
//set up event listeners to fire above handler
$(':text,textarea,select').on('input', checkForm);
$(':radio,:checkbox').on('change', checkForm);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<form action="#" method="post" id="new_tide">
Title: <input id="titlenewtide" type="text" name="title" required> <br>
Description: <textarea name="description" id="description"></textarea> <br>
Tag: <input id="newtag" type="text" name="newtag" required> <br>
Category: <input type="radio" name="category" value="19" required> Animation
<button type="submit" value="Submit" name="subnewtide" id="subnewtide" disabled="disabled">Submit</button>
</form>
var inputs = $("form#myForm input, form#myForm textarea");
var validateInputs = function validateInputs(inputs) {
var validForm = true;
inputs.each(function(index) {
var input = $(this);
if (!input.val() || (input.type === "radio" && !input.is(':checked'))) {
$("#subnewtide").attr("disabled", "disabled");
validForm = false;
}
});
return validForm;
}
inputs.each(function() {
var input = $(this);
if (input.type === "radio") {
input.change(function() {
if (validateInputs(inputs)) {
$("#subnewtide").removeAttr("disabled");
}
});
} else {
input.keyup(function() {
if (validateInputs(inputs)) {
$("#subnewtide").removeAttr("disabled");
}
});
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form action="#" method="post" id="myForm">
Title:
<input id="titlenewtide" type="text" name="title" required>
<br>Description:
<textarea name="description" id="description"></textarea>
<br>Tag:
<input id="newtag" type="text" name="newtag" required>
<br>Category:
<input type="radio" name="category" value="19" required>Animation
<button type="submit" value="Submit" name="subnewtide" id="subnewtide" disabled="disabled">Submit</button>
</form>
Use this html<br>
HTML:
<br>
<pre>
<form action="#" method="post" id="">
Title: ##<input id="titlenewtide" type="text" name="title" required>
Description: <textarea name="description" id="description"></textarea>
Tag: <input id="newtag" type="text" name="newtag" required>
Category: <input type="checkbox" onclick="validate()" name="category" id="cate"value="19" required > Animation
<button type="submit" value="Submit" name="subnewtide" id="subnewtide" disabled="disabled">Submit</button>
</form>
</pre>
validation code:<br>
//on each key up function intiate the function validate
<pre>
jQuery("input[type='text']").on("keyup", function () {
validate();
});
jQuery("#description").on("keyup", function () {
validate();
});
function validate(){
jQuery("input[type='text']").each(function(){
if (jQuery(this).val() != "" )
{
if((jQuery("#description").val() !="") && (jQuery("#cate").is(':checked')))
{
jQuery("#subnewtide").removeAttr("disabled");
}
else {
jQuery("#subnewtide").attr("disabled", "disabled");
}
}
});
}
</pre>
you can find the fiddle in : https://jsfiddle.net/s8uv2gkp/
Maytham Fahmi's relatively easy solution can be made even easier by passing this.name.
<form action="#" method="post" id="new_tide" name="form1">
<input onkeyup="myBtnActivator(this.name)" name="title" type="text" required> <br>
<textarea onkeyup="myBtnActivator(this.name)" name="description"></textarea> <br>
<input id="newtag" onkeyup="myBtnActivator(this.name)" name="newtag" type="text" required> <br>
<input name="category" onchange="myBtnActivator(this.name)" type="radio" value="19" required> Animation
<button id="subnewtide" name="subnewtide" type="submit" value="Submit">Submit</button>
</form>
this refers to the DOM object that called the function. So the switch can just directly take the name, or the value, or anything else you can pass with DOM.
myBtnActivator(n)
{
switch(n)
{
case "title":
break;
case "description":
break;
case "newtag":
break;
case "category":
break;
}
}