localStorage Update Cannot Find innerHTML Value - Javascript/jQuery - javascript

I have been refactoring some of my innerHTML content within a form to make it more readable. Before, I had one lump innerHTML which was hard to read, however worked and allowed updating to localStorage.
I gave each div wrapper its own unique ID so that I could change the innerHTML value, in order to make everything neater and readable, this worked fine but when I try to edit my form now it gives me an error of cannot set property 'fname' of undefined. When I revert it back to the lump html it edits fine?
My knowledge is limited of how JS works, so can anyone explain why this might be happening, and is there a resolution?
Here's my code and edit handler (simplified), it's difficult to show on this as it's using localStorage but hopefully it's at least helpful:
$(document).on('change keyup', '.required', function(e) {
var disabled = true;
$(".required").each(function() {
var value = this.value;
if (!(value) || (value.trim() === '') || ($(this).hasClass('is-invalid'))) {
disabled = false;
$('.toggle-disabled').prop("disabled", true);
}
});
if (disabled) {
$('.toggle-disabled').prop("disabled", false);
}
});
var bookings = JSON.parse(localStorage.getItem("bookings")) || [];
$("#submit").click(function() {
var newBookings = {
id: new Date().getTime(),
fname: $('#fname').val(),
lname: $('#lname').val(),
}
bookings.push(newBookings);
var json = JSON.stringify(bookings);
window.localStorage.setItem("bookings", json);
showBooking();
document.getElementById('formSuccess').style.display = "block";
});
$(document).on('click', '#edit', function(e) {
e.preventDefault();
var parent_form = $('this.form');
var fname = parent_form.find('.fname').val();
var lname = parent_form.find('.lname').val();
let i = bookings.findIndex(booking => booking.id == $(this).data("id"));
bookings[i].fname = fname;
bookings[i].lname = lname;
var json = JSON.stringify(bookings);
window.localStorage.setItem("bookings", json);
alert('Form updated!');
window.location.reload();
showBooking();
});
function showBooking() {
var bookingResult = document.getElementById("result");
var ul = document.createElement("ul");
bookingResult.innerHTML = `<h3 class="text-center">Your Bookings</h3>`;
for (let i = 0; i < bookings.length; i++) {
bookingResult.innerHTML += `
<div class="card card-body bg-light m-4">
<div class="row">
<p>Owner name: ${bookings[i].fname + " " + bookings[i].lname}</p>
</div>
<div class="row">
<div class="d-grid gap-2 d-md-block">
<button onclick="editBooking(${i})" class="col-md-4 btn btn-outline-danger ">Edit</button>
<button onclick="deleteBooking(${i})" class="col-md-4 btn btn-danger text-light ">Delete</button>
</div>
</div>
</div>`;
}
}
function editBooking(i) {
$('#result').hide();
var fnameEdit = document.getElementById("fnameEdit");
var lnameEdit = document.getElementById("lnameEdit");
var editButton = document.getElementById("editBtn");
fnameEdit.innerHTML = `<input type="text" class="fname form-control required" data-id="${bookings[i].id}" placeholder="First Name" name="${bookings[i].fname}" value="${bookings[i].fname}" required>`;
lnameEdit.innerHTML = `
<input type="text" class="lname form-control required" data-id="${bookings[i].id}" placeholder="Last Name" name="${bookings[i].lname}" value="${bookings[i].lname}" required>`;
editButton.innerHTML = `<div class="d-grid gap-2 d-md-block">
<input id="edit" class="btn btn-danger toggle-disabled" type="submit" value="Edit">
Cancel
</div>`;
}
<link href="https://cdn.jsdelivr.net/npm/bootstrap#5.0.0-beta1/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-giJF6kkoqNQ00vy+HMDP7azOuL0xtbfIcaT9wjKHr8RbDVddVHyTfAAsrekwKmP1" crossorigin="anonymous">
<form id="regForm" name="regForm" action="" class="col-md-6">
<div class="row">
<div id="fnameEdit" class="col-md-6">
<input type="text" class="input form-control required" id="fname" placeholder="First Name" name="fname" required>
</div>
<div id="lnameEdit" class="col-md-6">
<input type="text" class="input form-control required" id="lname" placeholder="Last Name" name="lname" required>
</div>
</div>
<div id="editBtn">
<div class="col-md-6">
<input id="submit" class="btn btn-danger toggle-disabled" type="submit" value="Submit">
</div>
</div>
</form>
<div class="col-md-6">
<div id="result" class="row"></div>
<div id="currentItem" class="row"></div>
</div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js">

