I need a value of text box for that I am using document.getElementsByName("elemntName") but the problem is the the name itself is dynamic, something like below.
for(temp = 0 ; temp < arracid.length ; temp++){
cell1=mynewrow.insertCell(4);
cell1.innerHTML="<input type='hidden' name='ACID"+index+"' class='tblrows' id='ACID"+index+"' value='"+arracid[temp]+"'>";
index++;
}
When I tried var acidCount = document.getElementsByName('ACID') its not working and I tried
var acidCount = document.getElementsByName('ACID"+index+"') still not working
For every loop the name is changing like ACID1,ACID2 etc.. can anyone help me how to get the value of this text box?
Since you are already assigning an ID to your inputs, it's recommended to use getElementsById which is faster than getElementsByName (and more accurate because the IDs are supposed to be unique, while the names don't have to be). Try this:
var acidCount = document.getElementById("ACID" + index);
If you still want to use getElementsByName, try this:
var acidCount = document.getElementsByName("ACID" + index);
But remember that getElementsByName returns a list of elements, but the list has only one element, because your names are unique. If you want to get that element in the list, you can use it's index like this:
var acidCount = document.getElementsByName("ACID" + index)[0];
Alternatively, if you want to get the list of all your inputs, first remove the index from the name:
cell1.innerHTML="<input type='hidden' name='ACID' class='tblrows' id='ACID"+index+"' value='"+arracid[temp]+"'>";
Then use:
var acidCount = document.getElementsByName("ACID");
Note: all the above return the DOM element(s). If you're only interested in the value, use the value property:
var acidCount = document.getElementById("ACID" + index).value;
or
var acidCount = document.getElementsByName("ACID" + index)[0].value;
(This is a jquery solution, since the question was initially tagged with jQuery)
You can use the selector of input elements with name starting with ^= ACID:
$("input[name^=ACID]").each(function(){
console.log($(this).val());
});
Issue is with single quoutes and double quotes :
var acidCount = document.getElementsByName("ACID"+index)
Since there can be more than one element with same name, so we need to get first element with that name, I have corrected your query check this, it will work.
var acidCount = document.getElementsByName('ACID'+index)[0].value
Try using wildcard * in the selector which will return all matched elements
document.querySelectorAll('[id*=ACID]')
You can try using class name.
$(document).find(".tblrows").each(function(){
console.log($(this).val());
});
Since you are naming your elements 'ACID' + index, you can utilize the querySelector method as follows:
for (var i=0; i < arracid.length; i++) {
var $el = document.querySelector('#ACID' + i));
}
Related
You can easily retrieve the tag name of an element using the nodeName, like this:
var atnode = document.getElementById("link-test");
alert(atnode.nodeName);
link
But how do I use the nodeName to get the attribute of the element instead?
Using the getAttribute() does not do what I want, because you have to insert the name of the attribute first, and then it just gives you back the value of the attribute. I want to get the name of the attribute just like I did with nodeName. I know nodeName can be used with attribute nodes too, but how?
const atnode = document.getElementById("link-test");
const nodes=[];
const values=[];
for (let att, i = 0, atts = atnode.attributes, n = atts.length; i < n; i++){
att = atts[i];
nodes.push(att.nodeName);
values.push(att.nodeValue);
console.log(att.nodeName + " - " + att.nodeValue);
}
link
After using attributes method you can use nodeName to get the attribute name and nodeValue to get the value of the attribute.
After pushing it to array you can get attribute and value of it using same index in both arrays.
You can get a list of the attributes with getAttributeNames() on the node. In your example, you could do like so:
atnode.getAttributeNames() This will return ["href", "id"].
Then you can loop through the list with getAttribute(<item from list as string>) to get the values of the element's attributes.
If I understood right, you just need to use the getAttributeNames method.
Follows an example:
const exampleElement = document.getElementsByTagName("example")[0];
console.log(exampleElement.getAttributeNames());
<example name="one" last="two"></example>
I have a for loop in my jquery script
var images[];
for(i=0;i<$('#imageHolder div').length;i++)
{
images.push($('#imageHolder div:eq( i )').attr('alt'));
console.log($('#imageHolder div:eq(i )').attr('alt'));
}
I am not able to add the elements to the array and the console.log says undefined in the console.
What is my possible error and how that can be corrected?
jQuery has useful method for this task, called $.fn.map:
var images = $('#imageHolder div').map(function() {
return $(this).attr('alt');
}).get();
Will produce an array of images alt attributes.
You have a typo:
images.push($('#imageHolder div:eq(' + i + ')').attr('alt'));
you need to concat i ^^^^
By the way, don't select your element every time in the for
var divs = $('#imageHolder div');
for(i=0; i < divs.length; i++)
i is a variable so need to use concatenation
$('#imageHolder div:eq('+ i + ')').attr('alt')
A more efficient way is to use .map(), in your case you are evaluating the selector many times which is not a optimal way
var images = $('#imageHolder div').map(function () {
return $(this).attr('alt')
}).get()
I have some ajax onclick stuff that updates this line when the value is selected from the menu:
<li id="li_273" data-pricefield="special" data-pricevalue="0" >
The intention is to take the that value (data-pricevalue) and then multiple it by the amount that is entered from another input box. Here's my function to try to make that happen:
$('#main_body').delegate('#element_240','keyup', function(e){
var temp = $(this).attr("id").split('_');
var element_id = temp[1];
var price = $('#li_273').data("pricevalue");
var ordered = $(this).val();
var price_value = price * ordered;
price_value = parseFloat(price_value);
if(isNaN(price_value)){
price_value = 0;
}
$("#li_273").data("pricevalue",price_value);
calculate_total_payment();
});
Except I get the following error:
Uncaught TypeError: Cannot call method 'data' of null
It appears as tho my attempt to get the price value out of getElementById isn't correct. Any suggestions?
UPDATE: The code above has been edited from your suggestions and thanks to all. It appears to be working just fine now.
This part is wrong:
var price = document.getElementById('#li_273').data("pricevalue").val();
Instead, you should use jQuery all the way here:
var price = $('#li_273').data("pricevalue");
Btw, you shouldn't use .val() because .data() already returns a string. .val() is used exclusively for input elements such as <input> and <select> to name a few.
Update
Also, the rest of your code should be something like this:
var price_value = parseFloat(price);
if(isNaN(price_value)){
price_value = 0;
}
getElementById doesn't return a jQuery object it returns just a normal DOM object.
You can wrap any DOM object in a jQuery call to get it as a jQuery object:
$(document.getElementById("li_273")).data("pricevalue").val();
Or better yet just use jQuery
$("#li_273").data("pricevalue").val()
Your call should be document.getElementById('li_273') it's a normal method and doesn't require the hash as jQuery does.
EDIT As #kennypu points out you're then using jQuery on a non jQuery object. #Craig has the best solution.
document.getElementById('#li_273').data("pricevalue").val(); should be jQuery('#li_273').data("pricevalue").val();
Again the variable price_value is not present, I think you mean price.
Ex:
$('#main_body').delegate('#element_240','keyup mouseout change', function(e){
var temp = $(this).attr("id").split('_');
var element_id = temp[1];
var price = $('#li_273').data("pricevalue").val();
var ordered = $(this).val();
var price_value = parseFloat(price);
if(isNaN(price_value)){
price_value = 0;
}
$("#li_273").data("pricevalue",price_value);
calculate_total_payment();
});
The document.getElementById('#li_273') is the problem. The method won't recognize the hash. If you want to get the element ID using that method try document.getElementById('li_273') and it will work.
Otherwise use all jQuery.
Since you're using jQuery, why are you using document.getElementById instead of $(...)? It should be:
$('#li_273').data("pricevalue")
Note also that the data() method is only defined on jQuery objects, not DOM elements. And you don't need to call val() after it -- that's for getting the value of form elements.
Your getElementById is wrong with javascript you do not need the #, if your using jQuery do it like this instead (Also I removed the .val() because its not needed):
$('#main_body').delegate('#element_240','keyup mouseout change', function(e){
var temp = $(this).attr("id").split('_');
var element_id = temp[1];
var price = $('#li_273').data("pricevalue");
var ordered = $(this).val();
price_value = parseFloat(price_value);
if(isNaN(price_value)){
price_value = 0;
}
$("#li_273").data("pricevalue",price_value);
calculate_total_payment();
});
I need to get the text that is inside a element.
I can only grab the class of this element and NOT the ID.
<span class="fileName">test.png</span>
So I need a way to get test.png, but as you see I have only the class of the element and not the ID.
Just notice also that we may have more <span class="fileName"></span>, so it could look like this
<span class="fileName">test1.png</span>
<span class="fileName">test2.png</span>
<span class="fileName">test3.png</span>
<span class="fileName">test4.png</span>
In the case we have more, like the example above, I need to get ALL the values and not only one, because I need to pass this value to another page with jQuery. So it should be able to get one value or more from that element.
Please help!
And also I am not a javascript expert!
var filenames = $('.fileName').map(function(){
return $(this).text();
}).get();
The array filenames will contain all the names of the images. You can pass on this array to another jQuery function, or anywhere else you like to do so.
You can test it here ยป
Update
Since you request the filenames to be a string separated by a comma, you can do it like this:
var filenames = $('.fileName').map(function(){
return $(this).text();
}).get().join(',');
Now, filenames will contain the string test1.png,test2.png,test3.png,test4.png.
Use document.getElementsByClassName: http://jsfiddle.net/pCswS/.
var elems = document.getElementsByClassName("fileName");
var arr = [];
for(var i = 0; i < elems.length; i++) {
arr.push(elems[i].innerHTML);
}
alert(arr);
(Since you didn't tag the question with jQuery I assume you have to do it with plain JavaScript.)
$('span.fileName').each(function() {
var fileName = $(this).text();
doSomethingWithFileName(fileName);
});
Here the span.fileName selector returns all spans with class fileName then we iterate through, reading the text from each one. You may want to find a container element first and then only iterate inside that, e.g.
var $container = $('#myFileNames');
$container.find('span.fileName').each( ... );
Here's my take:
var spans = document.getElementsByClassName('fileName');
var values = [];
for(var i = 0; i < spans.length; i++) {
values.push(spans[i].innerHTML);
}
// Example of processing: alert the values
alert(values);
Use the following jQuery selector
$("span.fileName").html()
For example, I have such HTML:
<input name="someinput[]">
I made a function to clone/remove this input but now I want to assign indexes to name dynamically - when I make an element clones, its new names should be someinput[1], someinput[2] etc. - how to make this?
You could just replace [] with [index] using the attr callback:
var i = 0;
$('button').click(function(){
$('input:first').clone().attr('name',function(a,e){
i++;
return e.replace("[]","["+i+"]");
}).insertAfter($('input:last'));
});
example: http://jsfiddle.net/niklasvh/c9G7c/
Keep the index of the next input in a global variable, and then use that in your cloning function. Is that what you do?
var source = $('#source')
var copy = source.clone().attr('name', 'some[' + index + ']')
$('body').append(copy);