Get Text of clicked link from a function - javascript

I want to start off by saying I'm not an expert, maybe not even an intermediate, user of jQuery and any and all help is appreciated.
Here is a simulation of my little problem:
https://jsfiddle.net/c897enhy/
<a id="someRandomID_hypNotifSentTo_0" class="NotifSent2" href = "#">
this is the text i want to get
</a>
<br>
<a id="someRandomID_hypNotifSentTo_0" class="NotifSent2" href = "#">
this is the text i want to get 2
</a>
<br>
<a id="someRandomID_hypNotifSentTo_0" class="NotifSent2" href = "#">
this is the text i want to get 3
</a>
if ($) {
$(document).ready(function () {
$("a[id*='_hypNotifSentTo_']").live("click", function ($e) {
// Will post list of recipients to be removed from the file
var x = $(this).text();
alert(x);
AjaxSuccessPopulateRecipients("restult");
});
function AjaxSuccessPopulateRecipients(result) {
alert("asdf");
var x = $('#NotifSent2').toString();
alert(x);
var x = $(this).text();
alert(x);
var recipients = $(this).text();
alert("1");
var recipientArr = recipients.split(',');
}
});
}
While, I am able to get the text of the active link from the "click" event, I am unable to do so from my second function.
The way the application works, is that the first function call ajax c# file, which then returns a success into the second jquery function with some results from c#.
I need to compare the results that are returned from the c# to what is inside the clicked hyperlink, but am unable to get the clicked text from within that "AjaxSuccess" function.

You're losing the the context of $(this) when you're in the Ajax function ($(this) will no longer refer to the clicked link). Try adding a variable that you can store the context in, like so:
$(document).ready(function () {
var $that;
$("a[id*='_hypNotifSentTo_']").live("click", function ($e) {
// Will post list of recipients to be removed from the file
$that = $(this);
var x = $that.text();
alert(x);
AjaxSuccessPopulateRecipients("restult");
});
function AjaxSuccessPopulateRecipients(result) {
alert("asdf");
//var x = $('#NotifSent2').toString();
//alert(x);
var x = $that.text();
alert(x);
var recipients = $(this).text();
alert("1");
var recipientArr = recipients.split(',');
}
});

$(this) inside the AjaxSuccessPopulateRecipients refers to the Widow object and not the anchor tag that was clicked.
Just send the reference of anchor tag from click event to the second function like this
AjaxSuccessPopulateRecipients("restult", $(this));
Use it as context like this
function AjaxSuccessPopulateRecipients(result, context) { // <--- context refers to the anchor tag
alert("asdf");
var x = $('.NotifSent2').text();
alert(x);
var x = context.text();
alert(x);
var recipients = context.text();
alert("1");
var recipientArr = recipients.split(',');
}

Take a look at Function.prototype.call().
The call() method calls a function with a given this value and
arguments provided individually.
Change:
AjaxSuccessPopulateRecipients("restult");
To:
AjaxSuccessPopulateRecipients.call(this, "restult");
Doing so will pass the correct this value to your function.

You should not able to access data via this $('#NotifSent2') selector as the # selector is JQuery syntax for finding an ID on the page, whereas your elements are constructed with class="NotifSent2".
If you wish to access a variable from a different function, you must ensure that the variable is within the correct scope.
Since your AJAX call and AjaxSuccessPopulateRecipients() function are within the same scope, you do not have access to $(this) across the two.
Simply pass the variable you wish to use to your function, as $(this) AjaxSuccessPopulateRecipients("restult", $(this));

Related

Unable to get the id of an element

