How to limit the clone of forms - javascript

I have a 4 form which has a button below it saying add more experience and add more education etc, when user clicks on the add more button the jquery creates a clone of the form and append it, the problem i'm getting is I'm not able to limit the number of clones here is code
$(".btn-duplicator").on("click", function(a) {
a.preventDefault();
var b = $(this).parent().siblings(".duplicateable-content"),
c = $("<div>").append(b.clone()).html();
$(c).insertBefore(b);
var d = b.prev(".duplicateable-content");
d.fadeIn(600).removeClass("duplicateable-content"), d.find(".btn-remove").on("click", function(a) {
a.preventDefault();
var b = $(this).parents(".item-block").parent("div");
b.fadeOut(600, function() {
b.remove()
})
})
});
i tried addding
var count = 1;
if(count < 5) {
count++;
}
but nothing seems to work how can i limit the cloning to only 5 forms
html structure for experience
<div class="col-xs-12 duplicateable-content">
<div class="form-group">
<input type="text" class="form-control" placeholder="Name">
</div>
<button class="btn btn-primary btn-duplicator">Add experience</button>
</div>
structure for education & more
<div class="col-xs-12 duplicateable-content">
<div class="form-group">
<input type="text" class="form-control" placeholder="name">
</div>
<button class="btn btn-primary btn-duplicator">Add Education</button>
</div>

