URL building with array parameters - javascript

I created a URL using jQuery serialize() and it creates something like this:
client_number=4&start_date&client_number=5
the problem is that I would like to have an url with arrays like this:
client_number[]=4&start_date&client_number[]=5

The [name] of the input elements that are being serialized must contain [] to produce those PHP compatible query strings.
$(function () {
$('form').on('submit', function (e) {
$('pre').text($(this).serialize());
e.preventDefault();
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form>
<input type="text" name="example1">
<input type="text" name="example1">
<input type="text" name="example2[]">
<input type="text" name="example2[]">
<input type="submit" value="Serialize">
</form>
<pre></pre>
Note: the keys will appear with %5B%5D instead of []. This is expected and OK because that is the proper URL encoding for [].

If I understand your question, you want to append [] to the duplicate query string items.
A JavaScript solution would be to use .serializeArray() on the form, mark the key/value pairs which are duplicates, add [] to the the name properties of the duplicates, and then convert the object back to a query string using $.param().
function serializeWithDuplicates(form) {
var pairs = $(form).serializeArray();
for (i = 0; i < pairs.length; i++)
for (j = i + 1; j < pairs.length; j++)
if (pairs[i].name === pairs[j].name)
pairs[i].isDuplicate = pairs[j].isDuplicate = true;
for (i = 0; i < pairs.length; i++)
if (pairs[i].isDuplicate)
pairs[i].name += "[]";
return $.param(pairs);
}
JSFiddle

Related

How to get a list of html input values parsed to integers from a for loop?

I am new to JavaScript & writing a program that takes a collection of HTML
input values and returning the sum.
I want to convert the data-type of the value from string to integer with a for loop, but am having issues.
for (i = 0; i < allInp.length; ++i) {
var integer = [parseInt(allInp[i].value, 10)];
console.log(integer[i]);
}
// should return something like "3, 4, 5"
I expect the values of allInp to be returned as integers but returns them as strings.
Create the array outside the loop and use push():
let allInp = document.querySelectorAll("input");
var arr = [];
for (i = 0; i < allInp.length; ++i) {
arr.push(parseInt(allInp[i].value, 10));
}
console.log(arr);
<input type="text" value="2" />
<input type="text" value="1" />
<input type="text" value="7" />

Take input value from form with loop and create array

I have problem with JavaScript function. How can I take the value from the form inputs with loop ?
I try something like
var values =[];
for (var h=1; h<=arrange;++h){
values[h]=parseFloat($('#inputr2"+h+"').val());
}
How can I add h in the id , as inputr20 (if h=0) ,inputr21 (h=1) ,anyone can help ?
try
var values =[];
for (var h=1; h<=arrange;++h){
values[h]=parseFloat($(String("#inputr2"+h)).val());
}
Array's index are 0 based. You have to assign the value to the index h-1. You do not need to decrease that, if you start the loop from 0. Also the string id you are generating is not properly formatted. You can try the following way:
var values =[];
var arrange = 2
for (var h=0; h<arrange;h++){
values[h]=parseFloat($("#inputr2"+h).val());
//Or you can simply use push() which does not require index.
//values.push(parseFloat($("#inputr2"+h).val()));
}
console.log(values)
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input id="inputr20" value="11.11"/>
<input id="inputr21" value="22.22"/>
If you want get all the input values having id Starts With, you can use map() and get() like the following way:
var values = $('[id^=inputr2]').map((i, el) => parseFloat($(el).val())).get();
console.log(values)
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input id="inputr21" value="11.11"/>
<input id="inputr22" value="22.22"/>

Accessing an element using id (JavaScript)

Scenario: I have a form element with id = "shipping_address"
Will all of the following work:
var i = document.shipping_address;
var i = window.shipping_address;
var i = shipping_address;
var i = document.forms.shipping_address;
var i = windows.forms.shipping_address;
var i = forms.shipping_address:
Thank you in advance!
Here is a running example:
var i = document.shipping_address;
console.log(i);
var i = window.shipping_address;
console.log(i);
var i = shipping_address;
console.log(i);
var i = document.forms.shipping_address;
console.log(i);
var i = windows.forms.shipping_address;
console.log(i);
var i = forms.shipping_address;
console.log(i);
<form id="shipping_address">
<input type='text'/>
</form>
Also I created a JSFiddle to help you.
https://jsfiddle.net/hszknwn9/1/
please notice you have what I think is a typo in the last line:var i =
forms.shipping_address:
the : should be a ;
I corrrected it in jsFiddle
You can try all of them on Codepen.io, but I would use only:
var i = document.getElementById("shipping_address");
And then access all the properties listed here according to what you need.
Those will not work.
If you are trying to assign the reference of your element with id="shipping_address", the correct way would be:
var i = document.getElementById("shipping_address");
To access the individual fields (and their respective contents) of that element, you need to first access the array of elements in your <form> element, and then iterate through:
var fields = i.elements;
var responses = [];
for(var j = 0; j < fields.length; j++) {
//perform actions on or with fields[j],
// such as responses.push(fields[j].value);
// which would put the value of each field
// of the form into the responses array.
}
The <form> element is a special container for grouping individual <input> elements, each of which should specify its input type. For example,
<form id="shipping_address">
<input type="text" placeholder="Street Address/P.O. box"></input>
<input type="text" placeholder="Town/City Name"></input>
<input type="text" placeholder="State/Country Name"></input>
<input type="text" placeholder="Zip Code (if applicable)"></input>
</form>
Which would create 4 input simple text fields from which inputs could be gathered. Putting all of this together, we can create a function that returns an array containing all of the values of the input fields in your shipping_address form element:
function getAddress() {
var i = document.getElementById("shipping_address");
var fields = i.elements;
var responses = [];
for(var j = 0; j < fields.length; j++) {
responses.push(fields[j].value);
return responses;
}
And from there on you can handle that data however you wish.
There are many more input types, I suggest you read the reference documentation at the w3schools html form reference, which provides acceptable documentation for most of the elements.
Hope this helps!
Use this to get value of a element by referencing ID of the element:
document.getElementById('shipping_address').value;

How to get url data in html textbox

i have a simple code of javascript which displays text from url.
example: index.html?id=001
then its output displays in html page as 001. but i want that data (id=001) into html text box which display only "001" into textbox.
here is my code.
<script type="text/javascript">
function GET() {
var data = [];
for(x = 0; x < arguments.length; ++x)
data.push(location.href.match(new RegExp("/\?".concat(arguments[x],"=","([^\n&]*)")))[1])
return data;
}
</script>
<br />
<script type="text/javascript"> document.write(GET("id")[0]); </script>
<br /><br />
<input type="text" id="" value="" name="" />
Actually i want that "001" into textbox as a textbox value.
Put the script after the input then just set its value:
<input type="text" id="myInput" value="" name="" />
<script type="text/javascript">
function GET() {
var data = [];
for(x = 0; x < arguments.length; ++x)
data.push(location.href.match(new RegExp("(/\?id=)([^\&]*)"))[2]);
return data;
}
document.getElementById('myInput').value = (GET("id")[0]);
</script>
Regular expressions are probably overkill for this, and your expression will only find the querystring value if it immediately follows the ?.
You should use location.search rather than the full URL, because then you just need to take everything after the first character (which will be ? if there is anything), and it will eliminate hashes.
I used simple string splitting to create a reusable map of key/value pairs for lookup.
function GET() {
var data = [];
for (var i = 0; i < arguments.length; i++) {
data.push(getQueryMap()[arguments[i]]);
}
return data;
}
var queryMap = null;
function getQueryMap() {
if (queryMap) { return queryMap; }
queryMap = {};
var querySplit = location.search.substring(1).split('&');
for (var i = 0; i < querySplit.length; i++) {
var thisQuery = querySplit[i].split('=', 2);
queryMap[thisQuery[0]] = thisQuery[1];
}
return queryMap;
}
To use the input and get the value into it, you need an ID on it or another way to identify it:
<input type="text" id="someInput" value="" name="" />
Then, after it, put a script like so:
<script type="text/javascript">
document.getElementById('someInput').value = GET('id')[0];
</script>
Replace...
<script type="text/javascript"> document.write(GET("id")[0]); </script>
with...
<script type="text/javascript">$('input').val(GET("id")[0]);</script>
Place that line after the input box.
Here are a couple of functions that help you parse a URL's parameters into an associative array.
function transformToAssocArray(prmstr) {
var arr = {};
var prmarr = prmstr.split("&");
for (var i = 0; i < prmarr.length; i++) {
var tmparr = prmarr[i].split("=");
arr[tmparr[0]] = tmparr[1];
}
return arr;
}
function getURLParmeters() {
var prmstr = window.location.search.substr(1);
if (prmstr === null || prmstr === '' ) {
return null;
}
return transformToAssocArray(prmstr);
}
Then you can assign all URL parameters to a variable like this:
var params = getURLParameters();
From then on, you can access the parameter's value by referencing params.paramternamehere. So, to assign the value of the "id" parameter to a text input, just grab that input element and assign params.id to that input's value.
var inputElement = document.getElementById("myTextInput");
if (params !== null) {
inputElement.value = params.id;
}
This technique utilizes the HTMLHyperlinkElementUtils.search property to reliably separate URL location components from paramters, and then does a simple string split to separate key-value pairs and then store those pairs in an associative array.

Passing array of array elements to a function

I've been searching for an answer of this concept for a whole day and finally gave up and decided to ask it here.
Here's the concept:
I have a set of fields which are arrayed, I want that set of fields to be inside of array so that I can use a standard function for saving a module based on the fields involved and another param to check which to save.
Sample code:
module1.php
<?php
$i=0;
while($i<5){
?>
<input type="text" name="field1[$i]" />
<input type="text" name="field2[$i]" />
<input type="text" name="field3[$i]" />
<?php
$i++;
}
?>
<input type="button" name="process"
onclick="checkFields(['field1', 'field2', 'field3'], 'module1');" />
<script>
function checkFields(f, m){
var fn = f.length;
alert(fn); //Output is 3
for(i=0; i<fn; i++){
var nfn = f[i].length; //Here's where it's not working
alert(nfn); //Output should be 5
}
}
</script>
So, that part with comment is the thing I can't figure how to do, I tried using getElementById, getElementsByName but it's not working.
Or is there any possibility that I can pass an array of elements like this: array(field1, field2, field3) to a function?
Edit: I added a while loop statement to make the concept more comprehensive.
<script>
function checkFields(f, m){
var fn = f.length;
alert(fn);
for(i=0; i<=fn; i++){
var nfn = f[i].length; //Here's where it's not working
alert(nfn);
}
}
</script>
You should be applying the indexer on the f parameter, instead of the fn variable which is an integer.
fn is the length of your array, not your array. You should be using f
Change...
var nfn = fn[i].length; //Here's where it's not working
To...
var nfn = f[i];
Also, you will find that the for loop will fail, as i will reach fn but the array stops at fn-1
So change...
for(i=0; i<=fn; i++){
To...
for(i=0; i<fn; i++){
f[i] still points to just the incorrect input names. You don't really get access to the input field.
Do this:
var inputName = f[i] + "[]";//remember the input name is field1[] and not field1.
var value = document.querySelector( "input[name='"+inputName+"']" ).value;
the value here is just the input text of the input field and not really an array. If you have multiple fields with the same name, then use document.querySelectorAll method to get all the input fields and then iterate to get the values one by one.
To help you understand better, consider these 2 options:
Option 1:
html:
<input name="field1[]" />
<input name="field1[]" />
access the value:
var inputFields = document.querySelectorAll("input[name='field1[]']");
var values = [];
for (var j = 0; j < inputFields.length; j++) {
var val = inputFields[i].value;
values.push(val);
}
Option 2:
html:
<input name="field1[0]" />
<input name="field1[1]" />
access the value:
var values = [];
var j = 0;
var inputField;
while (true) {
var inputField = document.querySelector("input[name='field1[" + j + "]']");
if (!inputField) break;
values.push(inputField.value);
j++;
}
Note that, in option 1, there are multiple fields with the same "name" and in option 2, there are multiple fields with unique names.

Categories

Resources