Get all form values into javascript array - javascript

I am attempting to get all the form values into a normal array[]. I had it working for tags but then I added some tags and can't seem to get it.
With just tags it worked with this
var content = document.querySelectorAll("#form input[name='content[]']");
I am currently trying something like this
var content = document.elements["content[]"].value;
This form can change from user input down the road as each section of the form is a module that they choose to add. It is also important to get the values in order, if that isn't possible then I would need to make it a JSON array. Pure javascript or jquery is fine either way.
Thank you for any help.
EDIT
I used this to solve my problem
var contents=[]
var content = $('#form').serializeArray()
for (var i = 0; i < content.length; i++) {
contents[contents.length]=content[i].value
};

Try
html
<form id="form">
<input type="text" name="content[]" value="abc" />
<textarea name="textarea" value="">123</textarea>
</form>
js
$(function() {
var form = $("#form");
// escape `[]`
var content = form.find("input[name=content\\[\\]]");
// array `literal declaration`
var _arr = [content.prop("value")];
// map all form values to single array
var arr = $.map(form.serializeArray(), function(v, k) {
return [v.value]
});
// array literal with `textarea` `value`
var t = [$("textarea").prop("value")];
console.log(_arr, arr, t);
// _arr: `["abc"]` , arr:`["abc", "123"]` t:`["123"]`
})
Demo.
See Arrays

Related

How to put Parameter only with Javascript through URL in the website

I am using the software rimacon.
And i am using this URL: http://www.jabra.com.de/Support/warranty-checker
I want to send the Value of the serial number from Javascript (rimacon) into this input of this website: (see picture)
In this website, i click the mouse on the right and click "inspect Element/ Element Untersuchen". I get this HTML-Code:
<input type="text" class="serial-number">
i would like to change this into:
<input type="text" class="serial-number" value="xXx">
then i write URL like:
http://www.jabra.com.de/Support/warranty-checker/?xXx="0QYG06DF3FA"
or i would like to change this CODE into:
<input type="text" class="serial-number" name="PUT-Serial-number">
then i write URL like:
http://www.jabra.com.de/Support/warranty-checker/?PUT-Serial-number="0QYG06DF3FA"
i tried some Code with setAttribute or createAttribute and so on to get this fixed:
for example:
//var x = document.getElementsByClassName("serial-number").href="http://www.jabra.com.de/Support/warranty-checker";
var x = document.querySelectorAll("input.serial-number[href^='http://www.jabra.com.de/Support/warranty-checker']");
var y = x.innerHTML = "value="+seriennummer;
alert("y: "+y);
alert("Länge : "+y.length);
//var attr = document.createAttribute("Value");
//attr.value=seriennummer;
//var attr = x.setAttribute("Value",seriennummer);
//alert("attr: "+attr.value);
// this shall open window and show the serialnumber in this websites
url = escape("http://www.jabra.com.de/Support/warranty-checker");
var hpwindow = window.open("http://xxx:8081/sprungxbrett.php?TARGET="+url);
hpwindow.focus();
This Code is in function of onclick().
Please I need your Help! Is there some way to get fixed this JS-Code!
Because in "Inspect element/Element Untersuchen", you can add Attribute Value into this
<input type="text" class="serial-number" value="0QYG06DF3FA">
then this serial number truly display in the input this website.
Thank you very much.
this should solve getting the URL params as JSON format (wont show anything here, try any test file with url params, ex: test.html?this=that&that=this)
<p id="result"> result: </p>
<script>
function getUrlVars() {
var map = {};
var parts = window.location.href.replace(/[?&]+([^=&]+)=([^&]*)/gi, function(m,key,value) {
map[key] = value;
});
//get your values as JSON, one of the following
console.log(map);
document.getElementById("result").innerHTML += JSON.stringify(map);
return map;
}
getUrlVars()
</script>

javascript/jquery mutate and append html in var

