Accessing an element using id (JavaScript) - 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;

Related

Making variables assigned HTML ids with a function

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">
.

URL building with array parameters

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

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.

Binding an input element to a JavaScript object

I want to introduce a simple notation to bind a HTML <input> element to a JavaScript object. Something like:
<script>
var qform = {
uid : "",
pass : ""
};
</script>
<form method="get" action="#">
<input id="temp0" type="text" name="uid" bind="qform.uid" />
<input id="temp1" type="password" name="pass" bind="qform.pass" />
<input type="submit" value="submit" />
</form>
So that any changes to the <input>s will change my JS variable. The way I'm trying to implement it is:
<script>
var x = 0;
for(x = 0; x < 2; x++) {
var inputField = document.getElementById("temp" + x);
var bindObj = inputField.getAttribute("bind");
var bindObjTree = bindObj.split(".");
var parent = window;
for (var i = 0; i < bindObjTree.length - 1; i++) {
parent = parent[bindObjTree[i]];
}
child = bindObjTree[bindObjTree.length - 1];
inputField.value = parent[child];
inputField.onchange = function() {
var xp = parent;
var xc = child;
xp[xc] = inputField.value;
alert(JSON.stringify(window["qform"]));
};
} // for
</script>
However only the second input field behaves the way I want to. Can someone explain why that is? I'm guessing it has something to do with closures. I'm really trying to understand what I'm doing wrong rather than find a solution (I can easily work around this with JQuery, but I don't really want that).
The issue is with these:
parent = parent[bindObjTree[i]];
child = bindObjTree[bindObjTree.length - 1];
and
inputField.onchange = function() {
var xp = parent; // Always refers to the element retrieved at index 1 of the for loop
var xc = child; // Always refers to the element retrieved at index 1 of the for loop
// This is regardless of which input's event handler executes
xp[xc] = inputField.value;
alert(JSON.stringify(window["qform"]));
};
These will always refer to the elements found in the last iteration of the for loop because of closure.
inputFields needs to be an an array so it doesn't get overwritten in the loop or
you can place an id in the form tag and instead reference it to get the fields as its child elements.
Your child variable is global. Try to use:
var child = bindObjTree[bindObjTree.length - 1];
instead. Since it is global, you will overwrite the global child variable on the second turn.

Use array value as variable name

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

Categories

Resources