Validating dynamically created input elements - javascript

I have a form with dynamically created input elements
<input type='button' value='Add Another Product' id='aprod'>
<table id='page3_inside'>
<tr id='ln1'>
<td>
<label for="product_cat">Product Category</label><br>
<input type='text' class="input product_category" name="product_category[]" style="font-family:verdana; width:150px; border: 1px solid #000000;">
</td>
<td>
<label for="qty">Qty</label><br>
<input type="text" value="" class="input qty" style="width:100px;" name="qty[]" placeholder="Qty" onkeypress="return isNumberKey(event)"/>
</td>
<td>
<label for="unit">Unit</label><br>
<input type='text' class="input unit" style="width:100px;" name="unit[]">
</td>
<td>
<label for="brand">PO Number</label><br>
<input type="text" value="" class="input po" name="po[]" placeholder="PO Number" style='width:150px; height:28px;'/>
</td>
</tr>
</table>
The jQuery for appending elements:
<script>
$('#aprod').on('click', function() {
$('#ln1').clone().appendTo('#page3_inside');
prodnum = prodnum + 1;
$('#conf_prodnum').val(prodnum);
});
</script>
How do I validate each input, since all fields belongs to a class.
In the example I used ID as a selector, but how to do it with class instead?
Thanks.

Try a loop like this:
$('form').submit(function() {
$('form input.input').each(function() {
var valid = 1;
if ($(this).val() == '') {
$(this).addClass('error');
valid = 0;
} else {
$(this).removeClass('error');
}
});
if (valid === 1) {
// submit form
} else {
console.log('error');
return false;
}
});
You might need to change the selector and the condition to check for something more than just empty inputs but those are easy enough.
I'm not quite sure what they are supposed to be since your inputs are in a table in the question, there could be a containing form tag for all I know.
You can also add some styles for inputs with errors to highlight them when form submission has failed:
input.input.error {
border: 1px solid red;
}

I did this using id as selector but how to do it with class as
selector?
$('.conf_prodnum') A dot instead a hash is going to work on classes rather than ids.

Use a loop to visit every element that contains class input and check your inputs like so:
var inputs= $('.input ')
for(x in inputs){
x = inputs[x];
//do whatever you want
}

Related

Disable many fields by name javascript

This is my question:
I got an jsp page, this jsp has many text fields like this:
<html:text property="cicPF" maxlength="9" style="text-transform: uppercase;" onfocus="disableIfeFields()"/>
So I want to disable some of this text fields when the focus it's in a specific field
But no one of this fields has "id" label, and I can't modify it to include it.
May I disable the fields usig their given names, no one of this repeats the same name.
for example with a function like this:
function disableIfeFields(){
document.getElementsByName("numIdentificacionPF").disabled = true;
}
thanks
You need to loop through the list and disable all the fields you want that way, used input to show example:
function disableIfeFields() {
document.getElementsByName("numIdentificacionPF").forEach((e) => {
e.disabled = true;
});
}
<html:text property="cicPF" maxlength="9" style="text-transform: uppercase;" />
<input onfocus="disableIfeFields()" type="text" name="fname">
<input type="text" name="numIdentificacionPF">
<input type="text" name="numIdentificacionPF">
<input type="text" name="numIdentificacionPF">
<input type="text" name="numIdentificacionPF">
<input type="text" name="numIdentificacionPF">
Maybe like this:
function disableIfeFields(){
document.querySelectorAll('[property="cicPF"]')[0].disabled = true;
}
disableIfeFields();
<input type="text" property="cicPF" maxlength="9" style="text-transform: uppercase;" onfocus="disableIfeFields()"/>
Hopefully the following should help. Because the selection result is a list of elements you will have to loop through the results.
Please note that since you said no input repeats the same name, I'm using querySelectorAll, which might be a more suitable method after all…
var inputs = document.querySelectorAll('input[type="text"]');
for (var i = 0; i < inputs.length; i++) {
if (inputs[i].id === 'label') {
continue;
}
inputs[i].disabled = true;
}

Add more/remove functionality is throwing out of validation

