Dynamically appending value to a link produces wrong results - javascript

I have this simple table containing user details (user id in the provided example). There's a link available for each record. This link (in real) is dynamically generated based on no.of records. each record will have a link. And upon clicking this link, that corresponding user's id has to be passed (appended) to another link (which I refer as user link in the example).
My HTML Code:
<a id="abc" href="aa/">User Link</a>
<hr>
<table border="1">
<tr>
<td><a id="xyz" data-userid="100" href="#">first user</a></td>
<td>100</td>
</tr>
<tr>
<td><a id="xyz" data-userid="200" href="#">second user</a></td>
<td>200</td>
</tr>
<tr>
<td><a id="xyz" data-userid="300" href="#">third user</a></td>
<td>300</td>
</tr>
</table>
jQuery:
$(document).on('click','#xyz',function(e){
var uid = $(this).attr('data-userid');
$('#abc').attr('href',$('#abc').attr('href')+uid);
});
I am appending the user id to the User Link based on the above jQuery code.
This is what I am trying to achieve:
<a id="abc" href="aa/100">User Link</a> for first user
<a id="abc" href="aa/200">User Link</a> for second user
<a id="abc" href="aa/300">User Link</a> for third user
which I get partially.
Issue:
When I click a second link after clicking a previous one, both the values are appending to the end of User Link.
For example, If I click first user initially, User Link becomes
<a id="abc" href="aa/100">User Link</a>
and then if I click second user, User Link becomes
<a id="abc" href="aa/100200">User Link</a>
and so on...which is not what I am trying to get.
Where did I make mistake???
FIDDLE.
P.S: use Inspect Element from browser to see this mess in live action.

Few issues:
Change IDs to classes in your markup class="xyz" and in the click handler .xyz
Store the initial href value to access it on subsequent clicks.
Updated Fiddle
var initHref = $('#abc').attr('href')
$(document).on('click','.xyz',function(e){
e.preventDefault(); // Prevent default action of `<a>`
var uid = $(this).attr('data-userid'); //or $(this).data('userid');
$('#abc').attr('href',initHref+uid);
});

You may want to store the href of the user link and use it later to append the new value, like below.
P.S. please change ID xyz to class
Demo#Fiddle
$(function() {
var userLink = $('#abc')[0];
var linkHref = userLink.href;
$(document).on('click','.xyz',function(e) {
e.preventDefault(); //Cancels the default behaviour
var uid = $(this).attr('data-userid');
userLink.href = linkHref + uid;
});
})

The same way you used data-userid, you may use data-href in the first link to store your initial and unmodified url.
And then use something similar to:
$(function() {
$(document).on("click", ".xyz", function (e) {
e.preventDefault();
var userLink = $("#abc");
userLink.attr("href", userLink.attr("data-href") + $(this).attr("data-userid"));
});
});

First and foremost, do not have multiple elements with the same id. See
Why is it a bad thing to have multiple HTML elements with the same id attribute?
Second, store the initial href in a var like
var initialHref = $('#abc').attr('href');
and change
$('#abc').attr('href',$('#abc').attr('href')+uid);
to
$('#abc').attr('href',initialHref+uid);
See it working here

Related

How to change href of links within multiple instances of an element with jQuery depending on the content

Here's an example element that appears multiple times on a page
<td class=" market all">
123
</td>
The other elements change the param so other links may look like
<td class=" market all">
456
</td>
I'm looking for a way to use jQuery (because it's already there on the site and used for other stuff) to change the link but keep the param. So the first example would look like this
<td class=" market all">
123
</td>
I would prefer to not just replace the URL part but read either the param or the text that is linked and then use it to put the new URL in there.
So you want to replace linktosomesite to otherurl keeping other params same.
$(".market a").attr("href", function(){
var param = this.innerHTML;
return "linktosomesite?param="+param;
});
jQuery(".market a").attr("href", function(){
jQuery(this).attr("href", "otherurl?"+ jQuery(this).attr("href").split("?").pop());
})

How to Copy and Insert Table Row using jQuery / JavaScript

I have a table with the following structure
<table id='table1'>
<tbody>
<tr id='rowa'>
<td><select>....</select></td>
<tr>
...
<tr id='rowx'>
<td>....</td>
</tr>
...
<tr id='rowz'>
</tr>
</tbody>
</table>
What I want to do is on clicking of a button, I want to copy the rowa and insert it before rowx.
What I am currently doing is
<script type='text/javascript'>
function copyRow() {
var row = $('#rowa').clone();
$('#rowx').before(row);
}
</script>
It seems to show the newly constructed row before the rowx but when I try to access that new row, it does not work. what I mean by does not work in that the select input item does not behave like a select item, it behaves like the static text.
elsewhere on the page I have
<a href='javascript:copyRow()'><img src='images/copyrow.png' title='Copy Row' /></a>
Sorry! I should have made it clear that the copyRow is being called when the user clicks on a link somewhere else on the page.
Check this http://jsbin.com/owivin/1/.
JS:
$(document).ready(function(){
$("#rowx").before($("#rowa").clone());
});
Your code's not working because you never call copyRow(). I put it in the document.ready() so that it would run as the document gets ready!

Table Row onclick - change page, or open new tab

