how to add the input values in an array - javascript

i just like to ask regarding adding data in a array. But the data which i wanted to put is from a table of input boxes.. Here's the code that i've been practicing to get data:
http://jsfiddle.net/yajeig/4Nr9m/69/
I have an add button that everytime I click that button, it will store data in my_data variable.
i want to produce an output in my variable something like this:
my_data = [ {plank:"1",thickness:"4",width:"6",length:"8",qty:"1",brdFt:"16"}]
and if i would add another data again, it will add in that variable and it be something like this:
my_data = [ {plank:"1",thickness:"4",width:"6",length:"8",qty:"1",brdFt:"16"},
{plank:"2",thickness:"5",width:"6",length:"2",qty:"1",brdFt:"50"}]
the code that i have right now is really bad, so please help.
Currently my output:
1,4,6,4,1

You should be able to iterate over all of the textboxes using the following:
function add(e) {
var obj = {};
$('#addItem input[type="text"]')
.each(function(){obj[this.name] = this.value;});
myItems.push(obj);
}
Where myItems is a global container for your items and #addItem is your form.
Updated jsfiddle.
If you use a form and a submit button then you should be able to implement a non-JavaScript method to add your information so that the site will be accessible to people without JavaScript enabled.

Try this, sorry for modifying your form, but it works well:
HTML:
<form method="post" action="#" id="add_plank_form">
<p><label for="plank_number">Plank number</label>
<p><input type="text" name="plank_number" id="plank_number"/></p>
<p><label for="plank_width">Width</label>
<p><input type="text" name="plank_width" id="plank_width"/></p>
<p><label for="plank_length">Length</label>
<p><input type="text" name="plank_length" id="plank_length"/></p>
<p><label for="plank_thickness">Thickness</label>
<p><input type="text" name="plank_thickness" id="plank_thickness"/></p>
<p><label for="plank_quantity">Quantity</label>
<p><input type="text" name="plank_quantity" id="plank_quantity"/></p>
<p><input type="submit" value="Add"/>
</form>
<p id="add_plank_result"></p>
Javascript:
$(document).ready(function() {
var plank_data = Array();
$('#add_plank_form').submit(function() {
// Checking data
$('#add_plank_form input[type="text"]').each(function() {
if(isNaN(parseInt($(this).val()))) {
return false;
}
});
var added_data = Array();
added_data.push(parseInt($('#plank_number').val()));
added_data.push(parseInt($('#plank_width').val()));
added_data.push(parseInt($('#plank_length').val()));
added_data.push(parseInt($('#plank_thickness').val()));
added_data.push(parseInt($('#plank_quantity').val()));
$('#add_plank_form input[type="text"]').val('');
plank_data.push(added_data);
// alert(JSON.stringify(plank_data));
// compute L x W x F for each plank data
var computed_values = Array();
$('#add_plank_result').html('');
for(var i=0; i<plank_data.length; i++) {
computed_values.push(plank_data[i][1] * plank_data[i][2] * plank_data[i][3] / 12);
$('#add_plank_result').append('<input type="text" name="plank_add[]" value="' + computed_values[i] + '"/>');
}
return false;
});
});

Iterate through all keys, and add the values.
(code written from mind, not tested)
var added = { };
for (var i = 0; i < my_data.length; i ++) {
var json = my_data[i];
for (var key in json) {
if (json.hasOwnProperty(key)) {
if (key in added) {
added[key] += json[key];
} else {
added[key] = json[key];
}
}
}
}

You can use the javascript array push function :
var data = [{plank:"1",thickness:"4",width:"6",length:"8",qty:"1",brdFt:"16"}];
var to_add = [{plank:"2",thickness:"5",width:"6",length:"2",qty:"1",brdFt:"50"}];
data = data.concat(to_add);

Sorry I only glanced at the other solutions.
$(document).ready(function() {
var myData=[];
var myObject = {}
$("input").each(function() {
myObject[this.id]=this.value
});
alert(myObject["plank"])
myData.push(myObject)
});

Related

how to store dynamically created checked checkbox in array?

