Adding select menu default value via JS? - javascript

i'm developing a meta search engine website, Soogle and i've used JS to populate select menu..
Now, after the page is loaded none of engines is loaded by default, user needs to select it on his own or [TAB] to it..
Is there a possibility to preselect one value from the menu via JS after the page loads?
This is the code:
Javascript:
// SEARCH FORM INIT
function addOptions(){
var sel=document.searchForm.whichEngine;
for(var i=0,l=arr.length;i<l;i++){
sel.options[i]=new Option(arr[i][0], i);
}
}
function startSearch(){
var searchString=document.searchForm.searchText.value;
if(searchString.replace(/\s+/g,"").length > 0){
var searchEngine=document.searchForm.whichEngine.selectedIndex,
finalSearchString=arr[searchEngine][1]+searchString;
window.location=finalSearchString;
}
return false;
}
function checkKey(e){
var key = e.which ? e.which : event.keyCode;
if(key === 13){
return startSearch();
}
}
// SEARCH ENGINES INIT
var arr = [
["Web", "http://www.google.com/search?q="],
["Images", "http://images.google.com/images?q="],
["Knowledge","http://en.wikipedia.org/wiki/Special:Search?search="],
["Videos","http://www.youtube.com/results?search_query="],
["Movies", "http://www.imdb.com/find?q="],
["Torrents", "http://thepiratebay.org/search/"]
];
HTML:
<body onload="addOptions();document.forms.searchForm.searchText.focus()">
<div id="wrapper">
<div id="logo"></div>
<form name="searchForm" method="POST" action="javascript:void(0)">
<input name="searchText" type="text" onkeypress="checkKey(event);"/>
<span id="color"></span>
<select tabindex="1" name="whichEngine" selected="Web"></select>
<br />
<input tabindex="2" type="button" onClick="return startSearch()" value="Search"/>
</form>
</div>
</body>

I appreciate that your question asks for a solution that utilises JavaScript, but having looked at the webpage in question I feel confident in making this point:
Your problem is that you are trying to use JavaScript for something that HTML itself was designed to solve:
<select name="whichEngine">
<option value="http://www.google.com/search?q=" selected="selected">Web</option>
<option value="http://images.google.com/images?q=">Images</option>
<option value="http://en.wikipedia.org/wiki/Special:Search?search=">Knowledge</option>
<option value="http://www.youtube.com/results?search_query=">Videos</option>
<option value="http://www.imdb.com/find?q=">Movies</option>
<option value="http://thepiratebay.org/search/">Torrents</option>
</select>
Fear not, though! You can still access all of the options from JavaScript in the same way that you did before.
function alertSelectedEngine() {
var e = document.getElementsByName("whichEngine")[0];
alert("The user has selected: "+e.options[e.selectedIndex].text+" ("+e.options[e.selectedIndex].value+")");
}
Please, forgive and listen to me.

I have modified the code to use jQuery. It is working fine in IE8, IE8 (Compatibility mode) and in FireFox.
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" >
<head id="Head1" runat="server">
<title>Index</title>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"></script>
<script type="text/javascript">
// SEARCH ENGINES INIT
var arr = new Array();
arr[arr.length] = new Array("Web", "http://www.google.com/search?q=");
arr[arr.length] = new Array("Images", "http://images.google.com/images?q=");
arr[arr.length] = new Array("Knoweledge", "http://en.wikipedia.org/wiki/Special:Search?search=");
arr[arr.length] = new Array("Videos", "http://www.youtube.com/results?search_query=");
arr[arr.length] = new Array("Movies", "http://www.imdb.com/find?q=");
arr[arr.length] = new Array("Torrents", "http://thepiratebay.org/search/");
// SEARCH FORM INIT
function addOptions() {
// Add the options to the select dropdown.
var nOptions = arr.length;
var optionText = '';
for (var i = 0; i < nOptions; i++) {
optionText += '<option value="' + i + '">' + arr[i][0] + '</option>'
}
//alert('optionText = ' + optionText);
// Add the options to the select drop down.
$('select#whichEngine').html(optionText);
// set the second option as default. This can be changed, if required.
$('select#whichEngine option:eq(1)').attr('selected', true);
}
function startSearch() {
var searchEngineIndex = $('select#whichEngine option:selected').attr('value');
searchEngineIndex = parseInt(searchEngineIndex, 10);
var searchString = $('input#searchText').val();
if (searchEngineIndex >= 0 && searchString) {
var searchURL = arr[searchEngineIndex][1] + searchString;
//alert('location = ' + searchURL);
window.location.href = searchURL;
}
return false;
}
function checkKey(e) {
var character = (e.which) ? e.which : event.keyCode;
if (character == '13') {
return startSearch();
}
}
$(function() {
// Add the options to the select drop down.
addOptions();
// Add focus to the search text box.
$('input#searchText').focus();
// Hook the click event handler to the search button.
$('input[type=button]').click(startSearch);
$('input#searchText').keyup(checkKey);
});
</script>
</head>
<body>
<div id="wrapper">
<div id="logo"></div>
<form name="searchForm" method="POST" action="javascript:void(0)">
<input id="searchText" name="searchText" type="text"/>
<span id="color"></span>
<select tabindex="1" id="whichEngine" name="whichEngine"></select>
<br />
<input tabindex="2" type="button"value="Search"/>
</form>
</div>
</body>
</html>