I have a table with rows, that when clicked, take the user to a page with more detailed information about the item that row was describing. Unfortunately, it always changes the current page, and our users would like to be able to middle-mouse/control click the rows in order to open a new tab if they want to. This choice is available with normal links, but not with my onclick it seems. An example is shown below:
<html>
<body>
<table border='1'>
<tr onclick='window.open("http://www.google.com")'>
<td>Open Another Window</td>
</tr>
<tr onclick='location.href="http://www.google.com"'>
<td>Change Current Page</td>
</tr>
</table>
</body>
</html>
What is the best way to simulate a normal link with an onclick event so the behaviour will be the same across different os/browsers, which I believe have different bindings for what triggers opening a link in a new tab.
This works for me:
<tr onclick="window.open('http://www.google.com','_blank')">
I just stumbled across this question because I was also looking for a solution. Here is a possible solution. It opens the page normally when clicked normally and in a new tab if the middle button is used.
You can add a table class (like clickable-rows) to easily apply this behavior to your tables. Then add a data attribute (like data-href) with the link.
<!DOCTYPE html>
<html>
<body>
<table>
<tr class="clickable-row" data-href="http://www.google.com">
<td>Clickable row 1</td>
</tr>
<tr data-href="http://www.google.com">
<td>Non clickable row</td>
</tr>
<tr class="clickable-row" data-href="http://www.google.com">
<td>Clickable row 2</td>
</tr>
</table>
<script>
// loop through the table rows with the clickable-row class, and turn them into clickable rows by
// setting the cursor to a pointer, and adding a mousedown listener to open in the current page
// if left-clicked, or open in a new tab if middle-clicked
let rows = document.querySelectorAll("tr.clickable-row");
rows.forEach((clickableRow) => {
clickableRow.style.cursor = "pointer";
clickableRow.addEventListener("mousedown", function(e) {
e.preventDefault();
var href = this.getAttribute('data-href');
if (e.button === 1)
{
window.open(href, "_blank");
}
else if (e.button === 0)
{
window.location = href;
}
})
});
</script>
</body>
</html>
Instead of handling the click event of the table row, use an anchor tag. The default behaviour for Ctrl+click for anchors is to open the URL in the href attribute in a new window or tab. If you want a new tab or window opened without the Ctrl button, you can use the target attribute of the anchor as well.
<td>open another window or tab</td>
<tr onclick="window.open('./putyourlink.php')"> it's still work to me also but pls put '_blank' like another answer it's good more </tr>

Print each loop of <c:foreach> individually using javascript

Currently I'm printing the whole page with print icon using following code:
<a href="javascript:window.print()">
<img src="images/printIcon.gif" alt="Print the Records" width="40" height="40" border="0" />
</a>
I am reading a list of objects in JSP and displaying the object details using <c:foreach>.
I want to display a print icon beside details of each object and print(to external printer) that individual object details only, when clicked on it. The whole page is in single div.
I'm not sure whether this can be done or not. Can I control the each loop using some sort of ID?
Edit:
Example:
<c:forEach var="case" items="${distributions}">
<table>
<tr>
Print case details
</tr>
</table>
</c:foreach>
If I have 10 distributions, I get 10 tables so want a print icon beside each table and when clicked on it, print that individual table only.
I have not done the following but theoretically it should work:
1) define a print stylesheet, with:
body.detail-print .detail-item{display:none}
body.detail-print .detail-item.current{display:block}
2) define an event listener, e.g. with jQuery
$(".detail-item .print").click(function(e) {
$("body").addClass("detail-print");
$(this).closest(".detail-print").addClass("current");
window.print();
});
This should only print what is visible in your print stylesheet.
The only problem I see here: If someone wants to print the whole page afterwards, the browser will only print the last selected item. You could use a setTimeout to reset the classes. I have no better idea for now...
In your block you could put the data in a td then use the method described in this post to print the contents of that td.
<script type="text/javascript">
$(function(){
$(".printable").each(function(){
var $td = $(this);
var $printIconTD = $('<td><img src="images/printIcon.gif" alt="Print the Records" width="40" height="40" border="0" /></td>');
$td.parent().append($printIconTD);
$printIconTD.click(function(){
Popup($td.html());
});
});
});
</script>
....
<c:forEach var="case" items="${distributions}">
<table>
<tr>
<td class="printable">Print case details</td>
</tr>
</table>
Only problem with this solution is god and everyone has pop-ups disabled, so you will have to put a notice of sorts on the page letting users know
A different way to what has been suggested would be to reload the page showing only the selected object and then call the printer dialog (e.g. on document load). So the printer icons next to the objects could link to the same page and pass it a parameter that you'll be printing and the ID of the object that you want to print.

jQuery Code on <td> with ajax to extract a column from a table

I have a table of banned IPs. The first column holds the IPs, the second one has the timestamp and the third the action links. I want to make an ajax call when "Remove Ban" is clicked on the link. For that I need the IP address from the first column. But somehow, this isn't working.
Here are the codes (You can check it on jsfiddle.net)
<tr>
<td class="ip">192.168.1.1</td>
<td class="centered">August 10, 2011</td>
<td class="right action_td">
<a class="action ban remove" href="javascript://">Remove Ban</a>
</td>
</tr>
(This is just a <tr>. Other elements of the table removed.)
The js:
$(".action.ban.remove").live('click', function(){ // remove ban
ip = $(this).parent("td.right").siblings("td.ip").html();
alert(ip);
});
Instead of 192.168.1.1, it alerts with "null". Am I doing it wrong?
update okay, I figured out the problem. I had another handler attached to it which was creating the problem. Foolish of me. :-\
Change it to:
ip = $(this).parent().siblings("td.ip").text();
http://jsfiddle.net/sRRn9/
Just needed a table element to wrap the table row. See here.
$('.remove').click(function(e){
e.preventDefault();
alert($(this).parent().prev().prev().html());
});
http://jsfiddle.net/6VFm5/
Try this
$(".remove").live('click', function(){ // remove ban
ip = $(this).parent("td.right").siblings("td.ip").html();
alert(ip);
});
Working demo

Categories

Resources