The JSFiddle below is a simplified example of what I am trying to accomplish.
My code generates a. anchor element that is passed to a div.
I'd like it to return its id when double clicked but get an undefined instead.
Can anyone tell me what I am doing wrong?
JSFiddle
function abc() {
var myString = "<a onclick='bcd(this);' id='1'>krokodil</a>";
document.getElementById("output").innerHTML = myString;
}
function bcd(e) {
alert(this.id);
}
The value of this depends on how you call the function.
Since you are calling bcd without an explicitly object (foo.bcd()) and are not in strict mode, the value will be equal to window (in a browser).
You are reading the id of the window, not the element.
Look at the e variable instead of this (since you pass it the element from the click event handler).
The parameter you are passing to the alert function is referenced as e, but you then attempt to alert this.id. this refers to the function calling the expression. Try this:
function abc() {
var myString = "<a onclick='bcd(this.id);' id='1'>krokodil</a>";
document.getElementById("output").innerHTML = myString;
}
function bcd(e) {
alert(e);
}
Note that you also need to update the onclick() event to include the id property
The problem is you are alerting the id of this, which is not equal to e in the scope of the function. Change the function to
function abc() {
var myString = "<a onclick='bcd(this);' id='1'>krokodil</a>";
document.getElementById("output").innerHTML = myString;
}
function bcd(e) {
alert(e.id);
}
<button type="button" id="button" onclick="abc()">ADD</button>
<div id="output">kikker</div>
change
alert(this.id); to
alert(e)

How to pass a value from textbox into a jQuery function?

I'm trying to figur out how I can set the var number and then use it in my other function Custom.init(number); and make it stay on the page.
//Set number onclick
function setVar() {
var number = document.getElementById("textbox").value;
//Pass in number
jQuery(document).ready(function() {
Custom.init(number);
});
};
If you're using jQuery, the ready function should wrap all other functions as it will be invoked first and foremost.
$(document).ready(function(){
var number = document.getElementById("textbox").value;
//Then do your validation here
var setVar = function(){
Custom.init(number);
//whatever else is involved with this
}
})
If that doesn't work I'd check the console for a specific error and ensure your Custom.init function is working as expected.
It doesn't make sense to hide the ready handler inside a function. The comments in your code do also suggest that you wish to call Custom.init in response to a mouse click on some element. You would register an event handler to this end.
A suggested streamlining:
//Set number onclick
$(document).ready(function() {
$(<selector for clickable elements>).on (
"click"
, function (eve) {
Custom.init(parseInt($("#textbox").val()));
1;
}
);
});

pass through current target name to function

