Get the length of an array using document.getElementsbyName() - javascript

Hi I have an array like this.
var i;
for(i=0;i<10;i++){
$('<input/>').attr('type','text')
.attr('name','TxtBx_[]')
.attr('id','TxtBx_' + i)
.attr("readonly","readonly")
.attr('value',i)
.addClass('txtbx')
.appendTo($div);
}
And I prints the 10 input boxes well.
Later I need to get the number of text boxes I have created. So I'm using
var myarr=document.getElementsByName('TxtBx_');
var numberofElements=myarr.length;
but when I put an alert to check the value of numberofElements it gives me always 0. The length of the array must be 10. Could someone please let me know the mistake I have made.

The elements' names are TextBx[], not TxtBx_.
var myarr=document.getElementsByName('TextBx[]');
var numberofElements=myarr.length;

Element names are TextBx[] and TxtBx_ is a class name
var myarr=document.getElementsByName('TextBx[]');
var numberofElements=myarr.length;
Read getElementsByName() documentation for more information

var numberofElements = document.getElementsByName("TextBx[]").length;
Name of textbox is 'name','TxtBx_[]' getting by TxtBx_.

Because no element has name TxtBx_ . It's TextBx[] actually.
Since you are alrady using jQuery, you can find by class like below,
$('.txtbx').length
Few other things, I would like to add here.
attr accepts a object too. So, you can pass all inputs at once. Also, you can pass attributes as second arguement while dynamically creating input. Also, according to jQuery docs, you should specify type in input type while dynamically creating them or it won't work in some IE.
So, try something like this,
var i;
for(i=0;i<10;i++) {
$('<input type="text"/>',{
'name': 'TxtBx_[]',
'id': 'TxtBx_' + i,
'readonly':'readonly'
'value': i,
'class': 'txtbx'
}).appendTo($div);
}

Try it
$("input.txtbx").length;

Just use the class to get them:
var numberofElements = $('.txtbx').length;

Related

Clone element and increment index placed in name by 1

Lets say I have this input:
name="fecha_inicio[2]"
And I want to clone it and generate:
name="fecha_inicio[3]"
How can I do so?
I tried something like this, but Its ugly and it won't work..
var $input = $original.clone();
var name = $input.attr('name');
name.replace('['+(indice-1)+']', '['+indice+']');
$input.attr('name', name);
replace method doesn't modify string in place, but returns a new string. So your code should be:
name = name.replace('['+(indice-1)+']', '['+indice+']');
Also maybe you don't really need to have such index names. You can simply go with name="fecha_inicio[]" and don't worry about index. Later you would get form data with say serialize method.

Accessing a Dynamically Named array in jQuery/javascript

I wish to name an array according to the table row containing the button that was clicked.
I get the table row thus:
var rowNum = $(this).parent().parent().index();
Now, I wish to name the array and access it.
var arrayName = 'arrTR' + rowNum;
window[arrayName] = new Array();
window[arrayName]["First"] = "Bob";
window[arrayName]["Last"] = "Roberts";
window[arrayName]["email"] = "me#there.com";
//The array should be accessible as arrTR__
alert(arrTR1["Last"]);
The alert does not work, so I am doing something wrong.
How should I refactor the code to allow me to update and access the array?
jsFiddle
What you're doing with the dynamically named variables is essentially creating an array of those variables (one for each rowNum), but giving each of those array elements its own individual named variable.
There is a much better way to do this. Instead of generating a series of dynamically named variables, make a single array or an object. Then add an element or property for each of the dynamically named variables you were going to generate.
Your test code could look like this:
var arrTR = [];
var rowNum = 1;
arrTR[rowNum] = {
First: 'Bob',
Last: 'Roberts',
email: 'me#there.com'
};
alert( arrTR[1].Last );
Alternatively, you can do something with $.data as mentioned in Johan's answer. But if you do use plain JavaScript code, use a single array as described here instead of multiple dynamically named variables.
There are several reasons to do it this way. It's cleaner and easier to understand the code, it may be faster when there are large numbers of entries, and you don't have to pollute the global namespace at all. You can define the var arrTR = []; in any scope that's visible to the other code that uses it.
Arrays and objects are made for keeping track of lists of things, so use them.
There is nothing wrong with your code, and the only place it has error is the alert since it is not defined on the first click button
see this fiddle with a little update
if(rowNum === 1)
alert(arrTR1["Last"]);
else if(rowNum === 2)
alert(arrTR2["Last"]);
fiddle
How about something like this?
$('.getinfo').click(function() {
var result = $('table tr:gt(0)').map(function(k, v){
return {
firstName: $(v).find('.fname').val(),
lastName: $(v).find('.lname').val(),
email: $(v).find('.email').val(),
}
}).get();
//update to show how you use the jQuery cache:
//1. set the value (using the body tag in this example):
$('body').data({ result: result });
//2. fetch it somewhere else:
var res = $('body').data('result');
});
Not sure how you want to handle the first row. I skip in in this case. You can access each row by result[index].
As you might have noticed, this saves all rows for each click. If you want to use the clicked row only, use the this pointer.
http://jsfiddle.net/nwW4h/4/

