JavaScript, numbers and strings - javascript

I need to automatically populate certain cells of a table according to the cell name (that as to be a number) but when you call the cell by it's name it gets interpreted as it's index number and instead of populating the correct cell it will populate the ordinal cell corresponding to the index.
document.getElementById("myTR").cells['9'].innerHTML = "testValue"
//the following doesn't work either
a ='9' or a = 9
b = a.toString()
document.getElementById("myTR").cells[b].innerHTML = "testValue"
Any ideas how to solve this?
I've tried to aggregate a letter to the number (9n) and it works, I just wonder if there is any know procedure for this.

document.getElementsByName('9')[0].innerHTML = 'testVal';
gets elements by name, selects the first (only) element and Bob's your uncle.

You may try this
HTML
<table>
<tr id="myTR">
<td>Row1</td><td name="9">Row1</td>
</tr>
<tr><td>Row2</td><td>Row2</td></tr>
</table>
JS
var x='9';
document.getElementsByName(x)[0].innerHTML = "testValue";
DEMO.
Also try to avoid to declare names that begins with numbers.

try this if the name is unique:
document.getElementByName('9').innerHTML = 'testValue';
by the way, I suggest u use jquery to operate the cell, follow is the code use jquery:
$('td[name=9]','#myTR').html("testValue");

Not sure if I will get frowned upon by JS purists, but I suggest using jQuery for this, this is what it was built for:
$("#myTR TD[name='9']").html("testValue");
This should get the cell named 9 in the tr tag with id myTR
Heres a fiddle for you: http://jsfiddle.net/aZEXV/1/

Related

Javascript - How to get attribute value from a tag, inside a specific div class?

Snippet of HTML code I need to retrieve values from:
<div class="elgg-foot">
<input type="hidden" value="41" name="guid">
<input class="elgg-button elgg-button-submit" type="submit" value="Save">
</div>
I need to get the value 41, which is simple enough with:
var x = document.getElementsByTagName("input")[0];
var y = x.attributes[1].value;
However I need to make sure I'm actually retrieving values from inside "elgg-foot", because there are multiple div classes in the HTML code.
I can get the class like this:
var a = document.getElementsByClassName("elgg-foot")[0];
And then I tried to combine it in various ways with var x, but I don't really know the syntax/logic to do it.
For example:
var full = a.getElementsByTagName("input")[0];
So: Retrieve value 41 from inside unique class elg-foot.
I spent hours googling for this, but couldn't find a solution (partly because I don't know exactly what to search for)
Edit: Thanks for the answers everyone, they all seem to work. I almost had it working myself, just forgot a [0] somewhere in my original code. Appreciate the JQuery as well, never used it before :-)
The easiest way is to use jQuery and use CSS selectors:
$(".elgg-foot") will indeed always get you an element with class "elgg-foot", but if you go one step further, you can use descendent selectors:
$(".elgg-foot input[name='guid']").val()
That ensures that you only get the input named guid that is a child of the element labelled with class elgg-foot.
The equivalent in modern browsers is the native querySelectorAll method:
document.querySelectorAll(".elgg-foot input[name='guid']")
or you can do what you have yourself:
var x = document.getElementsByClassName("elgg-foot")
var y = x.getElementsByTagName("input")[0];
Assuming you know it is always the first input within the div
You can combine it like this:
var a = document.getElementsByClassName("elgg-foot")[0];
var b = a.getElementsByTagName("input")[0];
var attribute = b.attributes[1].value;
console.log(attribute); // print 41
Think of the DOM as the tree that it is. You can get elements from elements in the same way you get from the root (the document).
You can use querySelector like
var x = document.querySelector(".elgg-foot input");
var y = x.value;
query the dom by selector https://developer.mozilla.org/en-US/docs/Web/API/Document/querySelector
var fourty1 = document.querySelector('.elgg-foot input[name=guid]').value;
querySelector will return the first match from the selector. This selector will find the element with class elgg-foot and then look at the input element inside of that for one named guid and then take the value of the selected element.
I think the simplest way would be using JQuery. But using only javascript,
the simplest way would be:
var div = document.getElementsByClassName("elgg-foot")[0];
var input = div.getElementsByTagName("input")[0];
alert(input.value)
Take a look at this JSFiddle here: http://jsfiddle.net/2oa5evro/

Is there a way to read hidden inputs with array-like names correctly in all browsers?

An interface has a number of hidden inputs called "kilos[]" or "precio[]". These are then passed on to a PHP function that handles them like an array. All that is fine. However, if I require to delete a row (tr) from the table (where the inputs will be deleted, too) then I do the following:
var e=t.parentNode.parentNode;
var ix=e.sectionRowIndex;
var p=e.parentNode;
var f2=t.form;
var kl= p.rows.length > 2 ? f2.elements["kilos[]"][ix].value : f2.elements["kilos[]"].value;
var pc= p.rows.length > 2 ? f2.elements["precio[]"][ix].value:f2.elements["precio[]"].value;
f2.tokilos.value-=parseFloat(kl).toFixed(2);
f2.tomonet.value-=parseFloat(pc).toFixed(2);
f2.totamb.value-=parseFloat(kl).toFixed(2);
p.removeChild(e);
Notice that this code only works in Chrome, nowhere else. Can you see what needs to be done in order to get the correct values of "kilos[]" and "precio[]"?
If the total number of rows left in the table is greater than 2, then I can use:
f2.elements["kilos[]"][ix].value
However, if the number of rows is not greater than 2, I need to do this, instead:
f2.elements["kilos[]"].value
That is the only way for it work and only in Chrome. sectionRowIndex returns the correct values all the time; it is the form.elements["name[]"][ix].value that by itself does not behave as expected when the number of rows in the tbody is only 1 (the last one). The code works and does what I need it to be done; however, it is odd that such a workaround is needed.
Is there a way to make this work in all browsers, using pure javascript?
You could use document.getElementsByName('kilos[]') which will always return an array-like object.
If you want to restrict the search to a specific element, you can use querySelectorAll:
var inputs = f2.querySelectorAll('[name="kilos[]"]');
// or
var inputs = document.querySelectorAll('#formID [name="kilos[]"]');