I am having dynamically created checkbox...
I want that checked value from the checkbox should be stored in one array...
I am Facing the following Problems...
*
var checkedvalue=document.querySelectorAll('input[type=checkbox]:checked');
If I alert the value of checkedvalue It given undefined
If I have console.log the final variable console.log(array); It given the
["on"] in the console.log if the value is checked.
I didn't get the actual value.My code is given below. I don't know what is the mistake I did. Anyone could you please help me.
Thanks in Advance
<input type="Submit" Value="add" onclick="searchinput()">
--------------
function searchinput()
{
var li=document.createElement("li");
//creating checkbox
var label=document.createElement('label');
label.className="lab_style";
li.appendChild(label);
var check=document.createElement('input');
check.type="checkbox";
check.name="check_bo";
li.appendChild(check);
check.addEventListener('click', function() {
var array=[];
var checkedvalue=document.querySelectorAll('input[type=checkbox]:checked');
alert(checkedvalue.value);
for (var i = 0; i < checkedvalue.length; i++) {
array.push(checkedvalue[i].value);
console.log(array);
}
}, false);
}
one of the problems you are facing is that
document.querySelectorAll('input[type=checkbox]:checked');
returns a NodeList and value is not a property on an NodeList object. That is why you are seeing "undefined" in your alert.
Changing as little of your code as possible, I think this should work:
function searchinput()
{
var li=document.createElement("li");
//creating checkbox
var label=document.createElement('label');
label.className="lab_style";
li.appendChild(label);
var check=document.createElement('input');
check.type="checkbox";
check.name="check_bo";
li.appendChild(check);
check.addEventListener('click', function() {
var array=[];
var checkedvalue = document.querySelectorAll('input[type=checkbox]:checked');
for (var i = 0; i < checkedvalue.length; i++) {
if(checkedvalue[i].checked) {
array.push(checkedvalue[i].value);
}
}
}, false);
}
If you have a form with a bunch of checkboxes and once the form is submitted you want to have the values of all the checkboxes which are checked stored in an array then you can do it like this.
const checkboxes = document.querySelectorAll("input[type=checkbox]");
const form = document.querySelector("form");
const arr = [];
form.addEventListener("submit", (e) => {
e.preventDefault()
checkboxes.forEach(chbox => {
if (chbox.checked) {
arr.push(chbox.value)
}
})
console.log(arr)
})
<form>
<label>Apple:
<input type="checkbox" value="apple" name="test"></label>
<label>Mango:
<input type="checkbox" value="mango" name="test"></label>
<label>Banana:
<input type="checkbox" value="banana" name="test"></label>
<label>Grape:
<input type="checkbox" value="grape" name="test"></label>
<button type="submit">Submit</button>
</form>

Don't append if string already contains OnChange

