Loop through a table to find specific id's - javascript

I have a table that I'm trying to insert a paypal button in the last cell of the table which is blank. I'm not sure how many rows will be in the table and I have the id's hard coded now which works. The id's begin with el and a number for each row then _qryMyReservedSlots_Payment
['#el1_qryMyReservedSlots_Payment', '#el2_qryMyReservedSlots_Payment', '#el3_qryMyReservedSlots_Payment'].forEach(function(selector) {
paypal.Button.render({
...paypal code...
});
});
to be more efficient, how can I loop through the id's so I don't have to hard code them?
Scott

I'm not sure how many rows will be in the table and I have the id's
hard coded now which works
Use querySelectorAll and attribute contains selector - *
var allRows = document.querySelectorAll( "tr[id*='qryMyReservedSlots_Payment']");
Array.from( allRows ).forEach( function(rowElement){
//logic with rowElement
})

Use a for loop:
for (var el = 1; el < 4; el++) {
var selector = `#el${el}_qryMyReservedSlots_Payment`
...
}
or more old-fashioned:
for (var el = 1; el < 4; el++) {
var selector = '#el' + el + '_qryMyReservedSlots_Payment'
...
}

Do you need them to have unique ids ? You should give them a class and then do something like document.getElementsByClassName(className).forEach(...).
If you insist on having unique ids (which, again, is not needed and this is exactly one of the reasons why we have classes), your could would be something like this:
while (document.getElementById(`el${ counter++ }_qryMyReservedSlots_Payment`)) {
paypal.Button.render({
...paypal code...
});
}
Again, this is not good because each time you query the id, you are hitting the DOM. You should really get it all at once, manipulate in-memory, and then commit all your changes in as few DOM calls as possible.

Related

jQuery: Adding td elements with one class to tr

First of all I have to find the number of cells with one class, this line works.
var numcells = $('.hidden-td').length
And now I have to find the element with the class .placeholder-style I use this line (only one <tr>have this class):
$(this).find('.placeholder-style')
Now I have to add the same number of var numcellslike <td>inside the <tr>with the clase .hidden-td I think this will be with .addClass('hidden-td').
How can I make this?
Thanks
I'm assuming this is the correct structure you're after... if not, post your HTML so I can amend it but either way, this is how you should do it.
var numcells = $('.hidden-td').length;
var content = $(this).find('.placeholder-style');
for (i = 0; i < numcells; i++) {
content.append('<td class="hidden-td"></td>');
}

Have addEventListener on multiple of the same IDs

I need to add an event listener to my retweet, like and dislike buttons. They all have the same ID so right now only the top tweet has the counter increase. This is a project for school so I can only use raw JS. Here is a link to the fiddle:
https://jsfiddle.net/1sc7g5ko/
And here is what my JS looks like
var retweets;
retweets = 0;
var likes;
likes = 0;
var dislikes;
dislikes = 0;
document.getElementById("retweet").addEventListener("click", retweetClicked);
function retweetClicked(){
document.getElementById("retweet").innerHTML = retweets += 1;
};
document.getElementById("likes").addEventListener("click", likeClicked);
function likeClicked(){
document.getElementById("likes").innerHTML = likes += 1;
};
document.getElementById("dislikes").addEventListener("click", dislikeClicked);
function dislikeClicked(){
document.getElementById("dislikes").innerHTML = dislikes += 1;
};
Element IDs should be unique within your entire document. If you have more than one element with the same ID, your HTML is invalid.
Source: Can multiple different HTML elements have the same ID if they're different types?
I suggest you use classes instead, which support having multiple elements with the same class.
Then you can use document.getElementsByClassName("name") to get a list of all elements with that class.
What #Maxmillian Laumeister said is correct, but there are other solutions and/or workarounds. For example, let's say you have three <BUTTON> elements with the ID of edit. How you would go about adding event listeners to all of these elements is as such:
First we would grab all of the elements using querySelectorAll
Then, we would loop through with them using forEach
Inside/Using this forEach loop, we would then add the event listeners.
Implementation of this process is below. Feel free to view the demo of this on JSFiddle.
https://jsfiddle.net/n1b2u8cm/
document.querySelectorAll("#edit").forEach((e) => {
e.addEventListener("click", () => {
document.body.style.background = "red";
setTimeout(() => {
document.body.style.background = "blue";
}, 300);
});
});

Count number of elements with distinct name using jQuery or javascript