I am trying to submit a form in that I have Addmore functionality in it.
Example: I have entered name and then I have used addmore button so now remove appeared in second tr.
When I click the remove that tr is removed now, but when click the form submit button it is skipping the phone number validation,
so to remove the functionality is throwing out validation.
My html somewhat looks like this:
<form>
Name<input type="text" name="name" id="name" placeholder="Name Your Name "/>
<table class="skillsTable" id="jobSkills">
<tbody>
<tr class="gdskilltr">
<td><button type="button" class="addSkills"> Add Skill</button></td>
<td><button type="button" class="removeSkill"> Remove Skill</button></td>
</tr>
</tbody>
</table>
phone<input type="text" name="phone" id="phone" placeholder="enter Your phone "/>
<button type="submit" id="JobSubmit">Submit</button>
</form>
And here my Javascript validation starts:
var skillcount = 1;
$(".addSkills").click(function () {
$('#jobSkills tr:last').after('<tr class="gdskilltr "><td></td></tr>');
skillcount++;
});
$("#jobSkills").on('click', '.removeSkill', function () {
$(this).parent().parent().remove();
});
$("#JobSubmit").click(function () {
if ($("#name").val() == '') {
$("#warning_message").html('Please Enter name');
$("#name").focus();
return false;
}
if ($("#phone").val() == '') {
$("#warning_message").html('Please Enter name');
$("#phone").focus();
return false;
}
}

Disable input in table row if one of input filled

I have javascript code to disable other inputs if one is filled .
I need it in table that comes out of database.
The sad thing is that it only works with first table row and disable all inputs in table (but if input filled is not first nothing happens)
Javascript:
$(function(){
$("input").on("keyup", function(){
if($(this).hasClass("inputA") && $(".inputA").val()){
$("input.inputB").prop("disabled", true);
$("input.inputA").prop("disabled", false);
$("input.inputC").prop("disabled", true);
} else if($(this).hasClass("inputB") && $(".inputB").val()){
$("input.inputA").prop("disabled", true);
$("input.inputB").prop("disabled", false);
$("input.inputC").prop("disabled", true);
} else if($(this).hasClass("inputC") && $(".inputC").val()){
$("input.inputA").prop("disabled", true);
$("input.inputB").prop("disabled", true);
$("input.inputC").prop("disabled", false);
} else {
$(".inputA, .inputB").prop("disabled", false);
}
});
});
My td from html table:
<td><input type="text" class="inputA" value=""></td>
<td><input type="text" class="inputB" value=""></td>
<td><input type="text" class="inputC" value=""></td>
How to make it work for each line separated?
Use the same class on each input, create event on those input after that check the value of the input if she's not empty disable all of others input for this works in a line just select all input of the parent.
Try to avoid multiple test as you did. Not lisible and maintainable.
Example
$(".input").on("keypress change keyup",function(){
if($(this).val() != "")
{
$(this).parent().parent().find(".input").not($(this)).prop("disabled",true);
}
else
{
$(this).parent().parent().find(".input").prop("disabled",false);
}
});
.input:disabled{
background-color:LightBlue;
border:solid 1px blue;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table>
<tr>
<td>
<input type="text" class="input" value="">
</td>
<td>
<input type="text" class="input" value="">
</td>
<td>
<input type="text" class="input" value="">
</td>
</tr>
<tr>
<td>
<input type="text" class="input" value="">
</td>
<td>
<input type="text" class="input" value="">
</td>
<td>
<input type="text" class="input" value="">
</td>
</tr>
</table>
This solves your issue! Disable all input fields that doesn't have same class as the one being currently edited.
Demo: https://jsfiddle.net/3tf8ou3y/1/
jQuery(document).ready(function($) {
$("tr").on("keyup", "input", function(event) {
// get the current row
var $row = $(event.delegateTarget);
// get the class of the input field being edited
var this_class = $(this).attr('class');
if ($(this).val().length > 0) {
// if the input field has a value, disable all
// other input fields in the sam row
$('input:not(.'+this_class+')', $row).prop('disabled', true);
} else {
// else enable all input fields
$('input', $row).prop('disabled', false);
}
});
});
You can use 'jQuery(this).val()' instead of 'jQuery(".inputA").val()' or 'jQuery(".inputB").val()' or jQuery(".inputC").val()

Javascript/jQuery Submit Form Validation

I am new to web development and I am trying to create a simple form validation using javascript/jquery.
I drafted a simple form very similar to what I have that looks like this:
<form>
<input class="price" type="text" />
<br />
<input class="price" type="text" />
<br />
<input class="price" type="text" />
<br />
<input class="price" type="text" />
<br />
<button type="submit" onclick='return validateSubmit();'>Save</button>
</form>
What I want to happen is when the user clicks the submit button, it will check every input box if it contains a valid number (price) before it allows the submit, if one or more of the input box is invalid, it will be highlighted with an alert error "Invalid inputs on highlighted textboxes" or something like that. After couple of searches this is what I have in my script:
var validateSubmit = function () {
var inputs = $('.price');
var errors = 'False';
for (var i = 0; i < inputs.length; i++) {
if (isNaN(inputs[i].value)) {
$('.price')[i].focus();
}
errors = 'True';
}
if (errors == 'True') {
alert('Errors are highlighted!');
return false;
}
return true;
};
I understand what is wrong with what Ive done but I dont know how to fix it.
I know that we can only focus() 1 element at a time but I wanted to have some effect that it highlights the inputboxes with invalid characters.
Please tell me how to do it or if there's a better approach can you show me some examples. I saw bootstrap has some css effects for this focus but I dont know how to implement it. Thank you!
You can add a class to the inputs with bad values. The class can add a border for example.
var validateSubmit = function () {
var inputs = $('.price');
var errors = 'False';
for (var i = 0; i < inputs.length; i++) {
if (isNaN(inputs[i].value)) {
$(inputs[i]).addClass('error');
errors = 'True';
} else {
$(inputs[i]).removeClass('error');
}
}
if (errors == 'True') {
alert('Errors are highlighted!');
return false;
}
return true;
};
.error {
border: 1px solid red;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form>
<input class="price" type="text" />
<br />
<input class="price" type="text" />
<br />
<input class="price" type="text" />
<br />
<input class="price" type="text" />
<br />
<button type="submit" onclick='return validateSubmit();'>Save</button>
</form>
First, I think you should clean up your HTML. For example, it is always a good idea to give an id attribute to your form tags to reference them. Also, someone correct me if I am wrong, you won't be submitting any values without giving a name attribute to your input fields.
<form id="price-form" action="" method="get">
<input name="price[]" type="text" value="" class="price" />
<br />
<input name="price[]" type="text" value="" class="price" />
<br />
<input name="price[]" type="text" value="" class="price" />
<br />
<input name="price[]" type="text" value="" class="price" />
<br />
<button type="submit">Save</button>
</form>
Now, since you are using jQuery, why not utilize its methods such as on() and .each() ?
$(function() {
$('#price-form').on('submit', function(e) {
// this variable acts as a boolean, so might as well treat it as a boolean
var errors = false;
// remove previous errors
$('.price').removeClass('error');
// check each input for errors
$('.price').each(function() {
if (isNaN(this.value)) {
$(this).addClass('error');
errors = true;
}
});
// alert if there are any errors
if (errors) {
alert('Errors are highlighted!');
e.preventDefault(); // stop submission
}
});
});
In your CSS, you could do
.error {
border: 2px solid #a00;
}

Validation not working for dynamically created values

I have created a form along with dynamically created form fields (name, age). While trying to validate my age field using javascript, only the first record of the age field is validating - the other ones aren't.
The code is:
<script type="text/javascript">
function formValidator(){
var age = document.getElementById('age');
if(isNumeric(age, "Please enter a valid Age")){
return true;
}
return false;
}
function isNumeric(elem, helperMsg){
var numericExpression = /^[0-9]+$/;
if(elem.value.match(numericExpression)){
return true;
}else{
alert(helperMsg);
elem.focus();
return false;
}
}
HTML code is:
<html>
< body>
<div style="padding-left:70px;">
<input type="button" value="Add Person" onClick="addRow('dataTable')" />
<input type="button" value="Remove Person" onClick="deleteRow('dataTable')" />
</div>
</p>
<table style="padding-left:50px;" id="dataTable" class="form" border="1" >
<tbody>
<tr>
<p>
<td><input type="checkbox" name="chk[]" checked="checked" /></td>
<td>
<label>Name</label>
<input type="text" size="20" name="name[]" id="name" >
</td>
<td>
<label>Age</label>
<input type="text" size="20" name="age[]" id="age" >
</td>
</p>
</tr>
</tbody>
</table>
<div class="clear"></div>
</body>
</html>
Only the first field is validating. How can I validate the dynamically generated fields?
You have duplicate IDs for form element. which is targeting only first element matched with ID. You should rather use same class and target all of them for validation. give class age instead of id and then use:
function formValidator(){
var age = document.getElementsByClassName('age');
for (var i = 0; i< age.length; i++) {
if(!isNumeric(age[i], "Please enter a valid Age")){
return false;
}
}
return true;
}
If You are using dynamic values then pass dynamic ids to the javascript function and then do the validation
For example :
for(i=0;i<results;i++)
{
<input type="text" size="20" name="age[]" id="age"<?php echo i; ?> >
}
And in the javascript function read all the dynamic ids and do the validation.
The bug is in this line. getElementById returns the DOM element and not its value.
var age = document.getElementById('age');
To get the value in the DOM element, you should use the 'value' attribute.
var age = document.getElementById('age').value;
hope that fixes the issue.
You are getting only one element and create it with duplicated ID's. You should get all elements and check them using a loop.
function formValidator(){
var ageEls = document.getElementsByName('age[]'),
valid = true,
i = 0;
while (i < ageEls.length && valid) {
valid = isNumeric(ageEls[i], "Please enter a valid Age");
i++;
}
return valid;
}
JSFiddler example: http://jsfiddle.net/3zsLhe9c/3/
for jquery i have colustion if you use this "jquery.validate.unobtrusive.js" js.
$("#FrmSubmitToAgent").removeData("validator");
$("#FrmSubmitToAgent").removeData("unobtrusiveValidation");
$.validator.unobtrusive.parse("form");$("#FrmSubmitToAgent").removeData("validator");
$("#FrmSubmitToAgent").removeData("unobtrusiveValidation");
$.validator.unobtrusive.parse("form");

Categories