jQuery equivalent to "getElementsByName"

What is the correct jquery syntax for a getElementsByName call?
Here is my javascript code:
var test = document.getElementsByName(tableName)[0];
using this is returning a different value:
var test = $("[name=tableName]");
Thanks in advance
Use quotes around the attribute selector:
$('[name="somenamehere"]');
If you need to use a variable within a selector, you need to use string concatenation to get the value of the variable:
$('[name="' + tableName + '"]');
Typically one should avoid using the [name] attribute in favor of the [id] attribute, because selection would be simpler as:
$('#someidhere');
-or-
$('#' + tableID);
Remove the index from the first statement
These are equal.
var test = document.getElementsByName(tableName);
var test = $("[name=tableName]");
"[name=tableName]" is bad syntax in 2 ways. First, you should put your name in quotes, so it should be "[name='tableName']" and second, in the first case, you're using a variable and in the second, a string, so in reality it shoudl be "[name='" + tableName + "']"
good call also on the fact that you have an index on your getelementsbyname() call, if you select item [0] then it will only return one item.
Interesting to know that jquery is a LOT slower than the native method here.
See the jsPrefs test : http://jsperf.com/getelementsbyname-vs-jquery-selektor/4
if you want to get a element value use this code:
var test1 = $("[name='tableName']").val();
alert(test1);
These are equal to get value of specific index[]:
For same index [0]
var test2 = $("[name='arryname[]']")[0];
alert(test2.value);
var test3 = $("[name='arryname[]']").get([0]);
alert(test3.value);

How can I make the script to work?

I have 3 HTML form inputs fields that is dynamically generated by a "add more" button, with naming for the fields name as fieldName, fieldName1, fieldName2, fieldName3, and so on.
Now, I'm trying to retrieve the value from this fields with JavaScript, using the script below.
var bookingForm = document.forms['formName'];
var qty = bookingForm.fieldName +'i'.value;
with the 'i' been a generated numeric number by a for loop
when I use alert(qty), it returns NaN, when I'm expecting the value for fieldName1, fieldName2, and so on.
But when I use;
var qty = bookingForm.fieldName.value
I can get the value in that field but get NaN when I try to concatenate 1,2,3, with the fieldName.
Any help will be very much appreciated.
You use brackets to access a property using a string:
var qty = bookingForm['fieldName' + i].value;
You can't use code like:
var qty = bookingForm.fieldName +'i'.value;
bookingForm.fieldName +'i' is a string. You have to change that string into a DOM element in order to access the .value parameter.
Try document.getElementsByName('fieldName'+i)[0].value

How can I dynamically construct a document element string using a variable in Javascript?

This is driving me nuts, and I'm sure it's both possible and surely simple to do.
I have a page with a whole bunch of dynamically created forms on it. In one of my functions, I need to access one of those forms, so I pass the name of the form in a variable.
Then I need to access the name of that form using the document tree.
However, when I put in the variable, it assumes the name of the variable is the name of the form.
So this does not work:
function myAwesomeFunction(nameOfForm)
{
var selection = document.nameOfForm.nameOfInput.selectedIndex;
}
So I looked around the net and saw that I need to use bracket notation, but this doesn't work either:
function myAwesomeFunction(nameOfForm)
{
var selection = document[nameOfForm].nameOfInput.selectedIndex;
}
I also tried with some quotation action:
function myAwesomeFunction(nameOfForm)
{
var selection = document['nameOfForm'].nameOfInput.selectedIndex;
}
... but no joy.
So, where am I going wrong?
For bonus points... what if both the name of the form and the name of the particular input were both dynamic? Then what?
function myAwesomeFunction(nameOfForm, nameOfInput)
{
var selection = document[nameOfForm][nameOfInput].selectedIndex;
}
Look them up in the forms object - this won't work since it is an array and not an object.
use document.getElementsByName
function myAwesomeFunction(nameOfForm, nameOfInput)
{
var selection = document.getElementsByName(nameOfForm)[nameOfInput].selectedIndex;
}
or even better, set an id attribuite on the form and use document.getElementById to find the form
Try using document.getElementById(nameOfForm) (if you have the ID on the form as well)...
If you can include a jQuery reference to your page, you can easily do the following (again assuming you have the ID on the form):
function myAwesomeFunction(nameOfForm, nameOfInput)
{
var form = $("form#" + nameOfForm);
var input = $("#" + nameOfInput + ":input");
var selection = $(input).val();
}
function focusElement(formName, elemName) {
var elem = document.forms[formName].elements[elemName];
}
try this
formname is name of the form and elemname is input label name

Categories