I have a javascript OnChange function on a column having textboxes which captures the name of each row in a column. I am appending all the names and storing in variable.
Now , suppose user clicks same textbox again , I don't want to append that name again.
var AppendedString = null;
function onChangeTest(textbox) {
AppendedString = AppendedString;
AppendedString = AppendedString + ';' + textbox.name;
// this gives null;txt_2_4;txt_2_6;txt_3_4;txt_2_4 and so on..and I don't want to append same name again , here it's txt_2_4
}
My Input text :
<input type="text" name="txt_<%=l_profileid %>_<%=l_processstepsequence%>" value="<%= l_comments%>" onfocus="this.oldvalue = this.value;" onchange="onChangeTest(this);this.oldvalue = this.value;">
Those rows seem to have unique names.
you can simply check if AppendedString already contains that name :
var AppendedString=''
function onChangeTest(textbox) {
if (!AppendedString.includes(textbox.name)) {
AppendedString += ';' + textbox.name;
}
}
Codepen Link
You can’t initialize AppendedString as null otherwise, the includes() method won’t be available
otherwise, you can give each row a unique ID, and store in an array IDs that already have been clicked by the user.
var AppendedString = '';
var clickedRows = [];
function onChangeTest(textbox) {
if (!clickedRows.includes(textbox.id)) {
AppendedString += ';' + textbox.name;
clickedRows.push(textbox.id)
}
}
var arr = [];
$("input[type='text']").on("click", function() {
var nowS = ($(this).attr('name'));
if (!(arr.indexOf(nowS) > -1)) {
arr.push(nowS)
}
console.log(arr)
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="text" id="m1" name="lbl1">
<input type="text" id="m2" name="lbl2">
<input type="text" id="m3" name="lbl3">
Somewhat similar to your need,
var arr = [];
$("input[type='text']").on("click", function() {
var nowS = ($(this).attr('name'));
if (!arr.includes(nowS)) {
arr.push(nowS)
}
console.log(arr)
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="text" id="m1" name="lbl1">
<input type="text" id="m2" name="lbl2">
<input type="text" id="m3" name="lbl3">
You can add flag your textboxes and ignore if it's clicked again. Like using jquery you can do something like this:
function onChangeTest(textbox) {
AppendedString = AppendedString;
if (!textbox.hasClass("clicked")){
AppendedString = AppendedString + ';' + textbox.name;
textbox.AddClass("clicked");
}
}

Send only filled fields via GET

Look at simple form below:
<form method="GET" action="index.php">
<input type="text" name="price_min" >Min
<input type="text" name="price_max" >Max
</form>
When I send form with filled only one field, in my url I get empty values for not filled keys
(ex. index.php?price_min=).
Question:
How to remove empty keys from url?
You can parse serialized string and remove blank values. Then you can use post to necessary api using jQuery.
Sample
JSFiddle
$("#btn").on("click", function() {
var formjson = $("#frmTest").serialize();
var result = formjson.split("&").filter(function(val) {
return val.split("=")[1].length > 0;
}).join("&")
console.log("Serialized String:", formjson);
console.log("Processed String:", result);
// $.get('action.php', formjson, function(response){ ... })
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script>
<form id="frmTest">
<input type="text" name="price_min">Min
<input type="text" name="price_max">Max
</form>
<button id="btn">Test Serialize</button>
Use jQuery to send the fields like this
$('your_form').submit(function() {
var min_price = $("#min_price").val();
var max_price = $("#max_price").val();
var string = "";
if(min_price.length > 0){
string += "min_price="+min_price
}
if(max_price.length > 0){
string += "&max_price="+max_price
}
window.location.href = 'index.php?'+string;
});
Hope it helps!

HTML form passing array of options as the values to the checklist

I'd like to figure a way out using html and javascript. I have a form which will get modified each week and would like to simplify editing it.
events_in = ["event_1_date", "event_2_date", etc...]
and would display the check boxes
[] event_1_date
[] event_2_date
which you can then use the form normally.
The array input to form values will get updated weekly with new events.
There is a way using php but couldn't translate it into the languages I want to use.
Using jQuery (as you have included the jQuery tag).. First add a div to your form:
<div id="checkboxes"></div>
Then in javascript:
$(function() {
var events_in = ["event_1_date", "event_2_date"],
events_in_count = events_in.length,
i = 0;
for(;i<events_in_count;i++) {
$('#checkboxes').append('<label><input type="checkbox" name="' + events_in[i] + '">' + events_in[i] + '</label>');
}
});
You could try something like this.
var one = "text here";
var two = "text here"
var array = [["one", one],["two",two]]
window.onload = init;
function init(){
var checkListItems = document.querySelectorAll(".checklist-items");
for(var i = 0; i < checkListItems.length; i++){
updateHTML(checkListItems[i]);
}
}
function updateHTML(item){
var id = item.getAttribute("id");
alert(id)
for(var i = 0; i < array.length; i++){
if(array[i][0] == id){
item.innerHTML = array[i][1];
}
}
}
<form action="">
<input type="checkbox"><span class="checklist-items" id="one">Item</span>
<input type="checkbox"><span class="checklist-items" id="two">Item</span>
<input type="checkbox"><span class="checklist-items" id="three">Item</span>
<input type="checkbox"><span class="checklist-items" id="four">Item</span>
<input type="checkbox"><span class="checklist-items" id="five">Item</span>
</form>

how do i set a dynamic object in JS?

I want to keep a value from a form by a js function
with document.getElementById("form1")
but in the form there are dynamic inputs amount1 , amount2 ect... (i dont know how many - its from database)
how do i reach form1.amount (p)
when p is the index of the amount ?
thanks
You can retrieve it like this:
var frm = document.getElementById("form1");
if (frm) {
var valueA = frm["amount" + 1].value;
}
A more complete example:
<html>
<form id="f1">
<input name="input1" value="text" type="text" />
</form>
<script>
var f = document.getElementById("f1");
if(f)
{
alert(f["input"+1]);
alert(f["input"+1].value);
}
</script>
</html>
You can get all input elements of a form by use of "getElementsByTagName". Like this:
var form = document.getElementById("form1");
var inputs = form.getElementsByTagName("input");
That way the array "inputs" contains all input elements contained in your form.
Ioannis is pretty much there. To get the value of the ith amount input, use:
var value = document.forms['form1'].elements['amount' + i].value;
A little more robustly:
function getIthAmount(i) {
var o = document.forms['form1'];
o = o && o.elements['amount' + i];
if (o) {
return o.value;
}
}

Categories