You had some errors in how you handle the <select> values and options. I would reorganize your JavaScript like this:
// SEARCH ENGINES
var arr = [["Web", "http://www.google.com/search?q="],
["Images", "http://images.google.com/images?q="],
["Knowledge", "http://en.wikipedia.org/wiki/Special:Search?search="],
["Videos", "http://www.youtube.com/results?search_query="],
["Movies", "http://www.imdb.com/find?q="],
["Torrents", "http://thepiratebay.org/search/"]];
// SEARCH FORM INIT
function addOptions(){
var sel=document.searchForm.whichEngine;
for(var i=0;i<arr.length;i++) {
sel.options[i]=new Option(arr[i][0],arr[i][1]);
}
}
function startSearch(){
var searchString = document.searchForm.searchText.value;
if(searchString!==''){
var mySel = document.searchForm.whichEngine;
var finalLocation = mySel.options[mySel.selectedIndex].value;
finalLocation += encodeURIComponent(searchString);
location.href = finalLocation;
}
return false;
}
function checkKey(e){
var character=(e.which) ? e.which : event.keyCode;
return (character=='13') ? startSearch() : null;
}
I would also move your onload handler into the main body of your JavaScript:
window.onload = function() {
addOptions();
document.searchForm.searchText.focus();
};
I also made some changes to your HTML:
<body>
<div id="wrapper">
<div id="logo"></div>
<form name="searchForm" method="POST" action="." onsubmit="return false;">
<input name="searchText" type="text" onkeypress="checkKey(event);" />
<span id="color"></span>
<select tabindex="1" name="whichEngine" selected="Web"></select><br />
<input tabindex="2" type="button" value="Search"
onclick="startSearch();" />
</form>
</div>
</body>

You could specify which egine you would like preselected in the engines array like this:
// SEARCH ENGINES INIT
// I've used array literals for brevity
var arr = [
["Web", "http://www.google.com/search?q="],
["Images", "http://images.google.com/images?q="],
["Knoweledge", "http://en.wikipedia.org/wiki/Special:Search?search="],
/*
* notice that this next line has an extra element which is set to true
* this is my default
*/
["Videos", "http://www.youtube.com/results?search_query=", true],
["Movies", "http://www.imdb.com/find?q="],
["Torrents", "http://thepiratebay.org/search/"]
];
Then in your setup function:
// SEARCH FORM INIT
function addOptions() {
var sel = document.searchForm.whichEngine;
for (var i = 0; i < arr.length; i++) {
// notice the extra third argument to the Option constructor
sel.options[i] = new Option( arr[i][0], i, arr[i][2] );
}
}

if your only concern is preselecting an engine onload, don't "over-engineer" it.
var Web = "http://www.google.com/search?q=";
var Images = "http://images.google.com/images?q=";
var Knowledge = "http://en.wikipedia.org/wiki/Special:Search?search=";
var Videos = "http://www.youtube.com/results?search_query=";
var Movies = "http://www.imdb.com/find?q=";
var Torrents = "http://thepiratebay.org/search/";
function addOptions(source){
var sel=document.searchForm.whichEngine;
for(var i=0,l=arr.length;i<l;i++){
sel.options[i]=new Option(arr[i][0], i);
}
}
then insert your argument made onto your body tag to a pre-defined variable. If you want something random, create a new function with your equation for selecting a random variable then load your addOptions(function) within your new function. Then remove addOptions from your body tag.
<body onload="addOptions(Web);document.forms.searchForm.searchText.focus()">

Related

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

get value from HTML form with Javascript and then display them on html