Suppose I have a form with 20 rows as shown in the figure below:
I'm naming the elements in the each row as:
1st row (Ambiance) -> v1[requirement], v1[observation], v1[status], v1[remarks]
2nd row (TV Room) -> v2[requirement], v2[observation], v2[status], v2[remarks]
3rd row (Cleanliness) -> v3[requirement], v3[observation], v3[status], v3[remarks]
.... and so on till 20th row
Using jquery or javascript can I find the number of rows present based on the names of the element? i.e., in this form name starts from v1 and ends at v20. So there are 20 rows.
UPDATE
The reason why I want the number of rows is because I plan to process the forms using:
for($i=1; $i<=$rowcount; $i++)
{
$v.$i = $_POST['v'.$i];
// then insert the first row into table and so on
}
If there is always a header row, then the number of rows will be the number of tr elements in the table -1, Eg.
var rowCount = $("#myTable tr").length -1;
This saves you having to use some convoluted method of attribute selector or string parsing.
This approach should work for you:
var rowCount = $("#data-table tr").filter(function() {
return $(this).find('[name^="v"]').length;
}).length;
This code will count only tose rows which have input with the name starting with v. I guess this is what you need.
Quick demo: http://jsfiddle.net/dfsq/2P5cN/
UPD
As per Mark Reed's comment we can make it even more simple:
var rowCount = $('#data-table tr').has('[name^=v]').length;
If you can't modify the markup at all, then you'll pretty much have to loop over everything and do your own counting. Something like this:
var tds = document.getElementsByTagName('td'); // or just $('td') for jQuery
var count_tds = tds.length;
var max = 0;
for (var i=0; i<count_tds; ++i) {
var td = tds[i]
var m = td.id.match(/^v(\d+)\[/)
if (m) {
if (m[1] > max) max=m[1]
}
}
Now max is the number of rows, assuming there are no extraneous elements with id's that match the pattern.
http://jsfiddle.net/usDD7/1/
EDIT Clearly I wasn't thinking with jQuery. See dfsq's answer for a much better solution (and my comment on that answer for a tiny improvement).

Access dynamic generated div id

I have some div ids that are generated dynamicly via php
<div id='a<?php echo $gid?>>
How can I access them in JavaScript? All these divs start with "A" followed by a number.
Is there some kind of search function
getElementById(a*)?
Thanks for any help
No generic JavaScript function for this (at least not something cross browser), but you can use the .getElementsByTagName and iterate the result:
var arrDivs = document.getElementsByTagName("div");
for (var i = 0; i < arrDivs.length; i++) {
var oDiv = arrDivs[i];
if (oDiv.id && oDiv.id.substr(0, 1) == "a") {
//found a matching div!
}
}
This is the most low level you can get so you won't have to worry about old browsers, new browsers or future browsers.
To wrap this into a neater function, you can have:
function GetElementsStartingWith(tagName, subString) {
var elements = document.getElementsByTagName(tagName);
var result = [];
for (var i = 0; i < elements.length; i++) {
var element = elements[i];
if (element.id && element.id.substr(0, subString.length) == subString) {
result.push(element);
}
}
return result;
}
The usage example would be:
window.onload = function() {
var arrDivs = GetElementsStartingWith("div", "a");
for (var i = 0; i < arrDivs.length; i++) {
arrDivs[i].style.backgroundColor = "red";
}
};
Live test case.
In case you choose to use jQuery at some point (not worth for this thing alone) all the above code turns to single line:
$(document).ready(function() {
$('div[id^="a"]').css("background-color", "blue");
});
Updated fiddle, with jQuery.
No, you need a fixed id value for getElementById to work. However, there are other ways to search the DOM for elements (e.g. by CSS classes).
You can use querySelectorAll to get all divs that have an ID starting with a. Then check each one to see if it contains a number.
var aDivs = document.querySelectorAll('div[id^="a"]');
for(var index = 0, len = aDivs.length; index < len; index++){
var aDiv = aDivs[index];
if(aDiv.id.match(/a\d+/)){
// aDiv is a matching div
}
}​
DEMO: http://jsfiddle.net/NTICompass/VaTMe/2/
Well, I question myself why you would need to select/get an element, that has a random ID. I would assume, you want to do something with every div that has a random ID (like arranging or resizing them).
In that case -> give your elements a class like "myGeneratedDivs" with the random ID (if you need it for something).
And then select all with javascript
var filteredResults=document.querySelectorAll(".myGeneratedDivs").filter(function(elem){
....
return true;
});
or use jQuery/Zepto/YourWeaponOfChoice
var filteredResults=$(".myGeneratedDivs").filter(function(index){
var elem=this;
....
return true;
});
If you plan to use jQuery, you can use following jQuery selectors
div[id^="a"]
or
$('div[id^="id"]').each(function(){
// your stuff here
});
You will have to target the parent div and when someone click on child div inside a parent div then you can catch the child div.
<div id="target">
<div id="tag1" >tag1</div>
<div id="tag1" >tag2</div>
<div id="tag1" >tag3</div>
</div>
$("#target").on("click", "div", function() {
var showid = $(this).attr('id');
alert(showid)
});
getElementById() will return the exact element specified. There are many javascript frameworks including jQuery that allow much more powerful selection capabilities. eg:
Select an element by id: $("#theId")
Select a group of elements by class: $(".class")
Select subelements: $("ul a.action")
For your specific problem you could easily construct the appropriate selector.

javascript dropdown to change all dropdown in table

I have a requirement of changing all dropdown values in all the rows in a tale based on master dropdown. say someone selects "value 2" in dropdown1, dropdown2 values in all the rows in the table should show "value2".
function change(){
var cid = document.frm.locdropdown.selectedIndex;
document.frm.locdropdown2.selectedIndex = cid;
}
is the java script I use to change it but this changes only first row.
please help..
From your example code it looks like you've given the same ID to all your locdropdown2 elements? Maybe you should post an example of your table HTML. It's normal practice to give unique IDs to elements, so you may want to test the NAME attribute instead, but anyway something like the following should work:
function change() {
var cid = document.frm.locdropdown.selectedIndex;
var inputs = document.getElementsByTagName("input");
for (var i=0, l = inputs.length; i < l; i++) {
if (inputs[i].id == "locdropdown2")
inputs[i].selectedIndex = cid;
}
}
Another option is to loop through each row in the table. The following example assumes your locdropdown2 inputs are the only thing in the third column, but you can adapt to suit your actual layout:
function change() {
var cid = document.frm.locdropdown.selectedIndex;
var tableRows = document.getElementById("yourTableId").tBodies[0].rows;
for (var i=0, l=tableRows.length; i < l; i++) {
tableRows[i].cells[2].firstChild.selectedIndex = cid;
}
}
Note: I haven't actually tested any of that code, but it should be more than enough to get you started and you can tweak as needed. (You can use Google to learn about tBodies, rows, cells, firstChild, etc.)

Categories