Your var count=1 depends on where you declare it.
If you declare var count inside click handler it will always be set to one each click. If you declare it outside click handler it will increment.
var count = 1; // will work
$(".btn-duplicator").on("click", function(a) {
var count = 1; // won't work - is same value every click
Can also count elements
if( $(".duplicateable-content").length >=5 ){
alert('Only allowed 5');
return;// don't proceed to clone code
}

Add the following after:
$(".btn-duplicator").on("click", function(a) {
var noClones = $(this).data('clones') || 0;
$(this).data('clones', ++noClones);
if (noClones > 5) return;
// ...
// ...

Related

increment in the function name and id javascript

I have number of input types and buttons....every button on click increment the value in the relevant input types. But rather than creating a separate function for every button i want to do it by loop....where loop will increase in the function name and id......
<input type="number" id="s1"> <button onclick="increment_s1();">Add</button>
<input type="number" id="s2"> <button onclick="increment_s2()">Add</button>
<input type="number" id="s3"> <button onclick="increment_s3">Add</button>
here is JavaSc code
<script>
var i = 1;
for (i = 0; i < 5; i++) {
var data = 0;
document.getElementById("s"+i).innerText = data;
function ['increment_'+i]() {
data = data + 1;
document.getElementById("s"+i).placeholder = data;
i++;
}
}
</script>
You can't program the function name. You can set up a parameter in the function to make a difference. The param would be the identifier and you can put the whole input element id there.
After that, if you want to have the id s1, s2, and so on, you should initialize the i to start from 1 to 5 instead of 0 to less than 5.
Another thing is, you need to understand the role of placeholder and value attributes in input element. The placeholder works only when the value is empty and it doesn't count as the form value.
// This is for handling onclick
function increment(id) {
var elem = document.getElementById(id);
elem.value = parseInt(elem.value) + 1;
}
// This is to initialize the 0 values
for (var i = 1; i <= 5; i++) {
var data = 0;
document.getElementById("s"+i).value = data;
}
<input type="number" id="s1"> <button onclick="increment('s1');">Add</button>
<input type="number" id="s2"> <button onclick="increment('s2')">Add</button>
<input type="number" id="s3"> <button onclick="increment('s3')">Add</button>
<input type="number" id="s4"> <button onclick="increment('s4')">Add</button>
<input type="number" id="s5"> <button onclick="increment('s5')">Add</button>
What if you would like to generate whole input and button with loops? You can get them by adding div and use the innerHTML, i.e.
// This is for handling onclick
function increment(id) {
var elem = document.getElementById(id);
elem.value = parseInt(elem.value) + 1;
}
var divElem = document.querySelector('div');
// Set up empty first
divElem.innerHTML = "";
for(var i=1; i<=5; i++) {
// Create elements here
var innerElem = `<input type="number" id="s${i}" value="0"> <button onclick="increment('s${i}')">Add</button>`;
// Push them all into innerHTML
divElem.innerHTML += innerElem;
}
<div></div>
You can try these two workarounds. Perhaps you may need to learn more about basic HTML elements and their attributes also Javascript.

Updating LocalStorage Objects Based on Edit Form with JavaScript/jQuery?

I asked a question earlier with answers which didn't help, I still haven't been able to figure out where my issue is. Originally I thought it was because I had two IDs named the same but this was not the issue.. The form submits and there are no errors but it does not update the values in localStorage?
Edit: After changing const idx to const i the value at position [2] (or final value) would update for every booking (regardless of index). I thought of maybe changing the i value to below but it gives error i is defined before it is initialised?
bookings.findIndex(booking => bookings[i].fname == fname && bookings[i].lname == lname);
Here's what I have (updated code):
// ~~~ add bookings to localStorage
var bookings = JSON.parse(localStorage.getItem("bookings")) || [];
window.onload = showBooking();
$("#submit").click(function() {
var newBookings = {
fname: $('#fname').val(),
lname: $('#lname').val()
}
bookings.push(newBookings);
var json = JSON.stringify(bookings);
window.localStorage.setItem("bookings", json);
showBooking();
});
// ~~~ edit bookings in localStorage
$(document).on('click','#edit',function (e) {
e.preventDefault();
var parent_form = $(this.form);
var fname = parent_form.find('.input:eq(0)').val();
var lname = parent_form.find('.input:eq(1)').val();
const i = bookings.findIndex(booking => bookings.fname == fname && bookings.lname == lname);
deleteBooking(i);
bookings.push({
fname,
lname
});
var json = JSON.stringify(bookings);
window.localStorage.setItem("bookings", json);
// showBooking();
});
// ~~~ display bookings in browser
function showBooking() {
var bookingResult = document.getElementById("result");
var ul = document.createElement("ul");
// var bookingItems = JSON.parse(localStorage.getItem("bookings")) || [];
bookingResult.innerHTML = "";
for (let i = 0; i < bookings.length; i++) {
bookingResult.innerHTML += `<div class="card card-body bg-light m-4">
<h3>${bookings[i].fname + " " + bookings[i].lname}
<button onclick="deleteBooking(${i})" class="btn btn-danger text-light ">Delete</button>
<button onclick="editBooking(${i})" class="btn btn-danger text-light ">Edit</button>
</h3>
</div>`;
}
}
// ~~~ edit bookings in browser
function editBooking(i) {
// $('#regForm').hide();
$('#result').hide();
var currentItem = document.getElementById("currentItem");
var editBooking = document.getElementById("editAppt");
currentItem.innerHTML += `<div class="card card-body bg-light m-4">
<h3>${bookings[i].fname + " " + bookings[i].lname} </h3>
</div>`;
editBooking.innerHTML = `<input type="text" class="input" id="fname_${i}" placeholder="${bookings[i].fname}" name="${bookings[i].fname}" value="${bookings[i].fname}" required>
<input type="text" class="input" id="lname_${i}" placeholder="${bookings[i].lname}" name="${bookings[i].lname}" value="${bookings[i].lname}" required>
<input id="edit" type="submit" value="Edit">`;
}
// ~~~ delete bookings from localStorage
function deleteBooking(i) {
bookings.splice(i, 1);
localStorage.setItem("bookings", JSON.stringify(bookings));
showBooking();
}
My HTML form:
<form id="regForm" name="regForm" action="" class="col-sm-6">
<div class="row">
<input type="text" class="input" id="fname" placeholder="First Name" name="fname" required>
<input type="text" class="input" id="lname"placeholder="Last Name" name="lname" required>
<input id="submit" type="submit" value="Submit">
</div>
</form>
<div id="result" class="row"></div>
<div id="currentItem" class="row"></div>
<div id="editAppt" class="row"></div>
There are several changes you need to consider
You have bookings AND bookingItems
You do some changes (I assume there will be some destination change) but do not save them
You parse the localStorage far too often. Not needed. Only read once and write when modified
You cannot have duplicate IDs so you need to delegate and use class names
Be consistent and use jQuery to create elements and to add events- for example the delete button should be d er legates and remove its closest form element
Here is how to find the booking based on names
const idx = bookings.findIndex(booking => bookings.fname == fname && bookings.lname == lname);

How to get updated input values in HTML between form Tag

I want to check if a form has changed by using pure javascript.
My plan is to take all text including html tags between the form tag, hash the string and then when I need to check if any of the values has changed, I can just rehash the form and compare them.
So I have
<form action="/Building" method="post"> <div class="row">
<div class="col-md-12">
<div class="row">
<div class="col-md-3"> Building Address </div>
<div class="col-md-2"> City </div>
<div class="col-md-1"> State </div>
<div class="col-md-2"> Zip </div>
</div>
<div class="row">
<div class="col-md-3">
<input id="bldgResult_bldg_mail_address" name="bldgResult.bldg_mail_address" type="text" value="">
</div>
<div> ...etc
<input type="submit" value="Save and Next Building »" name="action:SaveContinue" class="btn btn-info pull-right">
<input type="submit" value="Save" class="btn btn-primary pull-right" name="action:Save">
<input type="submit" value="Go To Next Building" class="btn btn-primary hash" name="action:Next">
</div>
</form>
The problem is "value" of the input fields doesn't update. I'm able to change every textbox field and the value or the inner HTML doesnt change.
Here is the code that actually hashes and gets the innerHTML
window.onload = function () {
var forms = document.getElementsByTagName("form");
var hashValue = forms[1].innerHTML.hashCode();
Array.prototype.map.call(document.getElementsByClassName("hash"), function (hObj) {
hObj.addEventListener("click", function (event) {
if (document.getElementsByTagName("form")[1].innerHTML.hashCode() == hashValue) {
return true;
}
else {
var conf = confirm("Continue to the next building WITHOUT saving? Pressing \"Okay\" will undo any pending changes." );
if(conf)
{
return true;
}
event.preventDefault();
return false;
}
});
});
};
The above block
if (document.getElementsByTagName("form")[1].innerHTML.hashCode() == hashValue) {
return true;
}
Is always returning true, because the innerHTML doesnt change, even after the textboxes have been typed in.
What can I do? Is there another way to get the text in the HTML with updated information?
You could assign an event handler to the 'input' event of each of your fields that changes a boolean flag. You then just check that flag and set it back to false after your check is complete.
For example
document.querySelectorAll("#yourForm input").forEach(input => {
input.addEventListener("input", () => {
changed = true;
});
}
/* ... */
function checkIfChanged() {
if(changed) {
// ...
}
changed = false;
}
If you also need to check for backspace you could use the keypress event instead.
You could loop though your form elements, get and concatenate the values, and then hash the values.
Update:
Here is an example using FormData (depends on browser target):
Hash Function from Here: Generate a Hash from string in Javascript/jQuery
String.prototype.hashCode = function() {
var hash = 0, i, chr;
if (this.length === 0) return hash;
for (i = 0; i < this.length; i++) {
chr = this.charCodeAt(i);
hash = ((hash << 5) - hash) + chr;
hash |= 0; // Convert to 32bit integer
}
return hash;
};
function GetFormHash() {
var hashes = [];
var forms = document.getElementsByTagName("form");
var _hash = ""
for(var i=0;i<forms.length;i++) {
var formData = new FormData(forms[i]);
for (var key of formData.keys()) {
console.log(key + "=" + formData.get(key));
_hash = _hash + key + "=" + formData.get(key);
}
hashes.push(_hash.hashCode());
console.log(_hash.hashCode());
}
return hashes;
}
There is also an onchange event for <form>. Depends on browser...
<form onchange="alert('changed')"></form>
If you use something like jQuery you could use that change() event: https://api.jquery.com/category/events/form-events/
Change will not tell you if they change the data back - so not 100% reliable. If you were open to a library like jQuery - you could possibly serialize the data https://api.jquery.com/serialize/ to keep track of changes,
One last incomplete example. You would need to update to get non "input" form elements like textarea etc. You would also have to do a bit of work to get the selected radios...
function GetFormHashOther() {
var hashes = [];
var forms = document.getElementsByTagName("form");
var _hash = ""
for(var i=0;i<forms.length;i++) {
var chill = forms[i].getElementsByTagName("input");
for (var c of chill) {
console.log(c.name + " = " + c.value);
_hash = _hash + c.name + " = " + c.value;
}
hashes.push(_hash.hashCode());
console.log(_hash.hashCode());
}
return hashes;
}

Javascript can't get values from input

I'm trying to get the values from the inputs in my form with JavaScript. But whenever I hit submit, I either get nothing, 0 or undefined. Mostly undefined. It doesn't seem to get any of the values.
Here's the code
<form id="ecoCalculator">
<div class="form-group">
<label for="k0">Start Kapital</label>
<input type="number" name="k0" class="form-control" id="k0">
</div>
<div class="form-group">
<label for="kn">Slut Kapital</label>
<input type="number" name="kn" class="form-control" id="kn">
</div>
<div class="form-group">
<label for="x">Rente</label>
<input type="number" name="x" class="form-control" id="x">
</div>
<div class="form-group">
<label for="n">Terminer</label>
<input type="number" name="n" class="form-control" id="n">
</div>
<div class="ecoButtons">
<input type="button" value="Udregn" class="btn btn-default" onclick="k0Eco()">
<input type="reset" value="Ryd" class="btn btn-default">
</div>
</form>
<div class="ecoResult">
<p id="ecoResult">Resultat</p>
</div>
</div>
<script type="text/javascript">
// Public Variables
var k0 = document.getElementById('k0').value();
var kn = document.getElementById('kn').value();
var x = document.getElementById('x').value();
var n = document.getElementById('n').value();
// Calculation of Initial Capital
function k0Eco() {
// Calculation
var k0Value = kn / (1 + x) ^ n;
// Show Result
document.getElementById("ecoResult").innerHTML = k0;
}
I've looked around at different questions but haven't found a solution to this yet.
I've tried to change the names of the inputs, having the function only display a single value, but still no result.
Thanks
value isn't a function, it's a property. Change
var k0 = document.getElementById('k0').value()
to
var k0 = document.getElementById('k0').value
Your script also runs on page load, so nothing is filled yet. You need to put the whole thing in a submit handler:
document.getElementById('ecoCalculator').addEventListener('submit', function(e) {
e.preventDefault();
// your code here
});
Now remove the inline js from the button and make it type submit:
<input type="submit" value="Udregn" class="btn btn-default" />
And remove the function in your js
var k0 = document.getElementById('k0').value;
var kn = document.getElementById('kn').value;
var x = document.getElementById('x').value;
var n = document.getElementById('n').value;
// Calculation
var k0Value = kn / (1 + x) ^ n;
// Show Result
document.getElementById("ecoResult").innerHTML = k0Value;
Here's a working fiddle
you need to parse the input value in int. for eg.
// Public Variables
var k0 = parseInt(document.getElementById('k0').value);
var kn = parseInt(document.getElementById('kn').value);
var x = parseIntdocument.getElementById('x').value);
var n = parseIntdocument.getElementById('n').value);
Use value instead of value(). It is a property not a function.
Put your variables inside your function. When page loads you variables
are getting the value of the inputs and there is nothing there.
function k0Eco() {
var k0 = document.getElementById('k0').value;
var kn = document.getElementById('kn').value;
var x = document.getElementById('x').value;
var n = document.getElementById('n').value;
var k0Value = kn / (1 + x) ^ n;
document.getElementById("ecoResult").innerHTML = k0Value;
}
Put you javascript code inside <head> tag or at least before the button. When you try to fire onclick() event, your function is not created yet.

Changing Javascript variable value after onclick action

Pretty new to this Javascript thing.
I want to change a Javascript variable when a user inserts a number into an input field in my HTML document and clicks a button.
I'm assuming you'd use a function, but how do you gather the data and change the variable?
The stuff I tried to make looks a little something like this.
HTML
<input type="number" id="inputField">
<button onclick="changeTheVariable()" type="button" id="pushMe"></button>
Javascript
var a = 0;
function changeTheVariable() {
a = document.getElementById("inputField").value;
}
but it's not working!
Edit 1:
Wow. I didn't think I'd get this kind of attention. I also found it a bit strange it didn't work at first.
The question I'm asking is partly for a calculator here: https://titomagic.com/debug
It's simple, you type in a number, click the button and it calculates (based on other variables) to a result on the bottom.
Here's a link to the Javascript file, if you wanna have a look: https://titomagic.com/js/bursdagskalkulator.js
To those of you asking; yes, I've been testing with a console.log and the variable is not changing. It's not affecting the other variables (as it should?).
Also I've never heard of JSfiddle.
I discovered few things in the summarizeGjester() function. First of all I moved all the Javascript code in the bursdagskalkulator.js file inside the summarizeGjester() function. Also I converted var antallGjester to integer using parseInt() function, because it was treated as string before.
var antallGjester = document.getElementById("gjesterAntallInput").value;
antallGjester = parseInt(antallGjester); //integer conversion
Also the first Boolean comparison was changed to
if ((antallGjester < 10) && (antallGjester > 0)), so that the second one would work if there’s 0 value: else if (antallGjester === 0).
function summarizeGjester() {
var antallGjester = document.getElementById("gjesterAntallInput").value;
antallGjester = parseInt(antallGjester);
var fastPris = 1500;
var fastPrisDifferanse = 10;
var gjestePris = 120;
var gjesteDifferanse = antallGjester - fastPrisDifferanse;
var gjesteSum = gjestePris * gjesteDifferanse;
var gjesterTotalt = 0;
if ((antallGjester < 10) && (antallGjester > 0)) {
console.log("antallGjester < 10");
gjesterTotalt = 1500;
} else if (antallGjester === 0) {
console.log("antallGjester === 0");
gjesterTotalt = 0;
} else {
console.log("else");
gjesterTotalt = fastPris + gjesteSum;
}
document.querySelector('#results').innerHTML = gjesterTotalt;
}
<form>
<div class="form-group">
<label for="gjesterAntall">Antall barn:</label>
<input type="number" class="form-control" id="gjesterAntallInput">
</div>
<button class="btn btn-lg btn-warning" onclick="summarizeGjester()" type="button" id="sumGjester">Legg sammen</button>
</form>
<h1 class="text-center" style="font-size:80px;"><strong><span id="results">0</span>,-</h1>
I hope this helps :-)
HTML
<input type="number" id="inputField" ClientIDMode="static">
<button onclick="changeTheVariable()" type="button" id="pushMe"></button>
Javascript
var a = 0;
function changeTheVariable() {
a = document.getElementById('inputField').value;
alert(a);
}
Use Static ClientIDMode for stable id and access after page rendering
PlaceHolders canh change childe's id
I suppose this will work for you
var a = 0;
function changeTheVariable() {
a = document.getElementById("inputField").value || a;
document.getElementById("result").innerText = parseFloat(a);
}
<input type="number" id="inputField">
<button onclick="changeTheVariable()" type="button" id="pushMe">Click me</button>
<div>Result: <span id="result"></span></div>
Edited:
The reason behind this code is not running in jsfiddle is here.
After making the changeTheVariable() global variable this code will work in jsfiddle also. Here https://jsfiddle.net/1b9cfmje/
Use the following javascript code:
window.onload = function(){ var a = 0; window.changeTheVariable = function() { a = document.getElementById("inputField").value || a; document.getElementById("result").innerText = parseFloat(a); }}

Categories