I got a simple array like this:
var arr = ['string_1', 'string_2'];
And I got the following html (simplified, but original is very large):
var html = '<div><input class="myInput" type="text"></div>'
I need to append to #main_div in my DOM this html variable, but filled with values from arr, so in this case there should be 2 inputs, filled with string_1 and string_2.
I tried the following code:
$.each(arr, function(k, v){
$(html).find('.myInput').val(v);
$('#main_div').append(html);//mutated html var should be here
});
but I get 2 empty inputs. Any ideas how to fix it would be welcome. Thank you
Your logic is almost there, but the problem is that you're not storing the jQuery object that you create from the html string, so you just append the unchanged original value. Try this:
var arr = ['string_1', 'string_2'];
var html = '<div><input class="myInput" type="text"></div>'
$.each(arr, function(i, v) {
var $html = $(html).find('.myInput').val(v).end();
$('#main_div').append($html);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="main_div"></div>
Note the use of end() which returns the originally selected element (the outer div from the html string in this case) instead of the .myInput element resulting from the find() call.
Finally, you need to give the input elements name attributes to ensure they are still valid HTML.

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>

Novice/Beginner Javascript Request

HTML code:
<td>
<img src="../images/items/333.png"><br>
<b>Product One</b><br>
(2 in stock)<br>
<i>65 USD</i><br>
<form action="shopping.php?shop=1&item=333&price=65&buy=conf&type=" method="post">
<input name="" value="Buy this item" type="submit">
</form></td>
<td>
<img src="../images/items/444.png"><br>
<b>Product Two</b><br>
(4 in stock)<br>
<i>5 USD</i><br>
<form action="shopping.php?shop=1&item=444&price=5&buy=conf&type=" method="post">
<input name="" value="Buy" type="submit">
</form></td>
This is the html code on the page I'm working on, the html code cannot be altered.
There are several td tags on the page which contains the following information you see in the code above.
I would like to write a script that would do something like this:
if (document.body.innerHTML.indexOf("Product One") > -1) {
document.location = "shopping.php?shop=1&item="+itemID+"&price="+USD+"&buy=conf&type="
}
Search the body/td of the page for the "Product Name" specified in my script, and then if it's found, go to the url that contains variables that need to be extracted, itemID and USD.
itemID is extracted from the src of the image.png by taking the numbers. For example, the itemID of ../images/items/444.png is 444.
USD is extracted from the price defined between the italics tags. For example the extracted value for USD for<i>5 USD</i> would be 5.
Catch is
I would need a lot of if (document.body.innerHTML.indexOf("Name") > -1) {document.location = "shopping.php?shop=1&item="+itemID+"&price="+USD+"&buy=conf&type="} to cater to the large number of products I would specify. I might want to specify "Product One to Hundred" and "Sub-product A to Z"
Solution
Some ways I thought of to handle this (needs to be put into javascript code) is to:
Put list of products I will specify into an array (something like) var list = new Array ("Product One","Product Two","Sub-Product A"); and have a function check the page for the presence of any product from this array that displays on the page.
When the product is found, to get the itemID, isolate the numbers before .png and after /items/ from the image src of the product. And to get USD, get the value between the <i> </i> tags and only take the numerical values
To do this I think nextSibling or previousSibing can be used, but I'm not too sure about that.
Alternatively, to make it easier, there could be a function to immediately locate the form's action value and set the window.location since <form action="shopping.php?shop=1&item=444&price=5&buy=conf&type=" method="post">
I've seen this done before using XPath?
This is not difficult using jQuery -- especially if we extend it to search for case-insensitive, regular expressions.
The following script should work with the HTML structure from the question, if it is precisely accurate and not added by AJAX. Note the power that regular expressions give when targeting product descriptions.
You can see the underlying code at work at jsFiddle.
// ==UserScript==
// #name _Auto-follow targeted product links.
// #include http://YOUR_SERVER.COM/YOUR_PATH/*
// #require http://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js
// ==/UserScript==
var targetList = [
"Shoes, pumps",
"Horse shoes",
"(?:Red|Pink|Burgundy)\\s+shoes?"
];
/*--- Extend jQuery with a case-insensitive version of contains().
Also allows regular expressions.
*/
jQuery.extend (
jQuery.expr[':'].containsCI = function (a, i, m) {
//--- The next is faster than jQuery(a).text()...
var sText = (a.textContent || a.innerText || "");
var zRegExp = new RegExp (m[3], 'i');
return zRegExp.test (sText);
}
);
$.each (targetList, function (index, value) {
var jqSelector = 'td > b:containsCI("' + value + '")';
var productFound = $(jqSelector);
if (productFound.length) {
var matchingForm = productFound.first ().nextAll ("form");
if (matchingForm.length) {
alert (productFound.text () );
document.location = matchingForm.attr ("action");
}
}
} );
Here is a solution that does not rely on external libraries like jQuery:
function findProducts(referenceList) {
var productsOnPage = {}, listMatches = {},
tds = document.getElementsByTagName("TD"),
bold, form, i, productName, productUrl;
// build an index of products on the page (HTML scraping)
for (i = 0; i < tds.length; i++) {
bold = tds[i].getElementsByTagName("B")[0];
form = tds[i].getElementsByTagName("FORM")[0];
if (bold && form) {
productName = bold.innerHTML.toLowerCase();
productUrl = form.action;
productsOnPage[productName] = productUrl;
}
}
// match reference list against all available products on the page
for (i = 0; i < referenceList.length; i++) {
productName = referenceList[i].toLowerCase();
productUrl = productsOnPage[productName];
listMatches[productName] = productUrl;
}
return listMatches;
}
Call it:
var availableProducts = findProducts(["Product One","Product Two","Sub-Product A"]);
After that you'd have an object availableProducts that's looking like this:
{
"product one": "shopping.php?shop=1&item=333&price=65&buy=conf&type=",
"product two": "shopping.php?shop=1&item=444&price=5&buy=conf&type=",
"sub-product a": undefined
}
Note that all keys are lower case to make string comparisons consistent. To look up a product you would use
function navigateIfAvailable(productName) {
var url = availableProducts[productName.toLowerCase()];
if (url) document.location = url;
}
Now
navigateIfAvailable("Product Two");
would go somewhere. Or not.

Dynamically loaded form won't update correctly

I have a form which is loaded into the page using .load(). I want to update the form with the HTML I compute in str, but my code isn't updating the form correctly. Why?
if($(this).is('.step3')){
//Splits the comma seperated values into input fields
var active_fields = ($('#templateFields').val()).split(',');
$('#loadedcontent').load('template.html #step3',function(){
$('#steps').text('Step Three');
$('#start.btn').text('Save Template & Values').removeClass('step3').addClass('step4');
});
str = "";
for(var i = 0; i<active_fields.length; i++){
str += '<label>'+active_fields[i]+'</label><input name="'+active_fields[i]+'" type="text" class="span3">';
}
$('form#values.well').html(str);
}
You have to put the form modification in the load completion function like this:
if($(this).is('.step3')){
//Splits the comma seperated values into input fields
var active_fields = ($('#templateFields').val()).split(',');
$('#loadedcontent').load('template.html #step3',function(){
$('#steps').text('Step Three');
$('#start.btn').text('Save Template & Values').removeClass('step3').addClass('step4');
str = "";
for(var i = 0; i<active_fields.length; i++){
str += '<label>'+active_fields[i]+'</label><input name="'+active_fields[i]+'" type="text" class="span3">';
}
$('form#values.well').html(str);
});
}
The way you were doing it, your code to modify the form was running before the form finished loading so it wouldn't find the content and thus couldn't modify it.
Sorry, I figured i couldnt nest a form within a form. I think thats why it didnt work

Categories

Resources