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.
Related
I can make variables one by one like this:
var bookName = document.getElementById('bookName').value,
author = document.getElementById('author').value,
translator = document.getElementById('translator').value,
pageCount = document.getElementById('pageCount').value,
publisher = document.getElementById('publisher').value,
isbn = document.getElementById('isbn').value,
printingYear = document.getElementById('printingYear').value;
But it's so hard to write and it doesn't fit with the DRY rule. So I changed the code to this:
function variableMaker(argument) {
var tags = document.getElementsByTagName(argument);
for (var i = 0; i < tags.length; i++) {
var tags[i].name = tags[i].value;
}
}
variableMaker(input);
But I can't understand if it is the true way or if it is working? How do I check if it's true or not?
In this code, I tried to get the computer find all the input tags and make variables with their name property and assign it to its values for each of them.
If I understand correctly then you want to gather data from all <input> elements. If so, then you need to call it like this:
variableMaker('input'); // use quotes!
Still even then your function does not return anything, it just ends.
You'd also better create your own object for the return collection, instead of adding values to an existing object.
Here is a working solution:
function variableMaker(tagName) {
var elements = document.getElementsByTagName(tagName);
var items = {};
for (var i = 0; i < elements.length; i++) {
var elem = elements[i];
items[elem.id] = elem.value; // Use id as key, each points to the corresponding value.
}
return items;
}
var values = variableMaker('input');
console.log(values); // show the entire return object
console.log(values.author); // access individual items from the return object
console.log(values.isbn);
<input type="text" id="author" value="Dahl">
<input type="text" id="isbn" value="1234">
.
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;
I need to use jQuery's keyup function to take the value from input html form elements and display said values in a div elsewhere.
The working code looks as follows:
$('#name').keyup(function() {
var name = $(this).val();
$('#name-in-document').html(name);
});
Since I have many identical instances of the above code block, I'd like to use a for loop to loop through an array of values. The catch is the name of the variable in the second line
var name = $(this).val();
would come from the array.
I have tried the following loop, which does not work because (as I understand it) a Javascript variable cannot be named an array value:
var inputsArray = ["phone", "name", "address"];
for (var i = 0; i < inputsArray.length; i++) {
$("#"+inputsArray[i]).keyup(function() {
var inputsArray[i] = $(this).val();
$("#"+inputsArray[i]+"-in-document").html(inputsArray[i]);
})
};
So I have two questions:
Is it true that I cannot use the array values to create a variable in the for loop?
Is there an alternate way to accomplish the same thing (getting the variable names from the array) that might work?
I am just beginning JavaScript and really appreciate any insight. Thank you!
1. It is not true
2. You'll need to make a closure over the variable i or over the value from inputArray[i] and inside the event-bind the keyword this refers to the DOMNode witch triggers the event:
Read more absout closures here How do JavaScript closures work?
var inputsArray = ["phone", "name", "address"],
i = 0,
len = inputsArray.length;
for ( ; i < len; i ++ ) {
makeKeyupBind(inputsArray[i]);
}
function makeKeyupBind( value ) {
$("#" + value).on("keyup", function() {
$("#" + value + "-in-document").html( this.value );
});
}
That variable only exists within the scope of the function passed as a callback for the keyup event so I don't really see the need to give it a dynamic name; you could call it absolutely anything at all and not run into conflicts.
For the alternative approach, I would recommend giving #name (and his friends) a class name, e.g.
<input class="js-key-up" id="name" />
Then you can do away with the array and the for loop altogether. Also, adding new HTML elements would not require adding items to the array.
HTML
<input class="js-key-up" id="phone">
<input class="js-key-up" id="name">
<input class="js-key-up" id="address">
<p id="phone-in-document"></p>
<p id="name-in-document"></p>
<p id="address-in-document"></p>
JavaScript
$('.js-key-up').keyup(function (e) {
var id = $(this).attr('id');
$('#' + id + '-in-document').html($(this).val());
});
I've created a jsfiddle with the code in.
Try this:
var inputsArray = ["phone", "name", "address"];
for (var i = 0; i < inputsArray.length; i++) {
$("#"+inputsArray[i]).keyup(function() {
var valuesArray[i] = $(this).val();
$("#"+inputsArray[i]+"-in-document").html(valuesArray[i]);
})
var inputsArray = ["phone", "name", "address"];
for (var i = 0; i < inputsArray.length; i++) {
$("#"+inputsArray[i]).keyup(function() {
var htmlValue = $(this).val();
$("#"+inputsArray[i]+"-in-document").html(htmlValue);
})
I think you don't need to name variable from array, do you?
You can build a selector straight from the array and skip the loop completely. Use the id of the current input to create the selector for the other element
var inputsArray = ["phone", "name", "address"];
$('#'+ inputsArray.join(',#') ).keyup(){
$('#'+this.id+"-in-document").html( $(this).val() );
})
This will create the selector:
$('#phone,#name,#address')
Above assumes that you are trying to find elements :
$("#phone-in-document").html(val);
$("#name-in-document").html(val);/* etc*/
#Wes Cossick: this line inside of the loop is wrong:
var valuesArray[i] = $(this).val();
if you want to do it that way declare the array before the loop. that is problem of OP
#diana: if i understand you correct, you want to add a dynamic keyup handler to every item in the array? if it is that way, that code should do it (dont reassign items in the array!) the trick is to create a closure (code is untested).
var inputsArray = ["phone", "name", "address"];
for (var i = 0; i < inputsArray.length; i++) {
(function(item) {
$("#"+item).keyup(function() {
$("#"+item+"-in-document").html($(this).val());
});
})(inputsArray[i]);
};
if you are using jQuery (and it seems so ;-), take a look at the each-function in jQuery: http://api.jquery.com/jQuery.each/
that should be a lot easier for you ;-)
I've got about twenty checkboxes that are dynamically created with the following pattern:
<input type="checkbox" id="cb01" name="vehicle" />
I give it an ID of cb + index and a name attribute that corresponds to a database entry.
So over to my question:
Whats the best way to loop through the checkboxes performance wise? I need to send both the name and the value of the checkbox.
I would prefer the data as a jsonstring..
First, I'd give them all a common class. Let's say cb.
Then:
var json = {};
var checkboxes = document.querySelectorAll('.cb');
for ( var i = 0, l = checkboxes.length; i < l; i++ )
json[ checkboxes[i].name ] = checkboxes[i].checked;
Or with jQuery:
var json = {};
$('.cb').each(function(){
json[ this.name ] = this.checked;
});
Is there a way to create a dynamic array of strings on Javascript?
What I mean is, on a page the user can enter one number or thirty numbers, then he/she presses the OK button and the next page shows the array in the same order as it was entered, one element at a time.
Code is appreciated.
What I mean is, on a page the user can enter one number or thirty numbers, then he/she presses the OK button and the next page shows the array in the same order as it was entered, one element at a time.
Ok, so you need some user input first? There's a couple of methods of how to do that.
First is the prompt() function which displays a popup asking the user for some input.
Pros: easy. Cons: ugly, can't go back to edit easily.
Second is using html <input type="text"> fields.
Pros: can be styled, user can easily review and edit. Cons: a bit more coding needed.
For the prompt method, collecting your strings is a doddle:
var input = []; // initialise an empty array
var temp = '';
do {
temp = prompt("Enter a number. Press cancel or leave empty to finish.");
if (temp === "" || temp === null) {
break;
} else {
input.push(temp); // the array will dynamically grow
}
} while (1);
(Yeah it's not the prettiest loop, but it's late and I'm tired....)
The other method requires a bit more effort.
Put a single input field on the page.
Add an onfocus handler to it.
Check if there is another input element after this one, and if there is, check if it's empty.
If there is, don't do anything.
Otherwise, create a new input, put it after this one and apply the same handler to the new input.
When the user clicks OK, loop through all the <input>s on the page and store them into an array.
eg:
// if you put your dynamic text fields in a container it'll be easier to get them
var inputs = document.getElementById('inputArea').getElementsByTagName('input');
var input = [];
for (var i = 0, l = inputs.length; i < l; ++i) {
if (inputs[i].value.length) {
input.push(inputs[i].value);
}
}
After that, regardless of your method of collecting the input, you can print the numbers back on screen in a number of ways. A simple way would be like this:
var div = document.createElement('div');
for (var i = 0, l = input.length; i < l; ++i) {
div.innerHTML += input[i] + "<br />";
}
document.body.appendChild(div);
I've put this together so you can see it work at jsbin
Prompt method: http://jsbin.com/amefu
Inputs method: http://jsbin.com/iyoge
var junk=new Array();
junk.push('This is a string.');
Et cetera.
As far as I know, Javascript has dynamic arrays. You can add,delete and modify the elements on the fly.
var myArray = [1,2,3,4,5,6,7,8,9,10];
myArray.push(11);
document.writeln(myArray); // Gives 1,2,3,4,5,6,7,8,9,10,11
var myArray = [1,2,3,4,5,6,7,8,9,10];
var popped = myArray.pop();
document.writeln(myArray); // Gives 1,2,3,4,5,6,7,8,9
You can even add elements like
var myArray = new Array()
myArray[0] = 10
myArray[1] = 20
myArray[2] = 30
you can even change the values
myArray[2] = 40
Printing Order
If you want in the same order, this would suffice. Javascript prints the values in the order of key values. If you have inserted values in the array in monotonically increasing key values, then they will be printed in the same way unless you want to change the order.
Page Submission
If you are using JavaScript you don't even need to submit the values to the different page. You can even show the data on the same page by manipulating the DOM.
You can go with inserting data push, this is going to be doing in order
var arr = Array();
function arrAdd(value){
arr.push(value);
}
Here is an example. You enter a number (or whatever) in the textbox and press "add" to put it in the array. Then you press "show" to show the array items as elements.
<script type="text/javascript">
var arr = [];
function add() {
var inp = document.getElementById('num');
arr.push(inp.value);
inp.value = '';
}
function show() {
var html = '';
for (var i=0; i<arr.length; i++) {
html += '<div>' + arr[i] + '</div>';
}
var con = document.getElementById('container');
con.innerHTML = html;
}
</script>
<input type="text" id="num" />
<input type="button" onclick="add();" value="add" />
<br />
<input type="button" onclick="show();" value="show" />
<div id="container"></div>
The following code creates an Array object called myCars:
var myCars=new Array();
There are two ways of adding values to an array (you can add as many values as you need to define as many variables you require).
1:
var myCars=new Array();
myCars[0]="Saab";
myCars[1]="Volvo";
myCars[2]="BMW";
You could also pass an integer argument to control the array's size:
var myCars=new Array(3);
myCars[0]="Saab";
myCars[1]="Volvo";
myCars[2]="BMW";
2:
var myCars=new Array("Saab","Volvo","BMW");
Note: If you specify numbers or true/false values inside the array then the type of variables will be numeric or Boolean instead of string.
Access an Array
You can refer to a particular element in an array by referring to the name of the array and the index number. The index number starts at 0.
The following code line:
document.write(myCars[0]);
will result in the following output:
Saab
Modify Values in an Array
To modify a value in an existing array, just add a new value to the array with a specified index number:
myCars[0]="Opel";
Now, the following code line:
document.write(myCars[0]);
will result in the following output:
Opel
Please check http://jsfiddle.net/GEBrW/ for live test.
You can use similar method for dynamic arrays creation.
var i = 0;
var a = new Array();
a[i++] = i;
a[i++] = i;
a[i++] = i;
a[i++] = i;
a[i++] = i;
a[i++] = i;
a[i++] = i;
a[i++] = i;
The result:
a[0] = 1
a[1] = 2
a[2] = 3
a[3] = 4
a[4] = 5
a[5] = 6
a[6] = 7
a[7] = 8
Just initialize an array and push the element on the array.
It will automatic scale the array.
var a = [ ];
a.push('Some string'); console.log(a); // ['Some string']
a.push('another string'); console.log(a); // ['Some string', 'another string']
a.push('Some string'); console.log(a); // ['Some string', 'another string', 'Some string']