Passing an onClick javascript function when crafting an mvc link - javascript

I have some hyperlinks which have a common class name. This hyperlinks are created dynamically on my web page with mvc asp.net helpers.
Right now I want to write a script that would determine the particular link that was clicked and execute a javascript function when this link is clicked.
My code is below.
My mvc code that generate the link, please take note of the function passed updateWaitingState(this)
td> #AntiXss.HtmlEncode(customerchatname) #Html.ActionLink("chat", "StartChat", new { threadid = avisitor.ThreadID, email = AntiXss.HtmlAttributeEncode(email) }, htmlAttributes: new { target = "_blank", #class = "chat", operatorid = avisitor.OperatorID, connectionid = AntiXss.HtmlAttributeEncode(connectionid), threadid = avisitor.ThreadID, onClick = "updateWaitingState(this);" })</td>
My javascript function for this link is below, JQuery has been called above the link.
<script type='text/javascript'>
function updateWaitingState(sender) {
var parentid = $(sender).attr("data-parentid");
alert(parentid);
}
</script>
The problem is that the browser generates an undefined for the sender object. I have tried for hours debugging, I cant seem to find the problem.
When I run my code in the browser. The html looks like this
<tr id="kayode#yahoo.com">
<td> kayode <a class="chat" connectionid="135976e6-799b-4cda-a764-a00f7110d515" href="/Visitor/StartChat?threadid=3&email=kayode%40yahoo.com" onclick="updateWaitingState(this);" operatorid="1" target="_blank" threadid="3">chat</a></td>
<td>271.0.0.1</td>
<td>Waiting</td>
<td></td>
<td>9/13/2014</td>
<td>04:15:18</td>
<td>00:00:10</td>
<td>271.0.0.1</td>
</tr>

Is not sender that undefined, its the value of parentid because the html for your action link does not have a data-parentid attribute. Modify the html to
#Html.ActionLink(..., htmlAttributes: new { ... data-parentid="SomeValue", onClick = "updateWaitingState(this);" })

Give anchor tag a unique id say 'a1' and try this :
document.getElementById('a1').addEventListener('click', function(e){
e.preventDefault();
alert($(this).data('parentid'));
});
DEMO
EDIT :- if you want to add event listener on class then do as :
document.querySelector('[class=chat]').addEventListener('click', function(e){
e.preventDefault();
alert($(this).data('parentid'));
});
DEMO
OR Try Pure Jquery Approach :-
$("a[class='chat']").click(function(e){
e.preventDefault();
alert($(this).data('parentid'));
});
and make sure that there is a attribute i.e data-parentid in your anchor tag.

I had to correct this html that I generated. The problem was not from the javascript rather the html.
chat
This solved the problem. Thanks alot for all your contributions. I really appreciate !!!!.

Related

jQuery: Change all href values dynamically

