How to get a value of data-attribute with jquery - javascript

I need to get the value of userid, data-attribute from a html table and put this value into a var, but I wanna to this action without click action.
<table id="tblList">
<tbody id="someTest">
<tr data-userid="801992084067">
<tr data-userid="451207954179">
<tr data-userid="310896831399">
<tr data-userid="863939754980">
<tr data-userid="1123542226482">
</tbody>
</table>
I have tried to do this like that, but the rowId is undefined.
var rowId = $("#someTest tr").last().attr("[data-userid"]");

Simply, you can manage data attribute & value in HTML tag using data() method of jQuery. Alternatively, you can use attr() method also,
var rowId = $("#someTest tr").last().data("userid");
Alternatively
var rowId = $("#someTest tr").last().attr("data-userid");
.data() method is used to store arbitrary data associated with the matched elements or return
the value at the named data store for the first element in the set of
matched elements.
Initial HTML
<button id="mybtn">MyButton</button>
Add data-attribute with value
$('button#mybtn').data('id',10);
Alternatively
$('button#mybtn').data('data-id',10);
Reproduced HTML
<button id="mybtn" data-id="10">MyButton</button>
Get value from data-attribute
alert($('button#mybtn').data('id')); //alerts 10
Alternatively
alert($('button#mybtn').attr('data-id')); //alerts 10
Change value of data-attribute
$('button#mybtn').data('id',15);
Alternatively
$('button#mybtn').attr('data-id',15);
Reproduced HTML
<button id="mybtn" data-id="15">MyButton</button>
Remove data-attribute
You can remove data attribute using removeData() method
$('button#mybtn').removeData('id');
Alternatively
$('button#mybtn').removeAttr('data-id');
Reproduced HTML
<button id="mybtn">MyButton</button>

only Remove [] :
var rowId = $("#someTest tr").last().attr("data-userid");
Final code :
<html>
<title>This is test</title>
<head>
</head>
<body>
<table id="tblList">
<tbody id="someTest">
<tr data-userid="801992084067">
<tr data-userid="451207954179">
<tr data-userid="310896831399">
<tr data-userid="863939754980">
<tr data-userid="1123542226482">
</tbody>
</table>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
<script>
$(document).ready(function(){
var rowId = $("#someTest tr").last().attr("data-userid");
alert(rowId);
})
</script>
</body>
</html>

you just have to remove the square brackets:
var rowId = $("#someTest tr").last().attr("data-userid");
$('#rowidOutputAttr').text(rowId);
var rowId = $("#someTest tr").last().data("userid");
$('#rowidOutputData').text(rowId);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<html>
<body>
<table id="tblList">
<tbody id="someTest">
<tr data-userid="801992084067">
<tr data-userid="451207954179">
<tr data-userid="310896831399">
<tr data-userid="863939754980">
<tr data-userid="1123542226482">
</tbody>
</table>
<div id=rowidOutputAttr></div>
<div id=rowidOutputData></div>
</body>
</html>
i also added en example with .data()

Related

Passing variable to a modal

