How to access outer innerHTML of some nested div in javascript function - javascript

To keep it simple, I have below html code:
<div class = "customers" data-popover="true" data-html=true
data-content="
<table>
<c:forEach items="${element.first}" var="btnVal" varStatus="loop">
<c:if test="${not loop.first}">
<tr> <button onclick='setTestname(innerHTML)' class='btn btn-primary'> ${btnVal}</button> </tr>
<tr>&nbsp</tr>
</c:if>
</c:forEach>
</table>
">
<br>${element.first.get(0)}
</div>
Here I am trying to use the value of the clicked button using below javascript function:
function setTestname(test){
test = test.toString().trim();
document.getElementById('hiddenCostomer').value=test;
setLogfilename(test);
document.getElementById('form1').submit();
}
Above code works fine, but I am not sure abt how to access value of div as well. I want to pass two values to setTestname
${btnVal}
${element.first.get(0)}
How to get value of ${element.first.get(0)}
EDIT : I want the exact value of div on which the button is clicked , not the entire DOM.

You should add the value to a data attribute and then get it, something like this:
HTML:
<div id="myid" data-mydata="${element.first.get(0)}"></div>
JS:
document.getElementById("myid").getAttribute("data-mydata");

You can pass the class name of the div you want to fetch contents of.
setTestName(innerHTML, 'customers')
Then use customers as:
document.getElementsByClassName('customers')
which will return the DOM.

<c:set var="BtnIndex" value="${0}"/>
then I set
<tr> <button onclick='setTestname(innerHTML,${BtnIndex + 0})' class='btn btn-primary' > ${btnVal} ${BtnIndex + 0}</button> </tr>
I set one counter and assigned each div a unique number. Later , i fetched the value from array of class customers from that unique counter as index
function setTestname(test,btnIndex){
test = test.toString().trim();
btnIndex = btnIndex.toString();
var elemArray = document.getElementsByClassName('customers');
for(var i = 0; i < elemArray.length; i++){
elemArray[i].id = i;
}
var elem = document.getElementById(elemArray[btnIndex].id);
var mainDir = elem.innerHTML;
}
It worked !!! Bingo

Related

How to obtain text of a <td> element from another <td> element with jquery