JS: how to find a specific string, then extract an integer?

I'm trying to write a userscript for a game I'm playing. It uses this piece of HTML code:
<td valign="center">
<b>ten-leaf clover</b>
(4 left in stock for today)
</td>
This is a picture of what we're talking about:
The script should search for a string containing the words "left in stock for today", then look for an integer within this string. (The '4' is not constant, it changes every day.) Lastly, I would like to store this integer as a variable, so I can replace the '1' in the input field. Like this:
var clover = EnterCodeHere
$("input.text[name='quantity']").val(clover);
You can used a regex like so:
var textToSearch = $("td").innerHtml(); //You'll need a better selector than this. better to use a class or id
var clover = parseInt(textToSearch.match(/\d+\s*left in stock for today/)[0].match(/\d+/)[0]);
$("input.text[name='quantity']").val(clover);
You may want to check the array isn't empty before just taking the first value but if your confident it'll be there should be grand.

Insert a cell with javascript and then insert checkboxes into it?

I want to create a table with javascript, and in some of the cells, put in radiobuttons and checkboxes with javascript.
I found this code:
function insRow() {
var x = document.getElementById('myTable').insertRow(0);
var y = x.insertCell(0);
y.setAttribute('id', "NewDiv");
}
(the last line (setAttribute) is a line that I added. I thought that I could give the new table cell an ID, and then use document.GetElementByID with that ID in various subroutines. That does not work. Now maybe making a global variable to store a copy of 'y' in would work - I could use it in the routines. But shouldn't the above code also work?
The document.getElementById method (lowercase "g" and "d") will only work once the element is added to the DOM.
Ultimately, if possible, do your manipulations from the y variable, before it's appended, but it will be accessible by ID just like any other element.

Extracting values from Array with Javascript

I am having issues with getting exactly values with Javascript.
Following is working version of when we have class on single item.
http://jsfiddle.net/rtnNd/
Actually when code block has more items with same class (see this: http://jsfiddle.net/rtnNd/3), it picks up only the first item which use the class name.
My issue is that I would like to pick up only the last item which use the class name. So I used following code:
var item = $('.itemAnchor')[6];
var href = $($('.hidden_elem')[1].innerHTML.replace('<!--', '').replace('-->', '')).find(item).attr('href');
But it doesn't work though. I don't really know why.
The code that may contains items are using same class, class may be use in 2 items, 3 items, or 6th times. That's why, I want to pick up only the last item to extract.
Can you explain, thank you all for reading my question.
"My issue is that I would like to pick up only the last item which use the class name."
OK, so in a general sense you would use the .last() method:
var lastItem = $('.itemAnchor').last();
Except that there are no elements in the DOM with that class because (in your fiddles) they're all commented out. This is also the reason why the code you showed in your question didn't work. The first line:
var item = $('.itemAnchor')[6];
...sets the item variable to undefined. The selector '.itemAnchor' returns no elements, so $('.itemAnchor') is an empty jQuery object and it has no element at index 6.
You need to use the '.itemAnchor' selector on the html that you get after removing the opening and closing comments with your .replace() statements, so:
var href = $($('.hidden_elem')[0].innerHTML.replace('<!--','').replace('-->',''))
.find('.itemAnchor').last().attr('href');
Demo: http://jsfiddle.net/rtnNd/4/
EDIT in response to comment:
"How can we pick up the itemElement before that last one."
If you know you always want the second-last item use .slice(-2,-1) instead of .last(), as shown here: http://jsfiddle.net/rtnNd/5/
Or if you know you want whichever one has an href that contains a parameter h= then you can use a selector like '.itemAnchor[href*="h="]' with .find(), in which case you don't need .last() or .slice():
var href = $($('.hidden_elem')[0].innerHTML.replace('<!--','').replace('-->',''))
.find('.itemAnchor[href*="h="]').attr('href');
Demo: http://jsfiddle.net/rtnNd/6/
Note though that this last method using the attribute-contains selector is picking up elements where the href has the text "h=" anywhere, so it works for your case but would also pick up hh=something or math=easy or whatever. You could avoid this and test for just h= as follows:
var href = $($('.hidden_elem')[0].innerHTML.replace('<!--','').replace('-->',''))
.find('.itemAnchor')
.filter(function() {
return /(\?|&)h=/.test(this.href);
}).attr('href');
Demo: http://jsfiddle.net/rtnNd/7/

Categories