Having Issue on Using each() With Multiple Input Validate - javascript

Can you please take a look at this demo and let me know why I am not able to use the each iterator to check empty inputs?
$('#test').on('click', function(e){
e.preventDefault();
$("input").each(function(){
if($(this).val().length > 0){
$(this).addClass('error');
}
});
});
.error{background-color:red;}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="upper">a</div>
<div class="lower">b</div>
<input type="text" id="txt1">
<div class="upper">7</div>
<div class="lower">w</div>
<input type="text" id="txt2">
<div class="upper">o</div>
<div class="lower">66</div>
<input type="text" id="txt3"><br />
<br />
<button id="test">Test</button>

Try:
$('#test').on('click', function(e){
e.preventDefault();
$("input").each(function(i,v){
console.log($(v).val().length)
if($(v).val().length == 0){
$(v).addClass('error');
}
});
});
.error{border-color:red;}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="upper">a</div>
<div class="lower">b</div>
<input type="text" id="txt1">
<div class="upper">7</div>
<div class="lower">w</div>
<input type="text" id="txt2">
<div class="upper">o</div>
<div class="lower">66</div>
<input type="text" id="txt3"><br />
<br />
<button id="test">Test</button>

<input> elements at html at Question do not have value attribute to return .length of ?
Try setting value attribute at input elements to retrieve $(this).val() or this.value within .each() ; substituting .toggelClass() for .addClass() to toggle "error" class at #test element click event if input .length changes
$("#test").on("click", function(e) {
e.preventDefault();
$("input").each(function() {
$(this).toggleClass("error", !this.value.length);
});
});
.error {
background-color: red;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js">
</script>
<div class="upper">a</div>
<div class="lower">b</div>
<input type="text" id="txt1" value="">
<div class="upper">7</div>
<div class="lower">w</div>
<input type="text" id="txt2" value="1">
<div class="upper">o</div>
<div class="lower">66</div>
<input type="text" id="txt3" value="">
<br />
<br />
<button id="test">Test</button>

i have no problem with your code, everything is running.
if i fill something into the inputs then it is running into the if-clause.
but what you want to do with "error"? since version 1.8 it is deprecated and
in your coding there is no error-handler, you give a string as parameter to error not a handler (function).
read : https://api.jquery.com/error/
in your case it is better to give the parent-element to the each function like:
$("input","body").each(
if you want to work with error, then:
$('#myelement').on('error',function(){ /*your error code */});
for your example it is not the right way to bind the error handler on your input-element, if you want to check the values of the inputs. the error-handler catch thinks like "undefined" but it is not a system-error if your inputs are empty.
try:
if($(this).val().length > 0){
console.log('Input Val has ' + this).val().length + ' characters')
}

If I understand your query correctly, you want the empty input fields to be highlighted once you click the "Test" button, while the one's with values should not be highlighted. If so, then please check this solution:
$('#test').on('click', function(e){
e.preventDefault();
$("input").each(function(){
if($(this).val().length == 0){
$(this).addClass('error');
}else{
$(this).removeClass('error');
}
});
});
.error{background-color:red;}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="upper">a</div>
<div class="lower">b</div>
<input type="text" id="txt1">
<div class="upper">7</div>
<div class="lower">w</div>
<input type="text" id="txt2">
<div class="upper">o</div>
<div class="lower">66</div>
<input type="text" id="txt3"><br />
<br />
<button id="test">Test</button>

Related

JQuery form validation on clicking Submit, check all input fields are empty and show innerHTML error not working?

I am trying to create a form validation using HTML and JQuery to check that all the input fields are not empty when a "Submit" button is clicked. If any of them are empty, the Submit button will not process the form, and will change the color of the empty input fields to Yellow and display a message at the bottom of the form (using innerHTML in a .
This are the relevant HTML codes:
<body>
<div id="div_main">
<form action="process.html" method="POST">
<div id="div_left">
<p>Name:</p>
<p>Age:</p>
<p>Gender:</p>
</div>
<div id="div_right">
<p><input type="text" id="name" name="name"></p>
<p><input type="text" id="age" name="age"></p>
<p><input type="text" id="gender" name="gender"></p>
</div>
<input type="submit" id="chksubmit" value="submit"/>
<div id="divmessage"></div>
</form>
</div>
</body>
And these are my relevant JQuery codes to perform the validation:
<script src="jquery-3.3.1.min.js"></script>
<script>
$(document).ready(function(){
$('#chksubmit').click(function(){
if($('#name').val()==''){
$('#name').css('background-color','yellow');
$('#divmessage').append("Please enter Name.")
success = false;
}
});
$('#chksubmit').click(function(){
if($('#age').val()==''){
$('#age').css('background-color','yellow');
$('#divmessage').append("<br>Please enter Age.")
success = false;
}
});
$('#chksubmit').click(function(){
if($('#gender').val()==''){
$('#gender').css('background-color','yellow');
$('#divmessage').append("<br>Please enter Gender.")
success = false;
}
});
});
</script>
When I click the Submit with empty input boxes, the form still goes through instead of stopping. I can't figure out why.
Check the below example
$(document).ready(function() {
$('#chksubmit').on("click", function(e) {
//clean divmessage
$('#divmessage').html("");
//or use $("#div_main form input") to check all inputs
$("#name, #age, #gender").each(function() {
$(this).css('background-color', '');;
if ($(this).val().replace(/\s+/g, " ").trim() == '') {
$(this).css('background-color', 'yellow');
success = false;
$('#divmessage').append("<br>Please enter " + $(this).data("for"))
}
});
e.preventDefault();
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="div_main">
<form action="process.html" method="POST">
<div id="div_left">
<p>Name:</p>
<p>Age:</p>
<p>Gender:</p>
</div>
<div id="div_right">
<p><input type="text" data-for="Name" id="name" name="name"></p>
<p><input type="text" data-for="Age" id="age" name="age"></p>
<p><input type="text" data-for="Gender" id="gender" name="gender"></p>
</div>
<input type="submit" id="chksubmit" value="submit" />
<div id="divmessage"></div>
</form>
</div>

How can I listen to all inputs that have a "required" attribute?

EDIT :
I have an input field and a checkbox. Checkbox allow to win "required" on this input field. I want to listen required, i mean if required is true or not. I don't want to listen checkbox.
==> When input win/lose required attribute, it trigger function (without use checkbox).
$(document).ready(function() {
$('input[type=checkbox]').click(function() {
cible_required_on = $(this).closest('.panel').find('.required_on');
if(!cible_required_on.prop('required')){
cible_required_on.attr("required", true);
} else {
cible_required_on.attr("required", false);
}
});
// Here my new function listening required attribute
});
<!DOCTYPE html>
<html lang="fr">
<head>
<meta charset="UTF-8">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.4/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.4/js/bootstrap.min.js"></script>
</head>
<body>
<div class="panel panel-default" >
<div class="container-fluid">
<div class="row">
<div class="col-sm-12 col-md-4 changement_position_champ" id="bottom_left">
<div class="panel">
<label> Raison Sociale</label>
<div class="input-group">
<span class="input-group-addon"><i class="glyphicon glyphicon-use" ></i></span>
<input type="text" class="form-control required_on" placeholder="Raison sociale"
aria-describedby="basic-addon1">
</div>
</div>
<div class="checkbox">
<label><input type="checkbox" ><p>Checkbox trigger required on input field</p></label>
</div>
</div>
</div>
</div>
</div>
</body>
</html>
$('input[required]').change(function(){
alert('required')
});
$('input[required]').change(function(){
alert('required')
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" required/>
<input type="text" />
Knowing I'm late to the party, here's my contribution:
// ES6 supported - () => {} , arrow-function
$(':input[required]').change((e) => {
alert("Changed: " + e.target.value);
});
// Older compatibility
/*
$(':input[required]').change(function(e) {
alert("Changed: " + e.target.value);
});
*/
input {
width: 200px;
display: block;
margin-bottom: 5px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<p>Type something and unfocus from input.</p>
<form action="#">
<input type="text" required />
<input type="text" required />
<input type="checkbox" required />
<input type="text" />
<input type="submit" />
</form>
As mentioned in the question the user requires to select the input with some conditions like it is the checkbox and is required. So instead of running a loop which is more memory eating, we can use the jquery filter selectors to achieve the goal.
Below is the example.
var a = $('input[required][type="checkbox"]');
console.log(a)
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type='checkbox' required>

The order of my jquery validator is working wrong, and I have no idea why

My form validator works, but it works in a certain order, if I check the checkbox, it works fine, but if I fill the inputs first and then use the checkbox, it not works, unless I type something in the inputs
$(document).ready(function() {
$('#send').attr('disabled', true);
$('.input,#check').on('keyup', function() {
var text_value = $('.input-cpk').val();
if (text_value !== '' && (document.getElementById('check').checked)) {
$('#send').attr('disabled', false);
} else {
$('#send').attr('disabled', true);
}
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form class="block oh fr col-9 margem-d2 text-left" action="enviar-calculo.php" method="post" target="votar" name="cpk">
<input type="text" name="nome" id="nome" class="input-cpk col-20">
<input type="number" name="telefone" class="input-cpk-tel">
<input type="submit" value="CALCULAR" id="send" class="f-josefin-s-b f-branca bg-amarelo botao" onclick="output();">
<input type="checkbox" id="check" name="others" />
</form>
You only run your validation code during the keyup event, which only happens on the input boxes. You also need to do validation during a click event on the checkbox.
You can put multiple event names in the argument to .on(), to handle both with the same code.
You also have an incorrect class .input, there are no elements with class="input" in the HTML. I've changed it to .input-cpk.
$(document).ready(function() {
$('#send').prop('disabled', true);
$('.input-cpk,#check').on('keyup click', function() {
var text_value = $('.input-cpk').val();
if (text_value !== '' && (document.getElementById('check').checked)) {
$('#send').prop('disabled', false);
} else {
$('#send').prop('disabled', true);
}
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form class="block oh fr col-9 margem-d2 text-left" action="enviar-calculo.php" method="post" target="votar" name="cpk">
<input type="text" name="nome" id="nome" class="input-cpk col-20">
<input type="number" name="telefone" class="input-cpk-tel">
<input type="submit" value="CALCULAR" id="send" class="f-josefin-s-b f-branca bg-amarelo botao" onclick="output();">
<input type="checkbox" id="check" name="others" />
</form>
It's because you're using the wrong selector.
Try this
$('input,#check').on('keyup', function() {
Instead of this
$('.input,#check').on('keyup', function() {
Additionally you might want to use the .on('change') instead of .on('keyup')

javascript to remove dynamically added div

i have 3 textfield which i want to clone with one remove icon on add button click ...upto this my code works fine.
Now i want to remove the last 3 textfields of that particular div on remove button click...but my code removes all the dynamically added textfields of my form..
please help me to resolve this....
$('#add_exercise').on('click', function() {
$('#exercises').append('<div class="exercise"><input type="text" name="exercise[]"></div>');
$('#exercises').append('<div class="exercise"><input type="text" name="exercise[]"></div>');
$('#exercises').append('<div class="exercise"><input type="text" name="exercise[]"><button class="remove">x</button></div>');
return false;
});
$('#exercises').on('click', '.remove', function() {
$(this).parents("#exercises").remove();
return false;
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<fieldset id="exercises">
<div class="exercise">
<input type="text" name="exercise[]">
<input type="text" name="exercise[]">
<input type="text" name="exercise[]">
</div>
<button id="add_exercise">add exercise</button>
<button class="remove">x</button>
</fieldset>
The issue is with your use of .parents('#excercises') as this selects the top level container and removes it.
A better solution would be to wrap all the 3 inputs you append in their own div and then remove that using closest(), like this:
$('#add_exercise').on('click', function() {
$('#exercises').append('<div class="exercise"><input type="text" name="exercise[]"><input type="text" name="exercise[]"><input type="text" name="exercise[]"><button type="button" class="remove">x</button></div>');
});
$('#exercises').on('click', '.remove', function() {
$(this).closest(".exercise").remove();
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<fieldset id="exercises">
<div class="exercise">
<input type="text" name="exercise[]">
<input type="text" name="exercise[]">
<input type="text" name="exercise[]">
<button type="button" class="remove">x</button>
</div>
<button type="button" id="add_exercise">add exercise</button>
</fieldset>
Note that I added type="button" to your <button> elements as it would make sense for them not to submit any parent form elements.

How do I associate button events with a unique control?

I have this form http://jsfiddle.net/thiswolf/XDsSt/ with four identical inputs and buttons.The problem is,each section is updates its own unique data in the database so when updating,its important the submit button i click updates the database with the input from that section only.
My function is
$(document).ready(function() {
$(".xx").live('click', function(){
alert('clicked');
});
});
How do i make sure the button click is unique to that section?.
Use an ID value instead for each input button. This way, jQuery can identify it like so:
$('#button_tag');
HTML:
<html>
<head></head>
<body>
<section>
<input type="text" value="Town">
<input type="text" value="Mayor">
<input type="text" value="Highway">
<input id="btn1" type="submit" class="xx" value="Submit">
</section>
<section>
<input type="text" value="Town">
<input type="text" value="Mayor">
<input type="text" value="Highway">
<input id="btn2" type="submit" class="xx" value="Submit">
</section>
<section>
<input type="text" value="Town">
<input type="text" value="Mayor">
<input type="text" value="Highway">
<input id="btn3" type="submit" class="xx" value="Submit">
</section>
<section>
<input type="text" value="Town">
<input type="text" value="Mayor">
<input type="text" value="Highway">
<input id="btn4" type="submit" class="xx" value="Submit">
</section>
</body>
</html>
Javascript:
$(document).ready(function () {
$(".xx").live('click', function () {
alert('clicked ' + $(this).attr('id'));
});
});
JsFiddle:
http://jsfiddle.net/XDsSt/7/
Get the corresponding section that button belongs to . Then access the elements inside that. You may use the jQuery closest()/parent()(if only one layer of hierarchy of controls) function for that.
$(document).ready(function() {
$(".xx").live('click', function(e){
e.preventDefault(); //if you want to prevent normal form submit
var item=$(this);
var sectionClicked=item.closest("section");
//Let's alert the first text box
alert(sectionClicked.find("input").first().val());
//do whatever with the items belongs the current section
});
});
Sample : http://jsfiddle.net/XDsSt/8/
I recommend you to switch to jQuery on instead of live as it is deprecated.
$(document).ready(function() {
$(".xx").live('click', function() {
$('section').has(this).find(':input:text').each(function() {
alert( this.value ) ;
});
});
});
Demo
If possible then instead of .live(), use .on() with jQUery 1.7+, because live() is deprecated.
$(document).ready(function() {
$("body").on('click', '.xx', function() {
$('section').has(this).find(':input:text').each(function() {
alert( this.value ) ;
});
});
});
Demo
if id is not an option - I don't understand that , but you can put multiple classes in buttons
<input type="button" class="xx btn1" ... >
$(document).ready(function() {
$(".xx").live('click', function(){ // look into on instead on live
if $(this).hasclass('btn1');{
alert('clicked');
}
});
});

Categories

Resources