I've been looking for a question like this but none of them answer my question.
Please forgive me as I sometimes lack the ability to explain myself.
I have a page in sub1.domain.com where all links are formatted as
<a href="/link?param=whatever">
and I'm using jQuery to change the base domain to sub2.domain.com before the /link part that's different to the host to all hrefs on the page. I found this snippet while researching the issue. This is the code:
$('a').each(function() {
$(this).attr("href", function(index, old) {
return old.replace("/link", "https://sub2.domain1.com/link");
});
});
And it works like a charm for static links but the thing is that the page is a search results page that dynamically loads new results even after the page has loaded.
How do I make it dynamic so that all links that are loaded by the search, are modified by this script automatically? In other words, how do I apply this script to links that appear after the page has loaded and new results are cominig in?
base href will not work in this instance as it somehow breaks the whole page.
Thank you.
You could actually bind this event to a click. So when clickinng the link it will run this function and change the link. This would then change any new link also as long as this is bound to a parent or the document for example below
$(document).on('click', 'a', function(e){
e.preventDefault();
var link = $(this).attr( 'href' );
link = link.replace("/link", "https://sub2.domain1.com/link");
window.location.href = link;
});
Welcome to SO. I'd advise you to create a custom event and trigger it on any search or any other action you need. This approach is going to provide you a good flexibility and readability.
const table = $('#table');
let counter = 1;
$('#btn').on('click', function() {
const row = $('<tr>');
const cell = $('<td>');
const link = $('<a>', {
href: '/linktest',
text: 'Test link ' + counter++
});
cell.append(link);
row.append(cell);
table.append(row);
table.trigger('table.updated'); //triggering custom event
});
table.on('table.updated', function() { //custom event handler
$('#table a').each(function() {
$(this).attr('href', '/whatever_you_want');
});
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table id='table'>
<tr>
<td><a href='/link'>Test link</a></td>
</tr>
</table>
<button type='button' id='btn'>
Add row
</button>
I wonder why no one of the other answers mentions that jQuery allows us to target all element with the same querySelector such for example if you want to target all aHref Elements you can just add a space after the letter a just like $("a ")!
const newLink="https://www.mynewLink.com";
$("a ").attr("href", newLink);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<a target="_blank" href="https://www.google.com">Google</a>
<br><br>
<a target="_blank" href="https://www.facebook.com">Facebook</a>

Java HtmlUnit click on anchor link does not work. How do I get the new page?

I'm trying to click on a "More" anchor tag on a website using HtmlUnit in order to expand a list until the more anchor tag does not exist.
page = client.getPage(url);
HtmlAnchor anchor;
while((anchor = page.getFirstByXPath("//a[#class='load-more list']")) != null) {
page = (HtmlPage) anchor.getPage();
}
I've also tried page = anchor.click();
System.out.println(anchor) shows
HtmlAnchor[ a
href="/guideitem/list/?id=g407&requestType=browse&filter=ZmlsdGVyPXMlM2FmcmVlJmxpbWl0PTMw"
class="load-more list" data-hijax="false" ]
I will continue to look into this problem and post what I find here.
I've had a somewhat similar problem, hope this helps.
It "solved itself" after we disabled CSS on the WebClient:
webClient.getOptions().setCssEnabled(false);
My anchor was:
<div class="my-anchors-parent-class"/>
Search
</div>
It had some JQuery attaching the .click() handler to it, who acted based on the 'class' property of my anchor's parent:
$('.my-anchor's-parent-class').each(function () {
$(this).children('a').click(function () {
// if parent has another given class appended, call .myFunction(this)
// else, call other function
});
});
When we reenable the CSS, the .click() is broken again.

CasperJS click is leads to error even when the element exists

I'm trying to click on a logout button, which I have retrieved from the current page. I successfully got the id of the logout link. But when I click on it, an error occurs
Cannot dispatch mousedown event on nonexistent selector
function getLogoutId()
{
var logoutid = "";
$(document).find("a").each(function(key,value){
var id = $(this).attr("id");
if(id.toLowerCase().indexOf("logout") > -1)
{
__utils__.echo("insidelogout" + id);
logoutid = id;
}
});
return logoutid;
}
var logoutid = this.evaluate(getLogoutId);
fs.write("logout.txt", this.getHTML(), 'w');
this.thenClick("#"+logoutid, function(){});
I have written the html content to a file, in which I checked for the id and it is there. The id attribute in question looks like this:
et-ef-content-ftf-flowHeader-logoutAction
I see nothing wrong with your code aside from strange usage of jQuery.
You can try other CSS selectors for clicking:
casper.thenClick("[id*='logout']"); // anywhere
or
casper.thenClick("[id$='logoutAction']"); // ending
or
casper.thenClick("[id|='logoutAction']"); // dash-separated
Maybe it is an issue with the code that follows the shown code. You can try to change thenClick to click.
Have you tried using just this.click("#"+logoutid);?
Also have you considered using jQuery to click on the button? Something like this...(first make a variable of your id so you can pass into jQuery).
var id = "#"+logoutid;
this.evaluate(function(id){
jQuery(id).click();
},id);

Javascript replace content innerhtml on click with integrated PHP tag

I am trying to replace the content of a DIV once the button inside that DIV is clicked, (basically replacing the button, which retreives a PHP variable:
<div id="buttonholder">
Publish
</div>
I am trying to replace it with an unpublish button after a post is published (when the button above is clicked):
function publish(status){
document.getElementById("buttonholder").innerHTML = 'Unpublish';
}
It does not work however ... What am I doing wrong ?
Your code syntax is wrong. Use like below.
function publish(status){
document.getElementById("buttonholder").innerHTML = 'Unpublish';
}
Add a button id and then do:
$(function() {
$("#buttonId").click(function() {
$("#buttonHolder").html(" html to replace with ");
});
});
Also you can use the $("#buttonHolder").html(" html to replace with "); instruction in your onClick function as well.

Call to Javascript function with in dynamically created HTML <a> tag not working

This seemed to be a simple javascript but I feel so dumb to ask this question.. but I don't know why this is not working. I have a method that dynamically creates some hyperlinks on the page. The hyperlinks are suppose to call an executable with a url as parameter. So, I use href with a call to this function that has the code to call the executable.
Non-dynamic anchor tag code works just fine to launch an exe.
But, I need this to work with dynamic hyperlinks. I have tried to simplify the problem and created the following jsFiddle to demonstrate the issue. The link doesn't call my method. Am I missing something stupid? I want this to work in IE.
I already tried some solutions posted by some people saying: I should try href="#" onclick="myfunc();". Somehow that didn't work either.
Here is my code:
function myfunc(url){
alert(url);
};
function dynfunc(){
var value = "This is a link";
var url="http://www.google.com";
var table = $("<table id='tab1'></table>");
var row = $("<tr></tr>");
var valueColumn = $("<td></td>");
$('').html(value).appendTo(valueColumn);
valueColumn.appendTo(row);
row.appendTo(table);
$("#div1").append(table);
};
dynfunc();
Assuming you have this html :
<table id="dyn">
<tbody>
</tbody>
</table>
You can just use this JavaScript for the Dynamicly added <a/>, this way you add one click handler instead of several.
<script>
$(function() {
var tbl = $('#dyn'), tbody = tbl.find('tbody');
var addLink = function(url, val) {
var tr = $('<tr/>'),
td = $('<td/>').appendTo(tr),
a = $('<a/>', {href: url}).html(val).appendTo(td);
}
tbl.on('click', 'a', function() {
alert($(this).attr('href'));
});
//some ajax that calls addLink
});
</script>
DEMO HERE
Change This line :
$('').html(value).appendTo(valueColumn);
To :
$('').html(value).appendTo(valueColumn).click(function(){myfunc(url) });
We associate a click event to your <a> after append and on every click , myfunc(url) will be called .

Categories

Resources