I'd like to dynamically create event listeners for multiple buttons, and subsequently, show a particular frame label depending on the button clicked, but I'm unsure what to pass through (FYI, this is will be used for HTML5 canvas in Flash CC, but principally the same should apply to a web page for showing divs etc). I currently have this:
var butTotal = 4;
var selfHome = this;
function createListeners () {
for (var i=0; i<butTotal; i++) {
selfHome["btn" + i].addEventListener('click', openPop);
}
}
function openPop () {
alert("test");
selfHome.gotoAndPlay("pop"+event.currentTarget.name.substr(3));
}
createListeners();
It creates the listeners fine, but I don't really know where to start with passing through the current button instance name to tell it which frame label to gotoAndPlay.
Based on the code that you have, I'd simply change the .addEventListener() to call a generic function (rather than openPop, directly), and pass it the reference to the button. So, this:
selfHome["btn" + i].addEventListener('click', openPop);
. . . would become this:
selfHome["btn" + i].addEventListener('click', function() {
openPop(this);
});
At that point, you would then have to update openPop to accept a parameter for the reference to the element that triggered it . . . something like:
function openPop (currentButton) {
At that point, you could reference the clicked button, by using currentButton in the openPop logic.
I'm not sure I totally understand your question. However if you just need to pass the button instance (in you case "selfHome["btn" + i]") you could call an anonymous function in your event handler which calls openPop() with the button instance as an arugment. Would this work for you?
var butTotal = 4;
var selfHome = this;
function createListeners () {
for (var i=0; i<butTotal; i++) {
var currentBtn = selfHome["btn" + i];
currentBtn.addEventListener('click', function(){openPop(currentBtn);} );
}
}
function openPop (btn) {
alert("test");
selfHome.gotoAndPlay(/*use button instance 'btn' to find frame*/);
}
createListeners();
When the event is triggered the this keyword inside the handler function is set to the element is firing the event EventTarget.addEventListener on MDN. If the button have the data needed to be retrieved just get it from the this keyword:
function openPop (btn) {
alert(this.name);
/* ... */
}
It looks like you expect it to contain the function gotoAndPlay() as well as the btn elements (which contain both an ID (of btn[number]) and a name with something special at substr(3) (I assume the same as the id). If those things were all true, it should work in chrome... in other browsers you'll need to add event to the openPop() method signature.
function openPop (event) {
alert("test");
selfHome.gotoAndPlay("pop"+event.currentTarget.name.substr(3));
}
I believe this is what you are looking for and adding that one word should fix your problem (assuming some things about your dom and what selfHome contains):
JSFiddle
You could also leave out the event from openPop() and replace event.currentTarget with this:
function openPop () {
alert("test");
selfHome.gotoAndPlay("pop"+this.name.substr(3));
}
JSFiddle

How do I pass local variable value from one function to another?

In my script I have 2 functions. First function references to a div element, creates a paragraph element inside div and appends some text to this paragraph element;
In my second function is triggered by onclick event attached to a link element. I want the text in the div to be changed to another text when clicking on the link. I do realize that there are 2 options how to achieve this:
1) declare global variables and use them in my second function;
2) pass the variable value from first function to the second function and manipulkate this value from the second function
But the question is how to do I correctly pass the variable value from first function to second function:
Here is the code:
<a href=''onclick='change();return false;'>Change</a>
<div id='box'></div>
Javascript:
window.onload= function createEl(){
var el = document.createElement('p');
var x = document.getElementById('box');
var text = 'text';
el.appendChild(document.createTextNode(text));
x.appendChild(el);
}
function change(){
x.innerHTML="other text";
}
in general you can write this:
function one(){
var var1 = "hello";
two(var1);
}
function two(x){
alert(x);
}
this will alert "hello".
For what you're doing, I would register my events through code to make it easier to pass a variable. We want to use an argument in the event handling function to pass the data to it.
window.onload = function()
{
// do your normal stuff with creating elements
var anc = document.getElementById('ID of your a element here');
if(anc.attachEvent)
{
//code for ancient IE
anc.attachEvent('onclick', function(){change(x);});
}
else if(anc.addEventListener)
{
//code for modern browsers
anc.addEventListener('click', function(){change(x);});
}
}
function change(elem)
{
elem.innerHTML='other text';
}
Do note that older versions of IE don't recognize addEventListener and use attachEvent instead, as seen in the above if block. Here's the documentation for addEventListener.

How to get the action performed by an hyperlink in javascript

How can i get the action performed by an hyperlink inside an div using javascript
<div id="example">
<a href="#">a<a>
b
c
</div>
var links = document.getElementById('example').getElementsByTagName('a');
links[0].onclick = function(){
alert('a clicked');
}
links[1].onclick = function(){
alert('b clicked');
}
links[2].onclick = function(){
alert('c clicked');
}
Working Example
you can attach event handlers in the loop as well:
var links = document.getElementById('example').getElementsByTagName('a');
for(var i = 0;i < links.length; i++){
links[i].onclick = function(e){
var event = e || window.event;
alert(e.target.innerHTML + ' link was clicked!!!');
}
}
I am guessing you are coming from a java background. So, action performed is not available by default in JavaScript. Neither is an anchor or <a>, an anchor is generally used to link to an external or internal links.
Goes to a mypage.html
Where As what you are asking by action performed is events. For that you should do something like this
Test Link
What this above link does is, executes a javascript function name test();
function test() {
alert('ok the action is performed');
return false; //so that the browser does not decides to navigate after the function is executed
}
Some javascript libraries will give you some workaround for this. Here is an basic example done in JQuery
$("#example a">.click(function() {
//now you have got the action performed work around.
// You can use this as you like
// $this represent the item that was clicked
});
For this functionality in core. #Headshota answers is good example.
#Headshota example of referencing all the links within a div is reasonable, I'm merely expanding on it. I'm not sure what you mean by the action of a link so I'm assuming that you mean the url it points to and perhaps the target (deprecated).
var links = document.getElementById('example').getElementsByTagName('a');
links[0].onclick = function(){
// `this` inside this handler points to the <a> element that has been clicked
var href = this.href //where the link points
var target = this.target //if required
//do something with href and target
return false; //don't follow the link
}
etc...
$("#example a").click(function() {
alert("action");
});

Categories