[![enter image description here][1]][1]I am looking to clear out all the fields that are filled in from this script below when a second search is entered. This script fills in 25 boxes with shoe-sizes and prices after for looping through it all, the problem is if the next item searched does not have the same number of shoe sizes (which is often), the boxes are left with the previous data (ex. First shoe goes up to size 15, the next shoe search only goes up to size 12, so sizes 12.5-15 are left with the previous data because its not overwriting them).
$('#searchForm').on('submit', (e) => {
e.preventDefault();
let searchText = $('#search-box').val();
$.ajax({
url: "/",
type: 'POST',
data: {
input: searchText},
success: function(res) {
console.log(res);
let product = res;
document.getElementById("shoe").innerHTML = (product.stockx.shoeId);
document.getElementById("date").innerHTML = (product.stockx.release);
document.getElementById("sneakerid").style.backgroundImage = 'url('+(product.photo)+')';
document.getElementById("shoeOverlay").style.backgroundImage = 'url('+(product.photo)+')';
let size = product.stockx.price_size
for( let i = 0; i < size.length; i += 1) {
document.getElementById(i === 0 ? `shoesize` : `shoesize${i}`).innerHTML = (size[i].sizing),
document.getElementById(i === 0 ? `stockxprice` : `stockxprice${i}`).innerHTML = ('$' + size[i].pricing);
}
for( let i = 0; i < product.sizes.length; i += 1) {
document.getElementById(i === 0 ? `goatprice` : `goatprice${i}`).innerHTML = ('$' + product.sizes[i][1]*.01);
if (product.sizes[i][1]*.01 > size[i].pricing) document.getElementById(i === 0 ? `goatprice` : `goatprice${i}`).style.color = "#00ffb3";
else if (product.sizes[i][1]*.01 < size[i].pricing) document.getElementById(i === 0 ? `stockxprice` : `stockxprice${i}`).style.color = "#00ffb3";
}
}}
)})
})
HTML snippet
<table class="table">
<tr>
<td>
<div class="innerbox">
<div id="shoesize" ></div>
<div class="prices">
<div id="stockxprice"></div>
<div id="goatprice"></div>
</div>
<div class="logocontainer">
<div class="stockxlogo"> <img src="img/stockxlogo.svg" ></div>
<div class="goatlogo"><img src="img/goatlogo.svg" height="30px" width="30px"></div>
</div>
<form id="searchForm">
<input type="text" autocomplete="off" id="search-box">
<div class="searchlogo"> <img src="img/searchlogo.svg" height="15px" width="15px" href="#"></div>
</form>
</div>
[1]: https://i.stack.imgur.com/plWLo.jpg
If the elements are inside a form, you can use the form.reset() method.
HTMLFormElement.reset():
The HTMLFormElement.reset() method restores a form element's default values. This method does the same thing as clicking the form's reset button.
you can read more here: HTMLFormElement.reset
Run and test:
function resetForm() {
let form = document.getElementById("myForm");
form.reset();
}
<form id="myForm">
<input type="text" value="" />
<input type="text" value="" />
<input type="text" value="" />
<input type="text" value="" />
<input type="text" value="" />
<input type="text" value="" />
</form>
<input type="button" value="reset" onclick="resetForm()" />
EDIT: If the elements are not inside a form:
If your elements are not inside a form, you can then give them all a common class name to help you iterate through them.
Run and test:
function resetElems() {
$(".resetable").html("");
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="shoesize" class="resetable">15</div>
<div class="prices">
<div id="stockxprice" class="resetable">13</div>
<div id="goatprice" class="resetable">14</div>
</div>
<input type="button" value="click to reset" onclick="resetElems()" />
EDIT 2: To only reset on the second search and after:
If you wish to only perform the reset after the first search you can declare a global variable to keep count of the searches (increment it on every search) and then do something like this:
var count = 0; // this variable is global; it's not inside any function
$('#searchForm').on('submit', (e) => {
e.preventDefault();
let searchText = $('#search-box').val();
$.ajax({
url: "/",
type: 'POST',
data: {
input: searchText
},
success: function(res) {
if(count > 0) { // only reset if it's not the first search
$(".resetable").html("");
}
count++; // increment the count
// other code ...
}
});
});
Related
I have created a form which can be dynamically changed using the buttons included. These buttons allow for more input fields to be added/removed. The issue is that the input fields created are not posting any data/ Values in those fields not being added to the $POST array on the submit of the form.
The main functions below resposible for adding and removing rows is RemoveRows() and addRows()
What should happen is that on submit all values in the form should be "posted" then I can access all of those fields via $_POST["nameOfField"].
The way I have currently approached this is to create an input fields with the relevant id's and names then append that field to where the "hard coded" fields exists.
From my initial debugging none of the fields that have been added via javascript are in $Post which I have checked via var_dump($_REQUEST);
I have also seen that the nodes that are added are not elements of the form tag even though the nodes are added between the opening and closing tag. This can be seen in the doBeforeSubmit() Function where we can see all elements that are children of the and this never changes as rows are added/removed.
function showPlatforms() {
let nacellesOptions = ["Option1", "option2", "Option3"];
let milOptions = ["Option1", "option2", "Option3"]
let highOptions = ["Option1", "option2", "Option3"]
let entry = document.getElementById("vs")
let platfom = document.getElementById("platform")
if (platform.hasChildNodes()) {
var lastChild = platfom.lastElementChild
while (lastChild) {
platfom.removeChild(lastChild)
lastChild = platform.lastElementChild
}
}
if (entry.value == "Nacelles") {
for (var i = 0; i < 2; i++) {
var option = document.createElement("option");
option.value = nacellesOptions[i]
option.innerHTML = nacellesOptions[i]
platform.appendChild(option)
}
} else if (entry.value == "Military") {
for (var i = 0; i < 2; i++) {
var option = document.createElement("option");
option.value = milOptions[i]
option.innerHTML = milOptions[i]
platform.appendChild(option)
}
} else {
for (var i = 0; i < 2; i++) {
var option = document.createElement("option");
option.value = highOptions[i]
option.innerHTML = highOptions[i]
platform.appendChild(option)
}
}
}
function formOptions() {
let entry = document.getElementById("type")
if (entry.value == "Engineering MAM") {
document.getElementById("WBS").disabled = false
document.getElementById("Desc").disabled = false
document.getElementById("ProName").disabled = false
} else {
document.getElementById("WBS").disabled = true
document.getElementById("Desc").disabled = true
document.getElementById("ProName").disabled = true
}
}
function formoptions2() {
let entry2 = document.getElementById("organisation")
if (entry2.value == "Aftermarket") {
document.getElementById("COT").disabled = false
document.getElementById("COC").disabled = false
} else {
document.getElementById("COT").disabled = true
document.getElementById("COC").disabled = true
}
}
count = document.getElementById("partNum").childElementCount
function addRows() {
rowNames = ["partNum", "partDesc", "leadTime", "quantity", "dateReq", "unitCost", "unitExtention", "unitSaleValue", "estSalesValue"]
rowNames.forEach(addRow, count)
count = document.getElementById("partNum").childElementCount
//doBeforeSubmit()
}
function doBeforeSubmit() {
var es = document.getElementById("form").elements;
var l = es.length;
var msgs = [];
for (var idx = 0; idx < l; idx++) {
var e = es[idx];
msgs.push('name=' + e.name + ', type=' + e.type + ', value=' + e.value);
}
alert(msgs.join('\n'));
return false;
}
function addRow(id) {
let col = document.getElementById(id)
var box = document.createElement("INPUT")
box.setAttribute("type", "text")
box.setAttribute("id", id + count)
box.setAttribute("name", id + count)
box.setAttribute("class", "form-control")
col.appendChild(box)
}
function RemoveRows() {
rowNames = ["partNum", "partDesc", "leadTime", "quantity", "dateReq", "unitCost", "unitExtention", "unitSaleValue", "estSalesValue"]
rowNames.forEach(removeBoxes)
count = document.getElementById("partNum").childElementCount
}
function removeBoxes(item) {
let box = document.getElementById(item)
let last = box.lastChild
box.removeChild(last)
}
function checkData() {
// if all stuff is correct do this:
document.getElementById("submit").disabled = false
// else dont activate the submit button.
}
<form method="post" id="form" action="SubmitMAM.php">
<div class="row" id="productRow" style="width:95%; margin:auto">
<div id="partNo" class="col-2">
<h3>Part Number:</h3>
</div>
<div class="col-2">
<h3>Part Description:</h3>
</div>
<div class="col-1">
<h3>Lead Time:</h3>
</div>
<div class="col-1">
<h3>Quantity:</h3>
</div>
<div class="col-1">
<h3>Date Required:</h3>
</div>
<div class="col-1">
<h3>Unit Cost:</h3>
</div>
<div class="col-2">
<h3>Unit Cost Extension:</h3>
</div>
<div class="col-1">
<h3>Unit Sale Value:</h3>
</div>
<div class="col-1">
<h3>Est Sales Value:</h3>
</div>
</div>
<div class="row" id="productRow" style="width:95%; margin:auto">
<div id="partNum" class="col-2">
<input type="text" id="partNum0" class="form-control" name="partNum0">
</div>
<div id="partDesc" class="col-2">
<input type="text" id="partDesc0" class="form-control" name="partDesc0">
</div>
<div id="leadTime" class="col-1">
<input type="text" id="leadTime0" class="form-control" name="leadTime0">
</div>
<div id="quantity" class="col-1">
<input type="text" id="quanitity0" class="form-control" name="quantity0">
</div>
<div id="dateReq" class="col-1">
<input type="text" id="dateReq0" class="form-control" name="dateReq0">
</div>
<div id="unitCost" class="col-1">
<input type="text" id="unitCost0" class="form-control" name="unitCost0">
</div>
<div id="unitExtention" class="col-2">
<input type="text" id="unitExtention0" class="form-control" name="unitExtention0">
</div>
<div id="unitSaleValue" class="col-1">
<input type="text" id="unitSaleValue0" class="form-control" name="unitSaleValue0">
</div>
<div id="estSalesValue" class="col-1">
<input type="text" id="estSalesValue0" class="form-control" name="estSalesValue0">
</div>
<button onclick="addRows()" class="btn btn-primary" type="button">Add a Product</button>
<button onclick="RemoveRows()" class="btn btn-primary" type="button">Remove Row</button>
<button onclick="checkData()" class="btn btn-primary" type="button">Check Data</button>
<br>
<button type="submit" name="submit" id="submit" class="btn btn-primary" disabled>Submit</button>
</form>
PHP:
<?php
var_dump($_REQUEST)
?>
UPDATE:
The code has been changed to use a php array by adding square brackets into the name which produces the following html:
<input type="text" id="partNum0" class="form-control" name="partNum[]">
<input type="text" id="partNum1" name="partNum[]" class="form-control">
<input type="text" id="partNum2" name="partNum[]" class="form-control">
You just need to use the name property of the input and add [] at the end, as GrumpyCrouton said. PHP parse it as an array, and you can access it as:
$partNum = $_POST["partNum"];
FIXED: It turns out the above code did not have any issues with the logic or the way it should work, in the source code in visual studio the indentation of some of the Divs was off causing the browser to have issues in rendering the form correctly hence why the added boxes were not included in the form and their values not POSTED.
As a heads up to anyone with maybe a similar issue, it pays to have your code neat.
I have a html form, where user need to enter the name and address of their office. The number of offices are dynamic.
I want to add an Add More button, so that users can enter the details of any number of offices.
My question is, how can I create an array of inputs where new elements can be added and removed using JavaScript. Currently, I'm doing it using js clone method, but I want an array, so that input data can easily be validated and stored to database using Laravel.
What I'm currently doing..
This is my HTML form where users have to enter the address of their clinic or office. I've taken a hidden input field and increasing the value of that field whenever a new clinic is added, so that I can use loop for storing data.
<div class="inputs">
<label><strong>Address</strong></label>
<input type="text" class="hidden" value="1" id="clinicCount" />
<div id="addresscontainer">
<div id="address">
<div class="row" style="margin-top:15px">
<div class="col-md-6">
<label><strong>Clinic 1</strong></label>
</div>
<div class="col-md-6">
<button id="deleteclinic" type="button" class="close deleteclinic"
onclick="removeClinic(this)">×</button>
</div>
</div>
<textarea name="address1" placeholder="Enter Clinic Address" class="form-control"></textarea>
<label class="text-muted" style="margin-top:10px">Coordinates (Click on map to get coordinates)</label>
<div class="row">
<div class="col-md-6">
<input class="form-control" id="latitude" type="text" name="latitude1" placeholder="Latitude" />
</div>
<div class="col-md-6">
<input class="form-control" id="longitude" type="text" name="longitude1" placeholder="Longitude" />
</div>
</div>
</div>
</div>
</div>
<div class="text-right">
<button class="btn btn-success" id="addclinic">Add More</button>
</div>
And my js code..
function numberClinic(){
//alert('test');
var i=0;
$('#addresscontainer > #address').each(function () {
i++;
$(this).find("strong").html("Clinic " + i);
$(this).find("textarea").attr('name','name'+i);
$(this).find("#latitude").attr('name','latitude'+i);
$(this).find("#longitude").attr('name','longitude'+i);
});
}
$("#addclinic").click(function(e){
e.preventDefault();
$("#addresscontainer").append($("#address").clone());
numberClinic();
$("#addresscontainer").find("div#address:last").find("input[name=latitude]").val('');
$("#addresscontainer").find("div#address:last").find("input[name=longitude]").val('');
$("#clinicCount").val(parseInt($("#clinicCount").val())+1);
});
function removeClinic(address){
if($("#clinicCount").val()>1){
$(address).parent('div').parent('div').parent('div').remove();
$("#clinicCount").val(parseInt($("#clinicCount").val())-1);
}
numberClinic();
}
This way, I think I can store the data to the database but can't validate the data. I'm using the laravel framework.
One way you could do this is by using the position of the input in the parent as the index in the array, then saving the value in the array every time each input is changed. Then you can just add and remove inputs.
Sample code:
var offices = document.getElementById('offices');
var output = document.getElementById('output');
var data = [];
var i = 0;
document.getElementById('add').addEventListener('click', function() {
var input = document.createElement('input');
input.setAttribute('type', 'text');
input.setAttribute('placeholder', 'Office');
var button = document.createElement('button');
var index = i++;
input.addEventListener('keyup', function() {
for (var i = 0; i < offices.children.length; i++) {
var child = offices.children[i];
if (child === input) {
break;
}
}
// i is now the index in the array
data[i] = input.value;
renderText();
});
offices.appendChild(input);
});
document.getElementById('remove').addEventListener('click', function() {
var children = offices.children;
if (children.length === data.length) {
data = data.splice(0, data.length - 1);
}
offices.removeChild(children[children.length - 1]);
renderText();
});
function renderText() {
output.innerHTML = data.join(', ');
}
JSFiddle: https://jsfiddle.net/94sns39b/2/
Problem
The maximum number of players for each position is:
2 out of 4 goalies
6 out of 15 defencemen
12 out of 31 forwards
I've gotten to the point where I'll click on a hockey player and that name gets added to a input field in a form, but if you already have two goalies selected, ie has a class of is-active and then click on one of the other two unselected players with the default is-inactive class, that name will still be added into an input when there should only be two goalies max. And unfortunately, this is also the case with the defencemen and the forwards too.
Goal
When starredGoaltenders === maxGoaltenders or starredDefencemen === maxDefencemen or starredForwards === maxFowards the names of players that do not have not been selected of that specific position and do not have an is-active class should not be added to any input in the form.
scripts.js
function countSelected() {
$(".player").on("click", function(){
// Checks if the maximum number of players have been selected
// If so, return false and then do nothing
// If not, the class will toggle from `is-inactive` to `is-active`
if ($(this).find(".picked.is-inactive.full").length > 0) return false;
$(this).find(".picked").toggleClass("is-inactive is-active");
$(".player").removeClass("not-picked");
$(".player").not(":has(.is-active)").addClass("not-picked");
// Count the number of players with stars
var starredGoaltenders = $(".player--goalie").find(".picked.is-active").length;
var starredDefencemen = $(".player--defencemen").find(".picked.is-active").length;
var starredForwards = $(".player--forward").find(".picked.is-active").length;
console.log(starredGoaltenders, starredDefencemen, starredForwards);
// The number of starred players for each position cannot exceed the following numbers
var maxGoaltenders = 2;
var maxDefencemen = 6;
var maxFowards = 12;
// If the number of starred players hits its max, a class of `is-completed` is adding to the corresponding checkmark to indicate that the task has been completed
if (starredGoaltenders === maxGoaltenders) {
$(".checkmark--goalie").addClass("is-completed");
$(".player--goalie").find(".picked").addClass("full");
} else {
$(".checkmark--goalie").removeClass("is-completed");
$(".player--goalie").find(".picked.is-inactive").removeClass('full');
}
if (starredDefencemen === maxDefencemen) {
$(".checkmark--defencemen").addClass("is-completed");
$(".player--defencemen").find(".picked").addClass("full");
} else {
$(".checkmark--defencemen").removeClass("is-completed");
$(".player--defencemen").find(".picked.is-inactive").removeClass('full');
}
if (starredForwards === maxFowards) {
$(".checkmark--forward").addClass("is-completed");
$(".player--forward").find(".picked").addClass("full");
} else {
$(".checkmark--forward").removeClass("is-completed");
$(".player--forward").find(".picked.is-inactive").removeClass('full');
}
// If all the conditions are met show the submit vote button
if (starredGoaltenders === maxGoaltenders && starredDefencemen === maxDefencemen && starredForwards === maxFowards) {
$(".btn--submit").show();
$(".btn--submit").addClass("slideLeft");
} else{
$(".btn--submit").hide();
$(".btn--submit").removeClass("slideLeft");
}
});
} countSelected();
// Every time a player is clicked, note the name of the player
$(".player").on("click", function(){
var playerNames = [];
$("input:text").each(function(i, t) { playerNames.push(t.value) });
if ($(this).find("picked.is-active")) {
var playerName = $(this).find(".player__name").html();
var index = playerNames.indexOf(playerName);
if (index == -1) // Add player
$("input:text:eq(" + playerNames.indexOf("") + ")").val(playerName);
else // Remove player
$("input:text:eq(" + index + ")").val("");
} else {
$("input").val("");
}
});
index.html - Snippet includes form and one out of the 60 available players to be clicked on
<form id="form">
<input type="text" name="p1" id="p1">
<input type="text" name="p2" id="p2">
<input type="text" name="p3" id="p3">
<input type="text" name="p4" id="p4">
<input type="text" name="p5" id="p5">
<input type="text" name="p6" id="p6">
<input type="text" name="p7" id="p7">
<input type="text" name="p8" id="p8">
<input type="text" name="p9" id="p9">
<input type="text" name="p10" id="p10">
<input type="text" name="p11" id="p11">
<input type="text" name="p12" id="p12">
<input type="text" name="p13" id="p13">
<input type="text" name="p14" id="p14">
<input type="text" name="p15" id="p15">
<input type="text" name="p16" id="p16">
<input type="text" name="p17" id="p17">
<input type="text" name="p18" id="p18">
<input type="text" name="p19" id="p19">
<input type="text" name="p20" id="p20">
<button class="btn btn--submit" type="submit"><img src="src/img/ballot-alt.png" class="image--ballot">Submit Vote</button>
</form>
<div class="player player--forward year--2000 year--2010">
<div class="tooltip">
<p class="tooltip__name">Mark Stone</p>
<p class="tooltip__hometown"><span>Hometown:</span> Winnipeg, Man.</p>
<p class="tooltip__years"><span>Years Played:</span> 2008-2012</p>
<div class="tooltip__stats--inline">
<div class="stats__group stats--games">
<p class="stats__header">GP</p>
<p class="stats__number stats__number--games">232</p>
</div>
<div class="stats__group stats--goals">
<p class="stats__header">G</p>
<p class="stats__number stats__number--goals">106</p>
</div>
<div class="stats__group stats--assists">
<p class="stats__header">A</p>
<p class="stats__number stats__number--assists">190</p>
</div>
<div class="stats__group stats--points">
<p class="stats__header">Pts</p>
<p class="stats__number stats__number--points">296</p>
</div>
<div class="stats__group stats--penalties">
<p class="stats__header">Pim</p>
<p class="stats__number stats__number--penalties">102</p>
</div>
</div>
</div>
<div class="player__headshot player--mstone">
<div class="picked is-inactive"><i class="fa fa-star" aria-hidden="true"></i></div>
</div>
<p class="player__name">Mark Stone</p>
<p class="player__position">Forward</p>
</div>
Probably, the easiest way to approach this problem is to repopulate all your inputs every time someone clicks on a player, rather than trying to populate each input once. This means you can keep your application state in a simple, easily understood data structure that is independent of your DOM/UI, rather than having to consult the DOM each time something new happens.
This is how I would probably write it.
var players = [
{name: 'Ovechkin', type: 'F'},
{name: 'Dubnyk', type: 'G'}
// your complete player list goes here
],
selectedPlayers: []; // these are the players the user has chosen
var getCurrentPlayerCount = function (playerType) {
// return the number of players currently selected of one type
return selectedPlayers.reduce(function (count, player) {
if (player.type === playerType) return count + 1;
return count;
}, 0);
}
var selectPlayer = function (player) {
// You call this when someone clicks on a player
var currentForwardCount = getCurrentPlayerCount('F')
currentDefenceCount = getCurrentPlayerCount('D'),
currentGoalieCount = getCurrentPlayerCount('G');
// Do nothing (or show a UI message) if someone goes over their
// player-type limit
if (player.type === 'F' && currentForwardCount > 12) return;
if (player.type === 'D' && currentDefenceCount > 6) return;
if (player.type === 'G' && currentGoalieCount > 2) return;
// If you get here, it means the player can be added, so add
// it to the user's list
selectedPlayers.push(player);
updateUI();
}
I'm not including updateUI here. You can work that out on your own.
If you need to support IE 8 or any other browser that does not support Array.prototype.reduce, you will need to do getCurrentPlayerCount differently.
I've tried many different methods, and even tried searching on SO. No answer was what I was looking for.
What I want is to have two input buttons that do some things in pure javascript.
Button one: Have it say "Add" when the page loads. When clicked, the value changes to "Cancel." Also, when it's clicked, have it display a form with three fields. When it's clicked again, have the form disappear. One named 'name', the second named 'location', the third named 'type'. I want the user to be able to submit these three things and have them be stored in the code.
Button two: Take the user input from the form and each time the user clicks, it displays all three information values, but have the button act as random generator. Let's say the code has 5 separate entries, I want them to be randomly selected and displayed when the button is clicked.
Like I said, I tried to make this work, but couldn't quite get over the top of where I wanted to go with it. If you want to see my original code, just ask, but I doubt it will be of any assistance.
Thanks in advance.
EDIT: Added the code.
function GetValue() {
var myarray = [];
var random = myarray[Math.floor(Math.random() * myarray.length)];
document.getElementById("message").innerHTML = random;
}
var testObject = {
'name': BWW,
'location': "Sesame Street",
'type': Bar
};
localStorage.setItem('testObject', JSON.stringify(testObject));
var retrievedObject = localStorage.getItem('testObject');
function change() {
var elem = document.getElementById("btnAdd1");
if (elem.value == "Add Spot") {
elem.value = "Cancel";
} else elem.value = "Add Spot";
}
window.onload = function() {
var button = document.getElementById('btnAdd1');
button.onclick = function show() {
var div = document.getElementById('order');
if (div.style.display !== 'none') {
div.style.display = 'none';
} else {
div.style.display = 'block';
}
};
};
<section>
<input type="button" id="btnChoose" value="Random Spot" onclick="GetValue();" />
<p id="message"></p>
<input type="button" id="btnAdd1" value="Add Spot" onclick="change();" />
<div class="form"></div>
<form id="order" style="display:none;">
<input type="text" name="name" placeholder="Name of Resturant" required="required" autocomplete="on" />
<input type="text" name="type" placeholder="Type of Food" required="required" autocomplete="off" />
<input type="text" name="location" placeholder="Location" required="required" autocomplete="off" />
<input type="submit" value="Add Spot" />
</form>
</div>
</section>
The randomizer works, and so does the appear/hide form. Only thing is storing the input and switching the input value.
Here's one way to do this. Each form submission is stored as an object in an array. The random button randomly selects an item from the array and displays it below.
HTML:
<section>
<input type="button" id="btnChoose" value="Random Spot" />
<p id="message"></p>
<input type="button" id="btnAdd1" value="Add Spot" />
<div class="form">
<form id="order" style="display:none;">
<input id="orderName" type="text" name="name" placeholder="Name of Resturant" required="required" autocomplete="on" />
<input id="orderType" type="text" name="type" placeholder="Type of Food" required="required" autocomplete="off" />
<input id="orderLocation" type="text" name="location" placeholder="Location" required="required" autocomplete="off" />
<input type="submit" value="Add Spot" />
</form>
</div>
</section>
<div id="randomName"></div>
<div id="randomLocation"></div>
<div id="randomType"></div>
JS:
var formData = [];
var formSubmission = function(name, location, type) {
this.name = name;
this.location = location;
this.type = type;
}
var spotName = document.getElementById("orderName"),
spotLocation = document.getElementById("orderLocation"),
spotType = document.getElementById("orderType");
var addClick = function() {
if (this.value === 'Add Spot') {
this.value = "Cancel";
document.getElementById('order').style.display = 'block';
}
else {
this.value = 'Add Spot';
document.getElementById('order').style.display = 'none';
}
}
document.getElementById("btnAdd1").onclick = addClick;
document.getElementById('order').onsubmit = function(e) {
e.preventDefault();
var submission = new formSubmission(spotName.value, spotLocation.value, spotType.value);
formData.push(submission);
submission = '';
document.getElementById('btnAdd1').value = 'Add Spot';
document.getElementById('order').style.display = 'none';
this.reset();
}
var randomValue;
document.getElementById('btnChoose').onclick = function() {
randomValue = formData[Math.floor(Math.random()*formData.length)];
document.getElementById('randomName').innerHTML = randomValue.name;
document.getElementById('randomLocation').innerHTML = randomValue.location;
document.getElementById('randomType').innerHTML = randomValue.type;
}
I was working on something since you first posted, and here is my take on it:
HTML:
<section>
<p id="message">
<div id="name"></div>
<div id="location"></div>
<div id="type"></div>
</p>
<input type="button" id="btnAdd" value="Add" onclick="doAdd(this);" />
<input type="button" id="btnShow" value="Show" onclick="doShow(this);" />
<div class="form">
<script id="myRowTemplate" type="text/template">
<input type="text" name="name" placeholder="Name of Resturant" required="required" autocomplete="on" onchange="onChanged(this, {{i}})" />
<input type="text" name="type" placeholder="Type of Food" required="required" autocomplete="off" onchange="onChanged(this, {{i}})" />
<input type="text" name="location" placeholder="Location" required="required" autocomplete="off" onchange="onChanged(this, {{i}})" />
</script>
<form id="order" style="display:none;">
<div id="formItems">
</div>
<input type="button" value="Add Spot" onclick="addSpot()" />
</form>
</div>
</section>
JS:
function GetValue() {
if (enteredItems.length) {
var entry = enteredItems[Math.floor(Math.random() * enteredItems.length)];
document.getElementById("name").innerHTML = entry.name;
document.getElementById("location").innerHTML = entry.location;
document.getElementById("type").innerHTML = entry.type;
}
}
function doAdd(elem) {
switch (elem.value) {
case "Add":
document.getElementById('order').style.display = "";
elem.value = "Cancel";
break;
case "Cancel":
document.getElementById('order').style.display = "none";
elem.value = "Add";
break;
}
}
function doShow(elem) {
GetValue();
}
function addSpot(index) { // (note: here, index is only for loading for the first time)
if (index == undefined) index = enteredItems.length;
var newRowDiv = document.createElement("div");
newRowDiv.innerHTML = document.getElementById("myRowTemplate").innerHTML.replace(/{{i}}/g, index); // (this updates the template with the entry in the array it belongs)
if (enteredItems[index] == undefined)
enteredItems[index] = { name: "", location: "", type: "" }; // (create new entry)
else {debugger;
newRowDiv.children[0].value = enteredItems[index].name;
newRowDiv.children[1].value = enteredItems[index].location;
newRowDiv.children[2].value = enteredItems[index].type;
}
document.getElementById("formItems").appendChild(newRowDiv);
}
function onChanged(elem, index) {
enteredItems[index][elem.name] = elem.value;
localStorage.setItem('enteredItems', JSON.stringify(enteredItems)); // (save each time
}
// update the UI with any saved items
var enteredItems = [];
window.addEventListener("load", function() {
var retrievedObject = localStorage.getItem('enteredItems');
if (retrievedObject)
enteredItems = retrievedObject = JSON.parse(retrievedObject);
for (var i = 0; i < enteredItems.length; ++i)
addSpot(i);
});
https://jsfiddle.net/k1vp8dqn/
It took me a bit longer because I noticed you were trying to save the items, so I whipped up something that you can play with to suit your needs.
I apologize for the wordy title but I haven't found a solution to my problem yet. I am a newbie with jQuery and web development so any guidance would be appreciated.
I have a <input> that allows user to enter a value (number) of how many rows of a set of input fields they want populated. Here's my example:
<div id="form">
<input id="num" name="num" type="text" />
</div>
<p> </p>
<div id="form2">
<form action="" method="post" class="form_main">
<div class="data">
<div class="item">
<input id="name" name="name[]" type="text" placeholder="name" /><br/>
<input id="age" name="age[]" type="text" placeholder="age" /><br/>
<input id="city" name="city[]" type="text" placeholder="city" /><br/>
<hr />
</div>
</div>
<button type="submit" name="submit">Submit</button>
</form>
My jQuery:
<script>
var itemNum = 1;
$("#num").on("change", function() {
var count = this.value;
var item = $(".item").parent().html();
//item.attr('id', 'item' + itemNum);
for(var i = 2; i <= count; i++) {
itemNum++;
$(".data").append(item);
}
})
</script>
I'm having problems adding an ID item+itemNum increment to <div class="item">... item.attr() didn't work. It doesn't append once I added that line of code.
Also, how can I get it so that once a user enters a number that populates rows of input fields, that if they change that number it will populate that exact number instead of adding to the already populated rows? Sorry if this doesn't make any sense. Please help!
Here is a DEMO
var itemNum = 1;
$("#num").on("change", function() {
$('.data div').slice(1).remove(); //code for removing previously populated elements.
var count = this.value;
console.log(count);
var item;
//item.attr('id', 'item' + itemNum);
var i;
for(i = 1; i <= count; i++) {
console.log(i);
item = $("#item0").clone().attr('id','item'+itemNum);
//prevent duplicated ID's
item.children('input[name="name[]"]').attr('id','name'+itemNum);
item.children('input[name="age[]"]').attr('id','age'+itemNum);
item.children('input[name="city[]"]').attr('id','city'+itemNum);
itemNum++;
$(".data").append(item);
}
})
Use clone() instead of html()
Try
var itemNum = 1,
item = $(".data .item").parent().html();;
$("#num").on("change", function () {
var count = +this.value;
if (itemNum < count) {
while (itemNum < count) {
itemNum++;
$(item).attr('id', 'item' + itemNum).appendTo('.data')
}
} else {
itemNum = count < 1 ? 1 : count;
$('.data .item').slice(itemNum).remove();
}
})
Demo: Fiddle