I'm having hard time on this localstorage array. I have search it here but can't get it out. Hope you can help me with this one.
Here is my code.
$(function(){
var addWishlist = $('.add-wishlist');
addWishlist.click(function(e){
e.preventDefault();
var product_ids = [];
localStorage.setItem('product_ids', $(this).prev().val() );
console.log( localStorage.getItem('product_ids') );
});
});
The output is:
The output should be [2, 3, 4, 1]
You need to add it to array on button click and then store it to local storage. Also product_ids should be initialized outside the click event
var product_ids = [];
addWishlist.click(function(e){
e.preventDefault();
product_ids.push($(this).prev().val())
localStorage.setItem('product_ids',product_ids );
console.log(localStorage.getItem('product_ids') );
});
There a couple of things wrong:
The array product_ids is always empty because you need to push() or unshift(), or anything to fill the array.
localStorage can only take strings, I don't even think it will even recognize your empty array.
Changes
Added an extra button to load the data into localStorage
Text is entered then click the Add button.
The value of the text input is push()ed into the array productList.
Each time productList is updated, it is stored in a hidden input #cache
When the Done button is clicked, the value of #cache is converted into a string by JSON.stringify.
Once productList is a string, it is then stored in localStorageand is displayed in #output.
Due to SO sandbox, the Snippet doesn't work, so review this PLUNKER instead.
SNIPPET
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<fieldset>
<legend>wishList</legend>
<input id='in1'>
<button><a href='#' id='add'>Add</a>
</button>
<button><a href='#' id='done'>Done</a>
</button>
<label for='out1'>wishList:</label>
<output id='out1'></output>
<input id='cache' type='hidden'>
</fieldset>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script>
$(function() {
var productList = [];
$('#add').on('click', function(e) {
e.preventDefault();
var productItem = $('#in1').val();
productList.push(productItem);
$('#cache').val(productList);
});
$('#done').on('click', function(e) {
e.preventDefault();
var cached = $('#cache').val();
var str = JSON.stringify(cached);
localStorage.setItem('proList', str);
var stored = localStorage.getItem('proList');
console.log(stored)
$('#out1').html(stored);
});
});
</script>
</body>
</html>
Related
EDIT: I changed the var to class but I might have some error in here.
Here it goes, I want to have this paragraph in which the user can change the name on the following paragraph. The code I'm using only changes one name but the rest remains the same.
<script type="text/javascript">
function changey(){
var userInput = document.getElementById('userInput').value;
var list = document.getElementByClassName('kiddo');
for (let item of list) {
item.innerHTML = userInput;
}
}
</script>
<input id="userInput" type="text" value="Name of kid" />
<input onclick="changey()" type="button" value="Change Name" /><br>
Welcome to the site <b class="kiddo">dude</b> This is how you create a document that changes the name of the <b class="kiddo">dude</b>. If you want to say <b class="kiddo">dude</b> more times, you can!
No error messages, the code only changes one name instead of all three.
Use class="kiddo" instead of id in the html.
You can then use var kiddos = document.getElementsByClassName('kiddo') which will return an array of all the elements of that class name stored in kiddos.
Then you just need to loop through the values and change what you want.
Example of loop below:
for (var i = 0; i < kiddos.length; i++) {
kiddos[i].innerHTML = userInput;
}
id should be unique on the page. Javascript assumes that there is only one element with any given id. Instead, you should use a class. Then you can use getElementsByClassName() which returns an entire array of elements that you can iterate over and change. See Select ALL getElementsByClassName on a page without specifying [0] etc for an example.
Hello You should not use id, instead use class.
Welcome to the site <b class="kiddo">dude</b> This is how you create a document that changes the name of the <b class="kiddo">dude</b>. If you want to say <b class="kiddo">dude</b> more times, you can!
After That on Js part :
<script type="text/javascript">
function changey(){
var userInput = document.getElementById('userInput').value;
var list = document.getElementByClassName('kiddo');
for (let item of list) {
item.innerHTML = userInput;
}
}
</script>
you should use class instated of id. if you use id then the id [kiddo] must be unique
In short, document.querySelectorAll('.kiddo') OR
document.getElementsByClassName('kiddo') will get you a list of elements to loop through. Take note of querySelectorAll, though - it uses a CSS selector (note the dot) and doesn't technically return an array (you can still loop through it, though).
See the code below for some full working examples (const and arrow functions are similar to var and function, so I'll put up a version using old JavaScript, too):
const formEl = document.querySelector('.js-name-change-form')
const getNameEls = () => document.querySelectorAll('.js-name')
const useNameFromForm = (formEl) => {
const formData = new FormData(formEl)
const nameValue = formData.get('name')
const nameEls = getNameEls()
// Set the text of each name element
// NOTE: use .textContent instead of .innerHTML - it doesn't get parsed, so it's faster and less work
nameEls.forEach(el => el.textContent = nameValue)
}
// Handle form submit
formEl.addEventListener('submit', (e) => {
useNameFromForm(e.target)
e.preventDefault() // Prevent the default HTTP request
})
// Run at the start, too
useNameFromForm(formEl)
.name {
font-weight: bold;
}
<!-- Using a <form> + <button> (submit) here instead -->
<form class="js-name-change-form">
<input name="name" value="dude" placeholder="Name of kid" />
<button>Change Name</button>
<form>
<!-- NOTE: Updated to use js- for js hooks -->
<!-- NOTE: Changed kiddo/js-name to spans + name class to remove design details from the HTML -->
<p>
Welcome to the site, <span class="js-name name"></span>! This is how you create a document that changes the name of the <span class="js-name name"></span>. If you want to say <span class="js-name name"></span> more times, you can!
</p>
var formEl = document.querySelector('.js-name-change-form');
var getNameEls = function getNameEls() {
return document.querySelectorAll('.js-name');
};
var useNameFromForm = function useNameFromForm(formEl) {
var formData = new FormData(formEl);
var nameValue = formData.get('name');
var nameEls = getNameEls(); // Set the text of each name element
// NOTE: use .textContent instead of .innerHTML - it doesn't get parsed, so it's faster and less work
nameEls.forEach(function (el) {
return el.textContent = nameValue;
});
};
// Handle form submit
formEl.addEventListener('submit', function (e) {
useNameFromForm(e.target);
e.preventDefault(); // Prevent the default HTTP request
});
// Run at the start, too
useNameFromForm(formEl);
<button class="js-get-quote-btn">Get Quote</button>
<div class="js-selected-quote"><!-- Initially Empty --></div>
<!-- Template to clone -->
<template class="js-quote-template">
<div class="js-quote-root quote">
<h2 class="js-quote"></h2>
<h3 class="js-author"></h3>
</div>
</template>
You have done almost everything right except you caught only first tag with class="kiddo".Looking at your question, as you need to update all the values inside tags which have class="kiddo" you need to catch all those tags which have class="kiddo" using document.getElementsByClassName("kiddo") and looping over the list while setting the innerHTML of each loop element to the userInput.
See this link for examples:https://www.w3schools.com/jsref/met_document_getelementsbyclassname.asp
try:
document.querySelectorAll('.kiddo')
with
<b class="kiddo">dude</b>
I'm having trouble storing input values from <input> tag in HTML into array of strings, I can't figure out how am I suppose to do that. I have an idea on how that might look like, however I still can't get it to work.
I believe that I have to use .push() and .join() method and += or + operator, it's just I do not know where to put them.
The first thing I did was searching on Google How to store string value from input in an array of strings? but I only found on how to do it using <form> tag in HTML and I can't do that. I can't use the <form> tag.
Here's the code that I think should look like
<body>
<input type="text" id="input" />
<button onclick="submit()">Submit</button>
<div id="placeholder"></div>
</body>
var inputName = document.getElementById("input");
var cityArray = [""];
// This triggers immediately when the browser loads
window.onload = (
// Pickup the string from input and add it on the previously created array
function submit() {
inputName.value;
for (var i = 0; i < array.length; i++) {
array[i];
}
}
);
I also need a piece of code that will delete the value that was typed in a <input> field right after the Submit button is pressed, so that the user doesn't need to press Backspace in order to type the second input value.
Here is a working code snippet.
When you click the submit button, that will call the submit() function. Since your array is defined to be global, you can access it within the function. You do not need to iterate over the array, and you can simply use the .push() method to easily append a string to your array.
var inputName = document.getElementById("input");
var cityArray = [];
function submit() {
cityArray.push(inputName.value);
console.log(cityArray);
}
<body>
<input type="text" id="input" />
<button onclick="submit()">Submit</button>
<div id="placeholder"></div>
</body>
Hope this helps!
Yes you need to use .push() method it will add the new entered string to the array, without the need to iterate it:
function submit() {
cityArray.push(inputName.value);
}
And you need to initialize your array as an empty array with [] :
var cityArray = [];
And you don't need to create the submit function in the body.onload event handler because it won't be accessible outside of it and may lead for an error.
Demo:
var inputName = document.getElementById("input");
var cityArray = [];
function submit() {
cityArray.push(inputName.value);
console.log(cityArray);
}
<input type="text" id="input" />
<button onclick="submit()">Submit</button>
<div id="placeholder"></div>
Js Code
//declare your array like this
var yourArray = new Array();
//To add items to array:
yourArray.push(yourString);
//To get you can use indexing like(almost any other language)
yourArray[i]
//You can even set as an object array like this:
yourArray.push({
text: 'blablabla'
})
//So, in your case, filling up the array could be something like this:
var inputText = document.getElementById('input').value;
yourArray.push(inputText);
// show it
for (var i = 0; i < yourArray.length; i++) {
alert(yourArray[i]);
}
HTML Script
<body>
<input type="text" id="input" />
<button onclick="submit()">Submit</button>
<div id="placeholder"></div>
</body>
I have a textbox in which user can add some values one by one. Now, when user click on add button I want to insert value that user enter into array one by one. I am doing this but I am getting the wrong result. The length of array is not increasing. Say If I entered 2 values then the length of array remain 1. I don't know what's the error. Below is my code:-
HTML
<input type="text" class="form-control input_add_prod_grp" name="input_add_prod_grp" placeholder="Enter Group Name" />
<button class="btn default btn-xs btn_add_input_prod_grp" name="btn_add_input_prod_grp" id="add_group">Add</button>
Javascript
$(".btn_add_input_prod_grp").click(function(){
var add_input_grp = $("input[name$='input_add_prod_grp']").val();
var newArray = [];
newArray.push('Ungrouped');
$( "input[name='input_add_prod_grp']" ).each(function() {
newArray.push($( this ).val());
});
console.log(newArray.length);
});
Now, If I enter more than 1 value then length of array remain 1. I don't know why.. Please help me out.. Thanks in advance..
Take you array outside:
var newArray = [];
$(".btn_add_input_prod_grp").click(function(){
var add_input_grp = $("input[name$='input_add_prod_grp']").val();
newArray.push(add_input_grp);
console.log(newArray.length);
});
JSFIDDLE:https://jsfiddle.net/c19u6fa2/1/
var newArray = [];
$(".btn_add_input_prod_grp").click(function() {
var add_input_grp = $("input[name$='input_add_prod_grp']").val();
newArray.push('Ungrouped');
$("input[name='input_add_prod_grp']").each(function() {
newArray.push($(this).val());
});
console.log(newArray);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" class="form-control input_add_prod_grp" name="input_add_prod_grp" placeholder="Enter Group Name" />
<button class="btn default btn-xs btn_add_input_prod_grp" name="btn_add_input_prod_grp" id="add_group">Add</button>
Put the initialization outside of click event. Inside click event it is always reinitialize over and over.
You are making newArray empty when you click on button so the old values are deleting from that array to avoid this you have to move that to outside of your function along with default values you have only one input box you no need to write each you can get directly that value from your variable
var newArray = ['Ungrouped'];
$(".btn_add_input_prod_grp").click(function(){
var add_input_grp = $("input[name$='input_add_prod_grp']").val();
newArray.push(add_input_grp);
console.log(newArray.length);
});
I have the following code
<!----SUBMIT BUTTON---->
<input type="button" value="Submit" onClick="getData();">
.....
<div id="rev"></div>
After click on the submit button, I can be able to display my required data from my database within the text area with id='rev' in the format below:
20
30
I want to push these content of the text area into an array using jquery
<script type="text/javascript">
var arr=new Array();
function createArr()
{
var txt=$('#rev').val();
$.each(txt.split('\n'),function(i,value){
if(value!=""){
arr.push(value);
}
});
}
createArr();
document.write(arr[0]);
</script>
It seems does not work, the output on my webpage suppose to display the first element of my array which is 20. Any one can show me what did I do wrong with my code ?
It works when I changed this
<div id="rev"></div>
into
<textarea id="rev"></textarea>.
I dont know why div can not be used here ?
Wrap your entire function using window.onload function.Try this:
<script type="text/javascript">
window.onload = function(){
function createArr()
{
var arr=new Array();
var txt=$('#rev').html(); // use html() instead of val()
$.each(txt.split('\n'),function(i,value){
if(value!=""){
arr.push(value);
}
});
}
createArr();
console.log(arr[0]);
}
</script>
Demo
I think it is beause you output only the first one:
document.write(arr[0]);
Maybe you need this?
$.each(arr, function(i, val) {
document.write(val);
}
I've got a table with a load of auto complete boxes in it which look like so...
<richui:autoComplete style="width:500px" name="objSelect[${newRow-1}].id" value= "" action="${createLinkTo('dir': 'object/searchAJAX')}" forceSelection = "true" maxResultsDisplayed="20" minQueryLength ="3" onItemSelect="updateHiddenInput(id,${newRow-1})" />
I've got it to call a function called updateHiddenInput when a user selects a value passing in the id selected as well as the row the autocomplete is on (this function then updates a hidden field in the same row, using the values passed in, with the ID). The function looks like so: -
function updateHiddenInput(id, num){
var objID = "objectID[" + num + "].id";
$(document.getElementById(objID)).val(id);
}
Everything works until I add a new row within my table, this pushes everything down one row and stops the autocomplete from updating the right rows hidden field (as its still referencing the old row).
Currently I have another piece of code that goes through and renames all the fields when a new row is inserted, but I have no idea how to update the autocomplete so that it passes through the right row number, anyone know how I can alter this?
The only other alternative I could think of would be to just pass through the object itself as well as the ID I can then locate the hidden based off the object, but I can't work out how to do this, any suggestions gratefully received! :S
I've tried changing
onItemSelect="updateHiddenInput(id,${newRow-1})"
to
onItemSelect="updateHiddenInput(id,this)"
Theoretically so I can just pass through the autocomplete object and from there just traverse the page to find the hidden field I want to update. However when I then attempt to use that object in my function, for example with something like: -
var mynumber = $(myobject).closest('td').find('input').val();
I always get an "undefined" returned when I try to alert back the value...
If I just put in an alert(myobject) in the function it returns AutoComplete instance0 autoLook[0].id but if I've inserted new lines the id value doesn't change (i.e the objects id is now autoLook[3].id but it still shows [0], which I think could be part of the problem but I've got now idea how I can update this value...
I notice when looking in firebug at the html there is a /script linked to the autocomplete which could be the problem as this doesn't get updated when new lines are added and I can see multiple references to the old/original id value (see below) so maybe the passing through of this isn't passing the current objects values through...?
<script type="text/javascript">
var autoCompleteDataSource = new YAHOO.util.XHRDataSource("/Framework/object/searchAJAX");
autoCompleteDataSource.responseType = YAHOO.util.XHRDataSource.TYPE_XML;
autoCompleteDataSource.responseSchema = {
resultNode : "result",
fields : [
{ key: "name" },
{ key: "id" }
]
};
;
autoComplete = new YAHOO.widget.AutoComplete('autoLook[0].id','ad186a42e45d14d5cde8281514f877e42', autoCompleteDataSource);
autoComplete.queryDelay = 0;
autoComplete.prehighlightClassName = 'yui-ac-prehighlight';
autoComplete.useShadow = false;
autoComplete.minQueryLength = 3;
autoComplete.typeAhead = false;
autoComplete.forceSelection = true;
autoComplete.maxResultsDisplayed = 20;
autoComplete.shadow = false;
var itemSelectHandler = function(sType, args) {
var autoCompleteInstance = args[0];
var selectedItem = args[1];
var data = args[2];
var id = data[1];
updateHiddenInput(id,this) };
autoComplete.itemSelectEvent.subscribe(itemSelectHandler);
</script>
My thanks so far to user1690588 for all his help thus far! :)
On further digging I'm convinced that my issues is down to the line autoComplete = new YAHOO.widget.AutoComplete('autoLook[0].id','a5b57b386a2d1c283068b796834050186', autoCompleteDataSource); specifically the part where its inputting autoLook[].id and if I could change this I'd then be ok, but this line is auto generated and I've got no idea how to update it, anyone have any similar experience?
I have not much idea about your gsp page but I tried it on my side:
My gsp:
<!DOCTYPE html>
<html>
<head>
<resource:autoComplete skin="default"/>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<script type="text/javascript">
var counter = ${list.size()};
function asd() {
jQuery.ajax({
url: " ${createLink(controller: 'oauthCallBack', action: 'testAuto')}",
data: "idx=" + counter++,
success: function (data) {
jQuery("#tableId").append("<tr><td>" + data + "</td></tr>");
}
});
}
function updateHiddenInput(id, tg) {
jQuery(tg).val(id);
}
</script>
</head>
<body>
<g:form>
<table id="tableId">
<g:each in="${list}" var="vr" status="idx">
<tr>
<td>
<richui:autoComplete name="name" id="uniqueId${idx}" action="${createLinkTo('dir': 'oauthCallBack/test')}" onItemSelect="updateHiddenInput(id, someId${idx})"/>
<g:hiddenField name="someName" id="someId${idx}" value=""/>
</td>
</tr>
</g:each>
</table>
</g:form>
<button onclick="asd()">Add</button>
</body>
</html>
My action:
def testAuto() {
render template: 'addNew', model: [idx: params.idx]
}
My template(addNew):
<richui:autoComplete name="name" id="uniqueId${idx}" action="${createLinkTo('dir': 'oauthCallBack/test')}"
onItemSelect="updateHiddenInput(id, someId${idx})"/>
<g:hiddenField name="someName" id="someId${idx}" value=""/>
Try this..,.
EDIT.....................................................................................
I supposed that you have successfully updated all the input field names. Then you can edit hidden field like:
View:
<tr class="dummyClass">
<td>
<richui:autoComplete name="name[${idx}]" id="uniqueId[${idx}]" action="${createLinkTo('dir': 'oauthCallBack/test')}" onItemSelect="updateHiddenInput(id, this)"/>
<g:hiddenField name="someName[${idx}]" id="someId[${idx}]" value=""/>
</td>
</tr>
jQuery:
function updateHiddenInput(id, tg) {
jQuery(tg._elTextbox).closest("tr.dummyClass").find("input[type=hidden]").val(id);
}
EDIT.....................................................................................
Why you need to change the 'id'? Changing name is sufficient to send values in order. And you can update the hidden field without id as above edit.
If you still need to change the id then you can change it by cloning the tr and then use regex. See this answer for full working example.