This is my first post ever! So I am currently studying front end web development online. I have come across a problem! I am trying to get input from a user HTML form and display those values back on the HTML document. When I do it using javascript work but when using the form it dont.
see my code in codepen : http://codepen.io/kevin1616/pen/KdOvwy
My html
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>Contact List</title>
</head>
<body>
<header>
<h1> ContactBook.com </h1>
</header>
<section id="body">
<form method="post">
<input type="text" id="name" ><br>
<input type="text" id="last" ><br>
<input type="text" id="phone" ><br>
<input type="text" id="address" ><br>
<input type="submit" id="create_new_contact" >
</form>
<ol id="people">
</ol>
</section>
<script src="js.js"></script>
</body>
</html>
my javascript
// JavaScript Document
// CONTACTS CONTRUCTOR OBJECT
var contacts = function ( ) {
this.name = [];
this.lastName= [];
this.phoneNumber = [];
this.address= [];
};
contacts.prototype.add = function(name, last, number, address) {// Add method to add contacts
this.name.push(name);
this.lastName.push(last);
this.phoneNumber.push(number);
this.address.push(address);
}
contacts.prototype.toHTML = function (i) {// toHTML method formats how html will be displayed
var htmlString ="<li>";
htmlString +="<p>" + this.name[i] + "<p>";
htmlString +="<p>" + this.lastName[i] + "<p>";
htmlString +="<p>" + this.phoneNumber[i] + "<p>";
htmlString +="<p>" + this.address[i]+ "<p>";
htmlString +="</li>";
return htmlString;
};
contacts.prototype.renderElement = function (list) {// method for sending input to html
for ( var i=0; i < this.name.length; i++) {
list.innerHTML+= this.toHTML(i);
}
};
var addingContact = new contacts();// creating new instance of contructor
addingContact.add("Kevin", "Silvestre" ,"781 582 4449", "26 endicott st");// using the add method to add contacts to my list
var itemsTorender = document.getElementById("people");// select where in the html the elemtents will be rendered
addingContact.renderElement(itemsTorender);// render elements to html
You Just Need A function which call during submit form to get form data that time and show it in list
function saveData(){
var name = document.getElementById("name").value;
var last = document.getElementById("last").value;
var phone = document.getElementById("phone").value;
var address = document.getElementById("address").value;
addingContact.add(name,last ,phone, address);// using
var itemsTorender = document.getElementById("people");// select where in the html
addingContact.renderElement(itemsTorender);// render elements to html
return false; // this will stop default submit of form (because by default form submit on "action" url if no action is define than on same page )
}
and you need to call it like
<form method="post" action="#" onsubmit="return saveData()">
Fiddle

Post input value into table

I'm trying to get the text from a input textfield and place the value in a table row, but each time someone posts something the oldest post moves down 1 row, here's what I have but I'm very confused now
<HTML>
<HEAD>
<SCRIPT Language="JavaScript">
<!--//
function thisPost(frm){
if (frm.postHere.value == "")
alert("Hey! You didn't enter anything!")
else
frm.postHere.value = ""
<table style="width:100%">
<tr>
<td>post + frm.postHere.value</th>
</tr>
</table>
}
//-->
</SCRIPT>
</HEAD>
<BODY>
<FORM NAME="thisPost">
<P>Post this: <INPUT TYPE="TEXT" NAME="postHere"><BR><BR>
<INPUT TYPE="Button" Value="Post" onClick="thisPost(this.form)">
</P>
</FORM>
</BODY>
</HTML>
Demo on Fiddle
HTML:
<label>Post this:</label>
<input type="text" name="postHere" />
<br />
<br />
<button>Post</button>
<table></table>
JavaScript:
var btn = document.getElementsByTagName("button")[0];
var inpt = document.getElementsByName("postHere")[0];
var cnt = 0;
btn.onclick = function() {
if (!inpt.value) alert("Hey! You didn't enter anything!");
else alert("The field contains the text: " + inpt.value);
var tbl = document.getElementsByTagName("table")[0];
var row = tbl.insertRow(cnt++);
var cell = row.insertCell(0);
var txt = document.createTextNode(inpt.value);
cell.appendChild(txt);
};
There's a number of syntax errors in your code, so I'm not sure how you are able to run it in its current state. Also, your markup and approach is fairly dated. I would highly recommend investing time in a cross-browser DOM framework like jQuery and then an good front-end MVW and templating framework. That aside, I've re-worked your code into a more usable form. Hopefully this will get you going.
function thisPost(){
//Use getElementById to retrieve the DOM elements you're looking for
var txtPost = document.getElementById('txtPost');
var post = txtPost.value;
if (post == "") {
alert("Hey! You didn't enter anything!")
} else {
alert("The field contains the text: " + post);
//Get a reference to your table
var table = document.getElementById('posts');
//TODO: This is unsafe and subject to script injection.
//http://en.wikipedia.org/wiki/Code_injection#HTML_Script_Injection
table.innerHTML = '<tr><td>' + post + '</td></tr>' + table.innerHTML;
txtPost.value = "";
}
}
//from: http://stackoverflow.com/a/10150042/402706
// add event cross browser
function addEvent(elem, event, fn) {
if (elem.addEventListener) {
elem.addEventListener(event, fn, false);
} else {
elem.attachEvent("on" + event, function() {
// set the this pointer same as addEventListener when fn is called
return(fn.call(elem, window.event));
});
}
}
//Don't bind events in your HTML markup, instead bind them in JavaScript.
addEvent(document.getElementById('btnPost'), 'click', thisPost);
table{
width:100%;
}
<form name="thisPost">
<p>
Post this: <input type="Text" name="postHere" id='txtPost'>
<br/><br/>
<input type="Button" value="Post" id='btnPost'/>
</p>
<table id='posts'>
</table>
</form>