Is it possible to pass a variable from anattribute to a modal. I need to use the value of the variable to return data from a*.php` function.enter code here
The call to the Modal with the record value in the data-id attribute.
Edit;
This will be Modal that will be displayed.
<div id="openModal" class="modalDialog">
<div>
X
<table border="1" width="600" height="500" cellpadding="5" cellspacing="0">
<tr>
<td>
$detail = Stuff->getDetails($_GET['data-id']);
</td>
</tr>
</table>
</div>
</div>
if you want access data-id you can use javascript / jquery to do that.
my suggestion is :
1. change the link to this :
Edit
2. in modal :
<tr>
<td id="place-data-id">
</td>
</tr>
3. in javascript access data id like this :
<script type="text/javascript">
$("#myModal").click(function(){
var myDataId = $(this).data('id'); // get data-id
$("#place-data-id").html(myDataId); // insert data id to td
$("#openModal").modal('show'); // showing modal
});
</script>

Multiple elements with same Id in Javascript

I have a case where a html file contains multiple elements with the same ID name.
The table row contains 5 columns of which I need to consider 2,3,4,5 columns data.
<tr id='total_row'>
<td>Total</td>
<td>%(count)s</td>
<td>%(Pass)s</td>
<td>%(fail)s</td>
<td>%(error)s</td>
<td> </td>
</tr>
I have the above code at several places in the file. I need to add the respective values using javascript.
An ID is unique in an html page. You can call it THE ID as well wrt a page. You cannot have same ID for two different tags in a single page. But you can use class instead of and ID. Know about it here
So your HTML can be like
<tr class='total_row'>
<td>Total</td>
<td>%(count)s</td>
<td>%(Pass)s</td>
<td>%(fail)s</td>
<td>%(error)s</td>
<td> </td>
</tr>
As an example with jquery you can do something like this,
<!DOCTYPE html>
<html>
<head>
<style>
</style>
</head>
<body>
<table>
<tr class="one">
<td></td>
<td></td>
</tr>
<tr class="one">
<td></td>
<td></td>
</tr>
<tr class="one">
<td></td>
<td></td>
</tr>
</table>
<script src="jquery-1.11.0.min.js"></script>
<script>
$(document).ready(function() {
$(".one").eq(0).find('td').eq(0).html("I'm tracked");
// get 1st tr and get first td
$(".one").eq(1).find('td').eq(1).html("I'm tracked");
// get 2nd tr and get second td
$(".one").eq(2).find('td').eq(0).html("I'm tracked");
// get 3rd tr and get first td
});
</script>
</body>
</html>
But I guess this approach can be tedious.
Id should be unique and if you use the same id, javascript code refers only the first element. but if you still want to use same id than you may try the below code:
$(function(){
$('[id="total_row"]').each(function(){//run for every element having 'total_row' id
var $this = $(this);
$this.find('td').eq(1).text() //to get second column data
$this.find('td').eq(1).text('dummy text') //to set second column data
});
});
You can use XHTML:
<p id="foo" xml:id="bar">
Through XHTML you can apply similar ID to multiple Controls.
Similar questions can be found here:
http://www.c-sharpcorner.com/Forums/
While duplicate IDs are invalid, they are tolerated and can be worked around. They are really only an issue when using document.getElementById.
I'll guess that the table looks like:
<table id="t0">
<tr>
<td>-<th>count<th>Pass<td>Fail<td>Error<td>
<tr>
<td>-<td>1<td>1<td>0<td>0<td>
<tr>
<td>-<td>1<td>1<td>0<td>0<td>
<tr id='total_row'>
<td>Total<td><td><td><td><td>
<tr>
<td>-<td>1<td>1<td>0<td>0<td>
<tr>
<td>-<td>1<td><td>1<td>0<td>
<tr>
<td>-<td>1<td><td>0<td>1<td>
<tr id='total_row'>
<td>Total<td><td><td><td><td>
</table>
<button onclick="calcTotals();">Calc totals</button>
If that's correct, then a function to add each sub–section can be like:
function calcTotals(){
var table = document.getElementById('t0');
var rows = table.rows;
var row, totals = [0,0,0,0];
// For every row in the table (skipping the header row)
for (var i=1, iLen=rows.length; i<iLen; i++) {
row = rows[i];
// If it's a total row, write the totals and
// reset the totals array
if (row.id == 'total_row') {
for (var j=0, jLen=totals.length; j<jLen; j++) {
row.cells[j+1].innerHTML = totals[j];
totals[j] = 0;
}
// Otherwise, add values to the totals
} else {
for (var k=0, kLen=totals.length; k<kLen; k++) {
totals[k] += parseInt(row.cells[k + 1].innerHTML) || 0;
}
}
}
}
In addition to using classes, which works but feels kind of icky to me, one can also use data-* attributes.
<tr class='total_row' data-val-row-type="totals-row">
<td>Total</td>
<td>%(count)s</td>
<td>%(Pass)s</td>
<td>%(fail)s</td>
<td>%(error)s</td>
<td> </td>
</tr>
Then, in your script (jQuery syntax -- querySelectorAll has a similar syntax)
var $totalsRows = $("[data-val-row-type='totals-row']);
When you are in a team with a separate UI designer, this keeps the UI guy from ripping out and changing your class names to fix the new design layout and it makes it quite clear that you are using this value to identify the row, not just style it.

how to dynamically add $scope in Angular

here is my HTML:
...
<table class="tickerTable">
<thead>
<th>Symbol</th>
<th>Accts</th>
</thead>
<tbody ng-repeat="ticker in tickers">
<tr ng-click="showTrades(ticker)">
<td >{{ticker.Ticker}}</td>
<td>{{ticker.TradeCount}}</td>
</tr>
<tr ng-show="currentItem == ticker">
<td colspan="2">{{trades}}</td>
</tr>
</tbody>
</table>
here is the controller:
$scope.showTrades = function(ticker){
$scope.trades = {};
$scope.currentItem = ticker;
$scope.trades = "this is the result of a rest call using the params from $scope.ticker";
};
the table is populated with many rows. for each row i add a blank row that is hidden by default.
when the row is clicked the hidden row displays dynamically generated content that is returned from a rest call made with the params of that particular table row's "ticker" object. the result is injected into $scope.trades and displayed in the now visible TR.
The problem: {{trades}} is being populated in every hidden row along with the revealed row. I only want it to load in the revealed row.
solution
http://plnkr.co/edit/qFZyeuIbt6z5dYEFFHzr?p=preview
In your plnkr you are using ng-if.
There is a bug relatead to ng-if in tables #3104 which will cause problems for you. Maybe you can use ng-show instead as you did in the posted HTML?
Next you may add the trades to the containing ticker. So you display the trades belonging to the current ticker. Then only the selected ticker row will have trades.
<!doctype html>
<html ng-app='portfolio'>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.0.5/angular.min.js">
</script>
<script src="script.js"></script>
</head>
<body>
<table ng-controller = "TickerListCtrl">
<thead>
<th>Symbol</th>
</thead>
<tbody ng-repeat="ticker in tickers">
<tr ng-click="showTrades(ticker)">
<td>{{ticker.Ticker}}</td>
</tr>
<tr >
<td ng-show="currentItem == ticker" colspan="2">{{ticker.trades}}</td>
</tr>
</tbody>
</table>
</body>
</html>
$scope.showTrades = function(ticker){
ticker.trades = "this is trades for ticker: " + ticker.Ticker;
$scope.currentItem = ticker;
};
Here is a fork of your plnkr with the described changes.

extract integer from td

if I have a simple html table:
<table>
<tr>
<th>header</th>
</tr>
<tr>
<td class="count test">423</td>
</tr>
</table>
how do I extract the integer from the td so that I can act on it?
the following code returns undefined:
function changeCount(){
var count = $("td.count.test").val();
alert(count);
}
changeCount();
complete html:
<html>
<head>
<title>Creation of array object in javascript</title>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js" ></script>
<script language="javascript" >
function changeCount(){
var count = $("td.count.test").text();
console.log(count);
}
changeCount();
</script>
<style>
td{width:200px;text-align:center;}
</style>
</head>
<body>
<table>
<tr>
<th>header</th>
</tr>
<tr>
<td class="count test">423</td>
</tr>
</table>
</body>
</html>
Not .val() for a <td>, but .text().
function changeCount(){
var count = $("td.count.test").text();
alert(count);
}
Note that if there are multiple such <td> elements, that'll return the contents of the first one in the DOM.
The .val() method is for getting the "value" attribute of <input>, <select>, and <textarea> elements. In either case, the DOM access will give you a string. If you need to do computation with the value, then it should be coerced to be a number via parseInt() or one of several other tricks.
The problem is you are trying to access stuff through JavaScript which is not available in the DOM tree at the time your function is executed. You need to make sure changeCount() is fired after the whole DOM tree has been loaded or at least after the element that is required by your function is part of the document DOM tree.
<html>
<head>
<title>Creation of array object in javascript</title>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js" ></script>
<script language="javascript" >
function changeCount(){
var count = $("td.count.test").text();
console.log(count);
}
$(document).ready(function(){
changeCount();
});
</script>
<style>
td{width:200px;text-align:center;}
</style>
</head>
<body>
<table>
<tr>
<th>header</th>
</tr>
<tr>
<td class="count test">four twenty three</td>
</tr>
</table>
</body>
</html>

Replacing the content of a <td> with <tr> id and <tr> index

I have a table structure like this
<table>
<tr id="tr_1">
<td>Content1</td>
<td>Content2</td>
<td>Content3</td>
<td>Content4</td>
</tr>
<tr id="tr_2">
<td>Content5</td>
<td>Content6</td>
<td>Content7</td>
<td>Content8</td>
</tr>
<tr id="tr_1">
<td>Content11</td>
<td>Content12</td>
<td>Content13</td>
<td>Content14</td>
</tr>
<tr id="tr_2">
<td>Content15</td>
<td>Content16</td>
<td>Content17</td>
<td>Content18</td>
</tr>
</table>
I am passing the row index(2) and <tr> id (tr_1) to a js function for replacing the content of 2nd 3 rd td's in that row.
i have a jquery funcion
document.getElementById('tr_1').getElementsByTagName("td")[2].innerHTML = '<td>New html</td>';
But that this replacing the first tr html. How we can replace with id tr_1 with index 2
if you are using jquery .. then this should work..
$("#tr_1 td").eq(2).html("<td>New html</td>");
here is the link to eq()...
http://api.jquery.com/eq/
Try this
<script language="javascript" type="text/javascript" src="jquery-1.8.2.js"></script>
<script language="javascript" type="text/javascript">
$(document).ready(function() {
$('#tr_1 td:eq(1)').html('Replacing Content of td 2');
$('#tr_1 td:eq(2)').html('Replacing Content of td 3');
});
</script>
You don't have unique ids. Is is essential for JavaScript that the DOM working with unique ids.
In jQuery you can use this to target the to tr elements with id set to tr_1:
$("tr[id=tr_1]");
To get the second element in these tr's you will need to use jQuery.fn.each
$("tr[id=tr_1]").each(function() {
$("td", this).eq(1).html("new html");
});
Try this:
jQuery("[id=tr_1]:eq(1) td:eq(1)").html("new html");
Note you need to insert the jquery plugin:
http://jquery.com/download/

Categories