Insert Textbox values in Array in Jquery / Javascript - javascript

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);
});

Related

Storing input value in Array, getting duplicate console logs

I am trying to store input values from an HTML form using javascript. I have the result I am looking for but not certain if it is the correct or most efficient way, as each time I press submit, it loops through and increase the array, but also the console log duplicates by one.
I am already quite aware that I have two console logs, that was not the question. The downvote without explanation is quite unnecessary as how am I to improve my query's?
let inputArr= [];
document.getElementById("submit-btn").onclick = function submitFormVal(event){
event.preventDefault();
let inputVal;
inputVal = document.getElementById("form-val").value;
console.log(inputVal);
inputArr.push(inputVal);
for(let i =0; i < inputArr.length;i++){
inputArr[i];
inputArr = inputArr.map(Number);
console.log(inputArr);
};
};
<form id="form-test">
<input type="number" id="form-val" value="1">
<button id="submit-btn">Submit</button>
</form>
Your console.log() is inside your loop. As the array grows, the loop iterates more and so you get more logging of the same array.
Move it so that it runs after the loop and use console.clear() at the beginning of the function so you only see the newest data.
Also, don't use a submit button if you aren't actually submitting any data anywhere. Just use a regular button and then you don't need to worry about cancelling the submit event.
Lastly, use modern standards. onclick (an event property) limits your ability to work with the event. Instead use .addEventListener
let inputArr= [];
document.getElementById("submit-btn").addEventListener("click", function(event){
console.clear(); // clear out old data
let inputVal;
inputVal = document.getElementById("form-val").value;
console.log(inputVal);
inputArr.push(inputVal);
for(let i =0; i < inputArr.length;i++){
inputArr[i];
inputArr = inputArr.map(Number);
};
console.log(inputArr);
});
<form id="form-test">
<input type="number" id="form-val" value="1">
<button type="button" id="submit-btn">Submit</button>
</form>
Now, with all that in mind, the real solution here is much simpler than what you are doing. There is no need for a loop that creates a new array of numbers with one more item in it. All you have to do is .push the new data (with a simple number conversion) into the existing array. Also, get your DOM reference just once before the button is pressed so you don't have to keep finding it every time the button is pushed.
let inputArr= [];
// Get your DOM reference just once, not every time you click the button
let inputVal = document.getElementById("form-val")
document.getElementById("submit-btn").addEventListener("click", function(event){
console.clear(); // clear out old data
inputArr.push(+inputVal.value); // the prepended + implicitly converts the string to a number
console.log(inputArr);
});
<form id="form-test">
<input type="number" id="form-val" value="1">
<button type="button" id="submit-btn">Submit</button>
</form>
You can just use indexOf. It will check if the value exist in the array.If not then it will add the element
let inputArr = [];
document.getElementById("submit-btn").onclick = function submitFormVal(event) {
event.preventDefault();
let inputVal = document.getElementById("form-val").value;
if (inputArr.indexOf(inputVal) === -1) {
inputArr.push(inputVal)
}
console.log(inputArr);
};
<form id="form-test">
<input type="number" id="form-val" value="1">
<button id="submit-btn">Submit</button>
</form>

How do I store the string value from input field in an empty array?

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>

Adding localstorage array

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>

How can I count the total number of inputs with values on a page?

I'm hoping for a super simple validation script that matches total inputs on a form to total inputs with values on a form. Can you help explain why the following doesn't work, and suggest a working solution?
Fiddle: http://jsfiddle.net/d7DDu/
Fill out one or more of the inputs and click "submit". I want to see the number of filled out inputs as the result. So far it only shows 0.
HTML:
<input type="text" name="one">
<input type="text" name="two">
<input type="text" name="three">
<textarea name="four"></textarea>
<button id="btn-submit">Submit</button>
<div id="count"></div>
JS:
$('#btn-submit').bind('click', function() {
var filledInputs = $(':input[value]').length;
$('#count').html(filledInputs);
});
[value] refers to the value attribute, which is very different to the value property.
The property is updated as you type, the attribute stays the same. This means you can do elem.value = elem.getAttribute("value") to "reset" a form element, by the way.
Personally, I'd do something like this:
var filledInputs = $(':input').filter(function() {return !!this.value;}).length;
Try this: http://jsfiddle.net/justincook/d7DDu/1/
$('#btn-submit').bind('click', function() {
var x = 0;
$(':input').each(function(){
if(this.value.length > 0){ x++; };
});
$('#count').html(x);
});

array input text get value

i want to get input text value of array in javascript
this is my code :
Item : <input id="t_item" name="t_item[]" type="text" class="teks3">
Cost : <input id="t_cost" name="t_cost[]" type="text" class="teks3">
<input type="button" id="tb_more_item" class="add_file"/>
and the js code is :
$("input#tb_more_item").click(function(){
var new_file = $("
Item : <input id='t_item' name='t_item[]' type='text' class='teks3'/>
Cost : <input id='t_cost' name='t_cost[]' type='text' class='teks3'/>
");
$("div#div_item").append(new_file).fadeIn();
});
i try to get more item value with this code :
var item_value = [], cost_value = [];
$("input#t_item").each(function() {
$thisItem = $(this);
item_value = $thisItem.val();
});
$("input#t_cost").each(function() {
$thisCost = $(this);
cost_value = $thisCost.val();
});
alert(item_value +"-"+ cost_value );
the result is get the last value value i've typed in the input text.
does anyone have the solutions?
thanks
You're creating invalid html by appending elements with duplicate ids. Update the .each() selectors to use the name attribute instead.
Also, inside the .each() functions you are overwriting the array variables with the value of the current item - that is, the array gets thrown away and replaced with the value, which is why that variable holds only the last value after the .each() finishes. What you want to do is add the value of each input as a separate element in the array:
$('input[name="t_item\\[\\]"]').each(function() {
item_value.push(this.value);
});
And similar for t_cost.

Categories

Resources