jQuery or Javascript to parse querystring on submit

This form has multiple choices through a checkbox. Eg. Pet You Own is a multiple choice and there are various options such as Cat, Dog, Mule etc.
Now by default, the querystring sent will look like:
?pet=dog&pet=cat&pet=mule
given all 3 are checked.
I need a way to parse this so that the querystring looks like:
?pet=dog,cat,mule
Another requirement is that, there are other parameters/inputs in the form so it needs to work in conjunction with other standard form inputs.
The format you're currently seeing is the conventional format. If your form fields were named pet[] rather than pet, your server would be able to interpret the result as an array.
Having said that, to actually do what you're requesting, you could reset the name attribute of your checkboxes, so that they won't be posted, and instead post a hidden field that holds the value of your checkboxes as a comma separated string:
$('#my-form').submit(function() {
var pets = [];
$('input[name=pet]:checked').each(function() {
pets.push($(this).val());
});
// stop checkboxes from being posted
$('input[name=pet]').attr('name','');
// have an input field be posted instead
$('#my-hidden-field')
.val(pets.join(','))
.attr('name', 'pet');
});
A bit of cleaning is needed but using this with plain JS you can acheive
<html>
<head>
<title>My Page</title>
<script>
function myFunction(){
var options = "";
if(document.getElementById("option1").checked){
options = options+"Milk";
}
if(document.getElementById("option2").checked){
options = options+",Butter";
}
if(document.getElementById("option3").checked){
options = options+",Cheese";
window.location = "end.html&options="+options
}
}
</script>
</head>
<body>
<div align="center"><br>
<input id="option1" type="checkbox" name="option1" value="Milk"> Milk<br>
<input id="option2" type="checkbox" name="option2" value="Butter" checked> Butter<br>
<input id="option3" type="checkbox" name="option3" value="Cheese"> Cheese<br>
<br>
</div>
Button to submit
</body>
</html>
I suggest you to do this job on server side. When your server receive this request, it will get an array which is called pet and has three element: dog,cat and mule. you can conjunction them easily.
====
I implement this with JavaScript:
var str = window.location.href;
var queryString = "", temp = {};
str = str.substring(str.lastIndexOf("?") + 1);
str.split("&").some(function(item) {
var tarr = item.split("=");
if(typeof temp[tarr[0]] == "undefined") {
temp[tarr[0]] = tarr[1];
} else if(typeof temp[tarr[0]] == "string") {
temp[tarr[0]] += "," + tarr[1];
}
});
// Make queryString
for(var i in temp) {
queryString += "&" + i + "=" + temp[i];
}
queryString = queryString.replace(/^./,"");
//
var href = window.location.href;
console.log("before:", href);
href = href.replace(/\?.*$/, "?");
// the url is that you want
console.log("after:", href + queryString);
//window.location.href = href + queryString;
OUTPUT:
before:
http://www.boutell.com/newfaq/creating/forcedownload.html?pet=dog&pet=cat&pet=mule&animal=camel
after:
http://www.boutell.com/newfaq/creating/forcedownload.html?pet=dog,cat,mule&animal=camel
Name your check boxes as p1, p2 etc. Have a hidden field in your form named 'pet'. Just before submit using JS, set the value of your hidden variable the way you need and return true.
function beforeSubmit() {
var p = '';
if($('#p1').attr('checked')==true) p += ',cat';
if($('#p2').attr('checked')==true) p += ',dog';
...
p = p.substring(1); // strip the , at 0
$('#pet').val(p);
return true;
}
and your form should be like:
<form ... onsubmit="return beforeSubmit()">
...
<input type="checkbox" name="p1" id="p1">Cat<br>
<input type="checkbox" name="p2" id="p2">Dog<br>
...
<input type="hidden" name="pet" id="pet" value="">
</form>

how to add the input values in an array

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

Categories