The first issue is described in the comment by #Swati (i.e.: $(this).closest('form'))
As a consequence, the second issue is related to the anonymous function you use inside .findIndex():
Change this part from:
let i = bookings.findIndex(booking => booking.id == $(this).data("id"));
to:
let i = bookings.findIndex(booking => booking.id == parent_form.find('.fname').data("id"));
$(document).on('change keyup', '.required', function(e) {
var disabled = true;
$(".required").each(function() {
var value = this.value;
if (!(value) || (value.trim() === '') || ($(this).hasClass('is-invalid'))) {
disabled = false;
$('.toggle-disabled').prop("disabled", true);
}
});
if (disabled) {
$('.toggle-disabled').prop("disabled", false);
}
});
var bookings = JSON.parse(localStorage.getItem("bookings")) || [];
$("#submit").click(function() {
var newBookings = {
id: new Date().getTime(),
fname: $('#fname').val(),
lname: $('#lname').val(),
}
bookings.push(newBookings);
var json = JSON.stringify(bookings);
window.localStorage.setItem("bookings", json);
showBooking();
document.getElementById('formSuccess').style.display = "block";
});
$(document).on('click', '#edit', function(e) {
e.preventDefault();
var parent_form = $(this).closest('form');
var fname = parent_form.find('.fname').val();
var lname = parent_form.find('.lname').val();
let i = bookings.findIndex(booking => booking.id == parent_form.find('.fname').data("id"));
bookings[i].fname = fname;
bookings[i].lname = lname;
var json = JSON.stringify(bookings);
window.localStorage.setItem("bookings", json);
alert('Form updated!');
window.location.reload();
showBooking();
});
function showBooking() {
var bookingResult = document.getElementById("result");
var ul = document.createElement("ul");
bookingResult.innerHTML = `<h3 class="text-center">Your Bookings</h3>`;
for (let i = 0; i < bookings.length; i++) {
bookingResult.innerHTML += `
<div class="card card-body bg-light m-4">
<div class="row">
<p>Owner name: ${bookings[i].fname + " " + bookings[i].lname}</p>
</div>
<div class="row">
<div class="d-grid gap-2 d-md-block">
<button onclick="editBooking(${i})" class="col-md-4 btn btn-outline-danger ">Edit</button>
<button onclick="deleteBooking(${i})" class="col-md-4 btn btn-danger text-light ">Delete</button>
</div>
</div>
</div>`;
}
}
function editBooking(i) {
$('#result').hide();
var fnameEdit = document.getElementById("fnameEdit");
var lnameEdit = document.getElementById("lnameEdit");
var editButton = document.getElementById("editBtn");
fnameEdit.innerHTML = `<input type="text" class="fname form-control required" data-id="${bookings[i].id}" placeholder="First Name" name="${bookings[i].fname}" value="${bookings[i].fname}" required>`;
lnameEdit.innerHTML = `
<input type="text" class="lname form-control required" data-id="${bookings[i].id}" placeholder="Last Name" name="${bookings[i].lname}" value="${bookings[i].lname}" required>`;
editButton.innerHTML = `<div class="d-grid gap-2 d-md-block">
<input id="edit" class="btn btn-danger toggle-disabled" type="submit" value="Edit">
Cancel
</div>`;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.5.3/css/bootstrap.min.css">
<script src="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.5.3/js/bootstrap.bundle.min.js"></script>
<form id="regForm" name="regForm" action="" class="col-md-6">
<div class="row">
<div id="fnameEdit" class="col-md-6">
<input type="text" class="input form-control required" id="fname" placeholder="First Name" name="fname" required>
</div>
<div id="lnameEdit" class="col-md-6">
<input type="text" class="input form-control required" id="lname" placeholder="Last Name" name="lname" required>
</div>
</div>
<div id="editBtn">
<div class="col-md-6">
<input id="submit" class="btn btn-danger toggle-disabled" type="submit" value="Submit">
</div>
</div>
</form>
<div class="col-md-6">
<div id="result" class="row"></div>
<div id="currentItem" class="row"></div>
</div>

I ended up solving this problem eventually, I hadn't given the attributes a new ID and somehow, that sorted the issue. I removed the innerHTML and replaced with setAttribute methods which work fine.
Thanks for help!
Something along these lines:
var fname = document.getElementById("fname");
var lname = document.getElementById("lname");
var editButton = document.getElementById("editBtn");
fname.setAttribute('data-id', bookings[i].id);
fname.setAttribute('value', bookings[i].fname);
lname.setAttribute('data-id', bookings[i].id);
lname.setAttribute('value', bookings[i].lname);
editButton.innerHTML = `<div class="d-grid gap-2 d-md-block">
<input data-id="${bookings[i].id}" id="edit" class="btn btn-danger toggle-disabled" type="submit" value="Edit" disabled>
Cancel
</div>`;

Related

Can't seem to fix this one

I am getting this error "Uncaught TypeError: Cannot set property 'onclick' of null
at index.html:73" and I can't seem to navigate past through it. an help on this one please, it should, when I click button next bring up the next form instead there is nothing and in the chrome debug option that's where I noticed that error.
<body>
<div class="container">
<form id="Form1">
<h3>Create Account</h3>
<input type="text" placeholder="Email" required>
<input type="password" placeholder="Password" required>
<input type="password" placeholder="Confirm Password" required>
<div class="btn-box">
<button type="button" id="Next1">Next</button>
</div>
</form>
<form id="Form2">
<h3>Social Links</h3>
<input type="text" placeholder="Medium">
<input type="text" placeholder="Github">
<input type="text" placeholder="LinkedIn">
<div class="btn-box">
<button type="button" id="Back1">back</button>
<button type="button" id="Next2">Next</button>
</div>
</form>
<form id="Form3">
<h3>Personal Info</h3>
<input type="text" placeholder="First Name" required>
<input type="text" placeholder="Last Name" required>
<input type="text" placeholder="Mobile No." required>
<div class="btn-box">
<button type="button" id="Back2">back</button>
<button type="Submit">Submit</button>
</div>
</form>
<div class="step-row">
<div id="progress"></div>
<div class="step-col">Step 1</div>
<div class="step-col">Step 2</div>
<div class="step-col">Step 3</div>
</div>
</div>
<script>
var Form1 = document.getElementById(Form1);
var Form2 = document.getElementById(Form2);
var Form3 = document.getElementById(Form3);
var Next1 = document.getElementById(Next1);
var Next2 = document.getElementById(Next2);
var Back1 = document.getElementById(Back1);
var Back2 = document.getElementById(Back2);
var progress = document.getElementById("progress");
Next1.onclick = function() {
Form1.style.left = "-450px";
Form2.style.left = "40px";
progress.style.width = "240px";
}
Back1.onclick = function() {
Form1.style.left = "40px";
Form2.style.left = "450px";
progress.style.width = "120px";
}
Next2.onclick = function() {
Form2.style.left = "-450px";
Form3.style.left = "40px";
progress.style.width = "360px";
}
Back2.onclick = function() {
Form1.style.left = "40px";
Form2.style.left = "450px";
progress.style.width = "240px";
}
</script>
</body>
</html>
Try something like following:-
var Form1 = document.getElementById('Form1');
var Form2 = document.getElementById('Form2');
var Form3 = document.getElementById('Form3');
var Next1 = document.getElementById('Next1');
var Next2 = document.getElementById('Next2');
var Back1 = document.getElementById('Back1');
var Back2 = document.getElementById('Back2');

Check input field is empty or not

I am going to create simple validation form using Vanilla JavaScript, but I have problem, I want to check first ('entername') field, if user will not enter any letters in it, i want to console log message ('enter name'), it's works fine, but after that user reenter his name if field it returns in console ('enter name'), i want to return ('not enter') message.
var userBtn = document.getElementById('checkuserinputs');
var checkUserName = document.getElementById('user-name').value;
var checkUserSurname = document.getElementById('user-surname').value;
var checkUserPhone = document.getElementById('user-mobile').value;
userBtn.addEventListener('click', function(){
if(checkUserName.length == 0){
console.log('enter name')
}else{
console.log('not enter')
}
})
<div class="container-fluid">
<div class="modal-costum-row">
<div class="enter-name-side">
<div class="input-row">
<input class="costum--input" type="text" id="user-name" name="user-nm" placeholder="entername">
</div>
</div>
<div class="enter-surname-side">
<div class="input-row">
<input class="costum--input" type="text" id="user-surname" name="surname" placeholder="entersurname">
</div>
</div>
</div>
<div class="enter-tel-numb-side">
<div class="input-row input--wide">
<input class="costum--input" type="tel" id="user-mobile" name="user-mobile" placeholder="enterphonenumber">
</div>
</div>
</div>
<button id="checkuserinputs">check input</button>
You need to get the value after clicking the button. If you put it outside of the click event, the value will never be updated.
var userBtn = document.getElementById('checkuserinputs');
userBtn.addEventListener('click', function () {
var checkUserName = document.getElementById('user-name').value;
var checkUserSurname = document.getElementById('user-surname').value;
var checkUserPhone = document.getElementById('user-mobile').value;
if (checkUserName.length == 0) {
console.log('enter name')
} else {
console.log('not enter')
}
})
<div class="container-fluid">
<div class="modal-costum-row">
<div class="enter-name-side">
<div class="input-row">
<input class="costum--input" type="text" id="user-name" name="user-nm" placeholder="entername" />
</div>
</div>
<div class="enter-surname-side">
<div class="input-row">
<input class="costum--input" type="text" id="user-surname" name="surname" placeholder="entersurname" />
</div>
</div>
</div>
<div class="enter-tel-numb-side">
<div class="input-row input--wide">
<input class="costum--input" type="tel" id="user-mobile" name="user-mobile" placeholder="enterphonenumber" />
</div>
</div>
</div>
<button id="checkuserinputs">check input</button>
You need to retrieve the value of the input field in the click function callback:
userBtn.addEventListener('click', () => {
const checkUserName = document.getElementById('user-name').value;
if(checkUserName.length === 0){
console.log('enter name')
} else {
console.log('not enter')
}
})
change the variable geting value to button click function that is,
var userBtn = document.getElementById('checkuserinputs');
userBtn.addEventListener('click', function(){
var checkUserName = document.getElementById('user-name').value;
var checkUserSurname = document.getElementById('user-surname').value;
var checkUserPhone = document.getElementById('user-mobile').value;
if(!checkUserName){
console.log('enter name')
}else{
console.log('not enter')
}
})
var userBtn = document.getElementById('checkuserinputs');
userBtn.addEventListener('click', function(){
var checkUserName = document.getElementById('user-name').value;
var checkUserSurname = document.getElementById('user-surname').value;
var checkUserPhone = document.getElementById('user-mobile').value;
if(!checkUserName){
console.log('enter name')
}else{
console.log('not enter')
}
})
<div class="container-fluid">
<div class="modal-costum-row">
<div class="enter-name-side">
<div class="input-row">
<input class="costum--input" type="text" id="user-name" name="user-nm" placeholder="entername">
</div>
</div>
<div class="enter-surname-side">
<div class="input-row">
<input class="costum--input" type="text" id="user-surname" name="surname" placeholder="entersurname">
</div>
</div>
</div>
<div class="enter-tel-numb-side">
<div class="input-row input--wide">
<input class="costum--input" type="tel" id="user-mobile" name="user-mobile" placeholder="enterphonenumber">
</div>
</div>
</div>
<button id="checkuserinputs">check input</button>

Form validation not working on submit

After clicking submit the form is not producing errors next to the input fields ,it refreshes the page and clears all the fields.
HTML:
<form id="mc-form" method="POST">
<div class="form-group col-xs-12 ">
<label for="name" hidden>שם פרטי</label>
<input type="text" name="name" id="name" class="cv form-control" placeholder="שם פרטי" onkeyup='validateMessage()'>
<span class='error-message' id='name-error'></span>
</div>
<div class="form-group col-xs-12 ">
<label for="lastName" hidden>שם משפחה</label>
<input type="text" name="lastName" id="lastName" class="cv form-control" placeholder="שם משפחה" onkeyup='validateMessage()'>
<span class='error-message' id='name-error'></span>
</div>
<div class="form-group col-xs-12 ">
<label for="phone" hidden>טלפון</label>
<input type="text" name="phone" id="phone" class="cv form-control" placeholder="טלפון" onkeyup='validateMessage()'>
<span class='error-message' id='name-error'></span>
</div>
<div class="form-group col-xs-12 ">
<label for="email" hidden>דואר אלקטרוני</label>
<input type="email" name="email" id="email" class="cv form-control" placeholder="דואר אלקטרוני" onkeyup='validateMessage()'>
<span class='error-message' id='name-error'></span>
</div>
<div class="form-group col-xs-12 ">
<label for="subject" hidden>נושא</label>
<input type="text" name="subject" id="subject" class="cv form-control" placeholder="נושא" onkeyup='validateMessage()'>
</div>
<div class="form-group col-xs-12 ">
<label for="message" hidden>הודעה</label>
<textarea name="message" id="message" class="cv form-control message" placeholder="השאירו את הודעתכם פה" rows="4" cols="50" onkeyup='validateMessage()'></textarea>
</div>
<!-- <input type="submit" id="submit-button" class="btn btn-custom-outline " value="שלח" > -->
<button onclick='return validateForm()' class="btn btn-custom-outline " id="submit-button">שלח</button>
<span class='error-message' id='submit-error'></span>
<br>
<!-- <div class="success"><?= $success ?></div>-->
<!--<span class="error"></span> -->
</form>
My JavaScript:
function validateName() {
var name = document.getElementById('name').value;
if(name.length == 0) {
producePrompt('Name is required', 'name-error' , 'red')
return false;
}
if (!name.match( /^[a-zא-ת]+(\s[a-zא-ת]+)*$/i)) {
producePrompt('Letters only please.','name-error', 'red');
return false;
}
producePrompt('Valid', 'name-error', 'green');
return true;
}
function validatePhone() {
var phone = document.getElementById('phone').value;
if(phone.length == 0) {
producePrompt('Phone number is required.', 'phone-error', 'red');
return false;
}
if(!phone.match(/^[0-9]{10}$/)) {
producePrompt('Only digits, please.' ,'phone-error', 'red');
return false;
}
producePrompt('Valid', 'phone-error', 'green');
return true;
}
function validateEmail () {
var email = document.getElementById('email').value;
if(email.length == 0) {
producePrompt('Email Invalid','email-error', 'red');
return false;
}
if(!email.match(/^[A-Za-z\._\-[0-9]*[#][A-Za-z]*[\.][a-z]{2,4}$/)) {
producePrompt('Email Invalid', 'email-error', 'red');
return false;
}
producePrompt('Valid', 'email-error', 'green');
return true;
}
/*function validateMessage() {
var message = document.getElementById('contact-message').value;
var required = 30;
var left = required - message.length;
if (left > 0) {
producePrompt(left + ' more characters required','message-error','red');
return false;
}
producePrompt('Valid', 'message-error', 'green');
return true;
}*/
function validateForm() {
if (!validateName() || !validatePhone() || !validateEmail() ) {
jsShow('submit-error');
producePrompt('Please fix errors to submit.', 'submit-error', 'red');
setTimeout(function(){jsHide('submit-error');}, 2000);
return false;
}
else {
}
}
function jsShow(id) {
document.getElementById(id).style.display = 'block';
}
function jsHide(id) {
document.getElementById(id).style.display = 'none';
}
function producePrompt(message, promptLocation, color) {
document.getElementById(promptLocation).innerHTML = message;
document.getElementById(promptLocation).style.color = color;
}
My scrips are in index.html , same page the form is, in the end :
<script src="https://code.jquery.com/jquery-3.2.1.slim.min.js" ></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.12.3/umd/popper.min.js" ></script>
<script src="js/bootstrap.min.js" ></script>
<!-- [ SLIDER SCRIPT ] -->
<script type="text/javascript" src="js/SmoothScroll.js"></script>
<script src="js/script.js" ></script>
<script src="js/validateform.js" ></script>
After clicking submit the form is not producing errors next to the input fields ,it refreshes the page and clears all the fields.
The issue that you are running into in calling
producePrompt('Email Invalid','email-error', 'red');
and any other where you are not passing name-error an error is occurring as there is no element with the id email-error they all have the same id. When the error is thrown the function returns undefined instead of false causing the form to be submitted.
When using Chrome dev tools you can go into settings and check preserve log this will allow you to see errors even after the page refreshes.
As to checking for all errors instead of just the first one...
the if (!validateName() || !validatePhone() || !validateEmail() ) {
or statements here mean the first one that false causes the rest to not be checked. Instead you could do something like the following
var vn = validateName();
var vp = validatePhone();
var ve = validateEmail();
if (!vn || !vp || !ve) {

Input field value returned empty after entering some value

The requirement is to dynamically add each li element as and when user click on "add row" button". And when User enters any value in field1, an ajax call with this value as parameter is made to server and the return value is set in the next 2 fields.
In focus lost method, when I try to retrieve the user entered value, the input field value is always returned as EMPTY or the default value which I set in the source code and not the user modified value.
The row ids are given unique like f1_edit_row1, f1_edit_row2 etc. Please let me know on why I dont get the value.
<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<script src="js/jquery-1.12.4.js"></script>
<title>Insert title here</title>
</head>
<body>
<ul id="Rows_Edit">
<li id="EditRow1">
<div class="row">
<div class="col-md-3 Field1">
<span>Field1</span><input type="text" class="form-control field1"
id="f1_edit_row1" onfocusout="focusLost_edit('1')" name="field1"
placeholder="1234">
</div>
<div class="col-md-3 Field2">
<span>Field2</span><input type="text" class="form-control"
id="f2_edit_row1" name="field2" placeholder="123"
disabled="disabled">
</div>
<div class="col-md-5 name">
<input type="text" class="form-control" id="field3_edit_row1"
placeholder="ABC" disabled="disabled">
</div>
<div class="col-md-1 icons" id="btn_row1">
<input type="button" class="addbtn" id="btn_row1" name="Add" value="Add Row" onclick="addButtonClick()">
<!-- <i class="fa fa-plus-square" id="btn1_edit" aria-hidden="true"></i> -->
</div>
</div>
</li>
</ul>
<div></div>
<div></div>
<div></div>
<div class="updatebutton">
<input type="submit" id='submit-button_edit' class="btn btn-default" value="Update" onclick="updateBtnClick()">
</div>
<div class="cancelbutton">
<input type="button" id='cancel-button_edit' class="btn btn-default" value="Cancel">
</div>
</body>
</html>
<script type="text/javascript">
function focusLost_edit(rowNo){
var id = "f1_edit_row" + rowNo;
var value = document.getElementById(id).value;
console.log(id, " Value:[", value, "]");
// API Code here
var returnvalue = "TEST";
var id1 = "#f2_edit_row" + rowNo;
$(id1).val(returnvalue);
console.log(id1, " Return Value:[", returnvalue, "]");
var returnvalue1 = "TESTING";
var id2 = "#field3_edit_row" + rowNo;
$(id2).val(returnvalue1);
console.log(id2, " Return Value1:[", returnvalue1, "]");
}
function addButtonClick(){
console.log("Add Button Click");
// Code to add rows here
}
function updateBtnClick(){
console.log("Update Button Click");
$('ul#Rows_Edit li').each(function() {
var id = $(this).attr('id');
var rowNo = id.substring(7);
var id1 = "#f1_edit_row" + rowNo;
var value1 = $(id1).val();
var id2 = "#f2_edit_row" + rowNo;
var value2 = $(id2).val();
var id3 = "#field3_edit_row" + rowNo;
var value3 = $(id3).val();
console.log("Value1:[", value1, "] Value2:[", value2, "]Value3:[", value3), "]";
});
// Code to send value to server here
}
</script>
Use this in your function call.
function focusLost_edit(rowNo){
var id = "f1_edit_row" + rowNo;
var value = document.getElementById(id).value;
console.log(id, " Value:[", value, "]");
// API Code here
var returnvalue = "TEST";
var id1 = "#f2_edit_row" + rowNo;
$(id1).val(returnvalue);
console.log(id1, " Return Value:[", returnvalue, "]");
var returnvalue1 = value;
var id2 = "#field3_edit_row" + rowNo;
$(id2).val(returnvalue1);
console.log(id2, " Return Value1:[", returnvalue1, "]");
}
function addButtonClick(){
console.log("Add Button Click");
// Code to add rows here
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<ul id="shipToRows_Edit">
<li id="EditRow1">
<div class="row">
<div class="col-md-3 Field1">
<span>Field1</span><input type="text" class="form-control field1"
id="f1_edit_row1" onfocusout="focusLost_edit('1')" name="field1"
placeholder="1234">
</div>
<div class="col-md-3 Field2">
<span>Field2</span><input type="text" class="form-control"
id="f2_edit_row1" name="field2" placeholder="123"
disabled="disabled">
</div>
<div class="col-md-5 name">
<input type="text" class="form-control" id="field3_edit_row1"
placeholder="ABC" disabled="disabled">
</div>
<div class="col-md-1 icons" id="btn_row1">
<input type="button" class="addbtn" id="btn_row1" name="Add" value="Add Row" onclick="addButtonClick()">
<!-- <i class="fa fa-plus-square" id="btn1_edit" aria-hidden="true"></i> -->
</div>
</div>
</li>
</ul>

on keyup validation is working but on keypress its not working

Input box requires following validations:
1) Length input box should take upto 3 integer length values (decimals not allowed)
2) Height input box should take 3 integer number and decimals upto 2 places Its working fine for the first time, but after clicking + button(near of Open New Row 1) same input fields are opening but now: In the new boxes validations are not working even if I use the same classes for input boxes, i.e, newly added input boxes are taking any number of digits and characters.
In keyup function it is working,but if user presses any key it doesn't work for newly opened row, so how to make its working on keypress also in both the cases; on keyup validation is working but on keypress its not working
var app = angular.module('Calc', []);
var inputQuantity = [];
$(function() {
$(".form-control").each(function(i) {
inputQuantity[i]=this.defaultValue;
$(this).data("idx",i); // save this field's index to access later
});
$(".form-control").on("keyup", function (e) {
var $field = $(this),
val=this.value,
$thisIndex=parseInt($field.data("idx"),10); // retrieve the index
// window.console && console.log($field.is(":invalid"));
// $field.is(":invalid") is for Safari, it must be the last to not error in IE8
if (this.validity && this.validity.badInput || isNaN(val) || $field.is(":invalid") ) {
this.value = inputQuantity[$thisIndex];
return;
}
if (val.length > Number($field.attr("maxlength"))) {
val=val.slice(0, 5);
$field.val(val);
}
inputQuantity[$thisIndex]=val;
});
});
app.controller('Calc_Ctrl', function ($scope, $http) {
$scope.choices = [{id : 'choice1', l2 : 0, b2 : 0}];
$scope.areas = [{id : 'choice2', total : 0}];
$scope.addNewChoice = function () {
var newItemNo = $scope.choices.length + 1;
$scope.choices.push({
'id' : 'choice' + newItemNo, l2 : 0, b2 : 0
});
};
$scope.removeChoice = function () {
var lastItem = $scope.choices.length - 1;
if (lastItem !== 0) {
$scope.choices.splice(lastItem);
}
};
});
<!DOCTYPE html>
<html>
<script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.0/jquery.min.js"></script>
<script src="newscript.js"></script>
<body>
<div ng-app="Calc" ng-controller="Calc_Ctrl">
<div data-ng-repeat="choice in choices" class="col-md-12 col-sm-12 col-xs-12 bottom-line no-gap">
<h6>Open New Row {{$index + 1}}
<button type="button" class="btn btn-default pull-right btn-right-gap btn-red" aria-label="Left Align" ng-click="addNewChoice()" style="margin-top: -5px;" id="plus_icon">
<span class="glyphicon glyphicon-plus" aria-hidden="true"></span>
</button>
</h6>
<div class="row walls top-gap">
<div class="form-group col-md-3 col-sm-3 col-xs-12">
<label for="length">Length :</label>
<input type="number" class="form-control text-red bold" id="length" ng-model="choice.l2" min="0" max="999" maxlength="6" step="0.00">
</div>
<div class="form-group col-md-3 col-sm-3 col-xs-12">
<label for="height">Height :</label>
<input type="number" class="form-control text-red bold" id="height" ng-model="choice.b2" min="0" max="999" maxlength="6" step="0.01">
</div>
<button type="button" class="btn btn-default pull-right btn-red" aria-label="Left Align" ng-click="removeChoice()" id="minus_icon">
</button>
</div>
</div>
</div>
</body>
</html>
To fire keyup event for all fields we need to change the listener's definition slightly,the selector .form-control should be defined inside the on() as a child selector & document as main selector:
$(document).on("keyup",".form-control", function (e) {
// listener code
});
keypress event behaves differently than keyup event. keypress is fired for each key pressed & just before the value is set in the field.Whereas keyup event is fired for each key released & just after the value is set in the field.So the same approach will not work for keypress.
var app = angular.module('Calc', []);
var inputQuantity = [];
$(function() {
$(".form-control").each(function (i) {
inputQuantity[i] = this.defaultValue;
$(this).data("idx", i); // save this field's index to access later
});
$(document).on("keypress", ".form-control", function (e) {
if (e.charCode!=0){
var $field = $(this),
val = this.value + '' + String.fromCharCode(e.charCode), pattern;
if (this.step == 0.00)
pattern = /[^0-9]/
else
pattern = /[^0-9.]/
if (val > parseInt(this.max, 10) || pattern.test(val) || (val.match(/\./) && (val.match(/\./g).length > 1 || val.replace(/\d+\./, '').length > 2))) {
e.preventDefault();
}
}
});
$(document).on("keyup",".form-control", function (e) {
var $field = $(this),
val=this.value,
$thisIndex=parseInt($field.data("idx"),10);
if (parseInt(val,10) > parseInt(this.max, 10) ) {
this.value = inputQuantity[$thisIndex];
return;
}
if (val.length > Number($field.attr("maxlength"))) {
val=val.slice(0, 5);
$field.val(val);
}
inputQuantity[$thisIndex]=val;
});
});
app.controller('Calc_Ctrl', function ($scope, $http) {
$scope.choices = [{id : 'choice1', l2 : 0, b2 : 0}];
$scope.areas = [{id : 'choice2', total : 0}];
$scope.addNewChoice = function () {
var newItemNo = $scope.choices.length + 1;
$scope.choices.push({
'id' : 'choice' + newItemNo, l2 : 0, b2 : 0
});
};
$scope.removeChoice = function () {
var lastItem = $scope.choices.length - 1;
if (lastItem !== 0) {
$scope.choices.splice(lastItem);
}
};
});
<!DOCTYPE html>
<html>
<script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.0/jquery.min.js"></script>
<script src="newscript.js"></script>
<body>
<div ng-app="Calc" ng-controller="Calc_Ctrl">
<div data-ng-repeat="choice in choices" class="col-md-12 col-sm-12 col-xs-12 bottom-line no-gap">
<h6>Open New Row {{$index + 1}}
<button type="button" class="btn btn-default pull-right btn-right-gap btn-red" aria-label="Left Align" ng-click="addNewChoice()" style="margin-top: -5px;" id="plus_icon">
<span class="glyphicon glyphicon-plus" aria-hidden="true"></span>
</button>
</h6>
<div class="row walls top-gap">
<div class="form-group col-md-3 col-sm-3 col-xs-12">
<label for="length">Length :</label>
<input type="text" class="form-control text-red bold" id="length" ng-model="choice.l2" min="0" max="999" maxlength="6" step="0.00">
</div>
<div class="form-group col-md-3 col-sm-3 col-xs-12">
<label for="height">Height :</label>
<input type="text" class="form-control text-red bold" id="height" ng-model="choice.b2" min="0" max="999" maxlength="6" step="0.01">
</div>
<button type="button" class="btn btn-default pull-right btn-red" aria-label="Left Align" ng-click="removeChoice()" id="minus_icon">
</button>
</div>
</div>
</div>
</body>
</html>

Categories

Resources