I am trying to use a button inside a table division to set a variable as the same value as another division in the same row, but whenever I run my code (below), it returns the value of all the table divisions concatenated together. I am unsure why this was happening, so I replaced '.children()' with 'childnodes[0]' to try and get only the first name, but this just doesn't work and I don't why.
My html looks like this:
<table>
<tr>
<td>John</td>
<td>Doe</td>
<td><button>Get First Name</button></td>
</tr>
</table>
And my Javascript is this:
$(document).ready(function(){
$("button").click(function(){
var first = $(this).closest("tr").childNodes[0].text();
alert(first)
})
});
set a variable as the same value as another division in the same row
there are lots of possibilities for this, here are some (with the most useful first (opinion based))
$("button").click(function() {
var first = $(this).closest("tr").find("td:first").text();
var first = $(this).closest("tr").find("td").first().text();
var first = $(this).closest("tr").find("td").eq(0).text();
var first = $(this).closest("tr").children().first().text();
var first = $(this).closest("tr").children().eq(0).text();
var first = $(this).closest("td").siblings().first().text();
});
it returns the value of all the table cells concatenated together
https://api.jquery.com/text
Get the combined text contents of each element in the set of matched elements, including their descendants, or set the text contents of the matched elements.
because you're passing the "tr" to text() it gets the text of all the cells (tds) and their content etc and combines them as one, so you need to limit to the first as you've attempted.
however .childNodes[0] can only be applied to a DOM element/node, while $(this).closest("tr") gives you a jquery object/collection, which doesn't have .childNodes property.
So the jquery equivalent would be to use .children().eq(0).
You could use class identifiers to get information you need as well.
<table>
<tr>
<td><span class="first-name">John</span></td>
<td><span class="last-name">Doe</span></td>
<td>
<button class="btn-get-data" data-class="first-name">Get First Name</button>
<button class="btn-get-data" data-class="last-name">Get Last Name</button>
</td>
</tr>
</table>
$(document).ready(function() {
$(".btn-get-data").click(function() {
$btn = $(this);
$tr = $btn.closest('tr');
var first = $tr.find('.' + $btn.attr('data-class')).html();
alert(first);
})
});
If you make the button click generic like so, you can add additional buttons on the page and use that to get the class within that row.
Here is a working fiddle example: https://jsfiddle.net/b1r0nucq/
you could find the :first child and get his html(), as below:
$(document).ready(function() {
$("button").click(function() {
var first = $(this).closest("tr").children(":first").html();
alert(first)
})
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table>
<tr>
<td>John</td>
<td>Doe</td>
<td><button>Get First Name</button></td>
</tr>
</table>

Button click only works on one button out of appended list of buttons

JQUERY
i have 4 buttons that are pulled from a database and appended to a list, but only this first appended button works. All the rest wont do anything.
function getaplist(){
$.getJSON('/geticsassignments',
function(data){
console.log(data)
for (var i = 0; i < data.length; i++){
var assign = ("<tr><th><button class='btn btn-warning' id='getaptext'
value=''>"+ data[i].aparatus +"</button></th></tr>")
$('#aptbody').append(assign)
}
$('#getaptext').on('click', function(){
$("#getaptext").removeClass("btn btn-warning").addClass("btn btn-danger")
var aparatus = $(this).text()
alert(aparatus)
$.getJSON('/sendap',{
}, function(data){
console.log(data)
})
})
})
}
getaplist()
<div id='aplist'>
<table class="table">
<thead>
<tr>
<th><p style="text-align: center;">Aparatus</p></th>
</tr>
</thead>
<tbody id='aptbody'>
</tbody>
</table>
</div>
There are two problems with your code.
1- ID must be unique on the DOM.
2- You're trying to add event listeners on dynamically created elements which doesn't work the way you are trying to do.
Solution :
First Make sure the id are unique. And add event listeners with class name for example
$(document).on('click','.btn',function(){
$(this).removeClass("btn btn-warning").addClass("btn btn-danger")
var aparatus = $(this).text()
...
})
This will work for all the elements event which are added dynamically on your page
You're using the same id, getaptext, for every button. The id attribute has to be unique. You'll have to make the ids different, or use something else like a common name or class.

How to get html td cell value by Javascript

I am trying to get the information from my table td's, using javascript. How can i achieve this? I have tried and failed, because i do not exactly understand the JS. So far, i have managed to get one of them to work, which is 'id' but thats just getting info from the db directly, the td values ive been unable to.
echoing the vals in my php update page shows the id val being passed successfully, but none others.
EDIT
Per your last comment I can recommend you use an event listener on all <td> tags and this way you can just get the relevant text of the specific <td> that the user clicked:
var tds = document.querySelectorAll('td');
for (var i = 0; i < tds.length; i++) {
var td = tds[i];
td.addEventListener('click', function(){
console.log(this.innerText)
});
}
<table>
<tr>
<td class="awb">I am the first awb</td>
<td class="awb">I am the second awb</td>
</tr>
<tr>
<td class="differentClass">I am the first differentClass</td>
<td class="differentClass">I am the second differentClass</td>
</tr>
</table>
You are approaching this all wrong...
Instead of this:
var awbno = String(tr.querySelector(".awb").innerHTML);
Do this:
var awbno = document.querySelector(".awb").innerHTML;
Here is a snippet:
var awbno = document.querySelector(".awb").innerHTML;
console.log(awbno);
<table>
<tr>
<td class="awb">Test Text inside a td tag</td>
</tr>
</table>
in order to get the contents of any element using class
let value = document.querySelector('.className').innerHTML;
in order to get the contents of a specific TD
let value = document.querySelector('td.className');

pass value of cell from table row to variable

I am attempting to pass the value of the data-count cell to a variable using either jQuery or Javascript. How can I do it? Here is the HTML:
edit I should have stated that the value of id-offer=186000 is not constant and differs from page to page
<table class="vis" id="own_offers_table">
<tbody>
<tr class="offer_container " id="offer_186000" data-id="186000" data-count="30" data-village="" data-wanted_wood="900" data-wanted_stone="0" data-wanted_iron="0">
Thanks again for any help
var count = $('#offer_186000').data('count');
Setting the value:
$('#offer_186000').data('count', value);
If you can't use it's id
$('#own_offers_table').find('.offer_container').data('count');
For Setting the value:
$('#own_offers_table').find('.offer_container').data('count', value);
Get the tr using getElementById or by the class using querySelector
Get the data- attribute value using dataset
//var count = document.getElementById('offer_186000').dataset.count;
var count = document.querySelector('.offer_container').dataset.count;
alert(count);
<table class="vis" id="own_offers_table">
<tbody>
<tr class="offer_container" id="offer_186000" data-id="186000" data-count="30" data-village="" data-wanted_wood="900" data-wanted_stone="0" data-wanted_iron="0">
</tr>
</tbody>
</table>
For Setting Value(Jquery Command):
$("#offer_186000").attr('data-count').val('30');
For getting value(Jquery Command):
var value = $("#offer_186000").attr('data-count').val();
alert(value);

Accessing/Changing Information in Tables with Javascript

I am using greasemonkey to change the functionality of an existing web page.. If you aren't familiar with greamonkey it doesn't really matter.. the main information is that the current code for the existing page looks like this:
<div id="sqlDiv" class="sqlBorderDiv" style="display: none;">
<div class="reportBorderDiv">
<table class="reportTable">
<tbody>
<tr>
<tr class="reportRow1">
<tr class="reportRow2">
<td>55555</td>
<td>Bruce Wayne</td>
<td>12456789123</td>
<td>2013-12-17</td>
<td>Batman</td>
<td>Superhero</td>
<td>Menace</td>
<td>123246</td>
<td>12456</td>
<td>123456</td>
<td></td>
</tr>
</tbody>
</table>
</div>
I want to run a script on it that will make the first cell of any reportRow into a hyperlink using the information in that cell. I am trying with a script like below, but something is going wrong and I have no idea what. ( I am really new into javascript). Thank you for any suggestions!!
var anchor = null;
var container;
var rows;
var cells;
var demoNum;
var linkString = "https://somewebsite.com/";
container = document.getElementById('sq1Div');
rows = container.getElementsByTagName("tr");
for (var i = 0; i < rows.length; i++) {
var className = rows[i].getAttribute("class");
if ( className == "reportRow1" || className == "reportRow2" ) {
anchor = rows[i];
cells = anchor.getElementsByTagName("td");
demoNum = cells[0];
linkString = linkString + demoNum;
cells[0] = <a href = linkString > demoNum </a>;
}
}
The problem is in the line
cells[0] = <a href = linkString > demoNum </a>;
That should be in a string, like this:
cells[0]="<a href='"+linkstring+"'>"+demonum+"</a>";
To put that back in the first row of the table, you can do this
row[i].childNodes[0].innerHTML=cells[0];
Also, you have document.getElementById("sq1div"), instead of "sqlDiv"
document.getElementById('sq*1*Div');
incorrect indetifier, you are using number "1" instead of letter "l"
and of course as wrote scrblnrd3 line with new link builds incorrect
It seems to me the HTML has unmatched tags, could this somehow confuse greasemonkey?

Categories