Unable to get the id of an element - javascript

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)

Related

Get Text of clicked link from a function

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));

Javascript - Function to use onclick?

I want to create a function and then use with onclick method, for example:
one = document.getElementById("oneID");
then instead of writing function for each onclick():
one.onclick = function(x) {
tempStack.push(parseFloat(one.value));
viewTemp.value += one.value;
}
I want to use a single function:
one.click = input(one);
but I'm not sure how to do it in the correct way for example the below I tried, doesn't work:
var input = function(x) {
tempStack.push(parseFloat(x.value));
viewTemp.value += x.value;
}
Lastly, no external JavaScript libraries to aid this question, vanilla JavaScript.
You'll need to pass a function as a reference, not call it:
one.onclick = input;
In this case you won't be able to pass an argument, but you can use this as a reference for the DOM element on which event is fired:
function input() {
tempStack.push(parseFloat(this.value));
viewTemp.value += this.value;
}
Here's a method with using JavaScript's .addEventListener(), as a previous answer mentioned, using this to pass through the DOM Node Element to use within the inputFunction.
<input type="text" value="64.23" id="bt" />
<script>
function inputFunction( x ) {
console.log( x.value ); //Console Logs 64.23
}
var bt = document.getElementById("bt");
bt.addEventListener( 'click', function(){ inputFunction( this )}, false );
</script>
Fiddle: http://jsfiddle.net/Lhq6t/
Think about functions as a normal objects, so the way is:
function input (event) {
// Process the event...
// event is my event object
// this is the object which trigger the event
// event.target is my button
}
on.onclick = input;
You must assign the input function as a normal variable.
The function input will receive an event object as parameter. Also you can refer to the button clicked with this.
Maybe the mozilla developer network or the real w3c site would explain it better.
Your requirement can be achieved by following:
Add this method in your script tag:
function input(x) {
/*tempStack.push(parseFloat(x.value));
viewTemp.value += x.value;*/
alert(x.id);
}
And then call this method onClick event of your buttons / anchors like:
<input type="button" id="oneID" value="oneID" onClick="input(this);"/>
<input type="button" id="twoID" value="twoID" onClick="input(this);"/>
threeID
See working example: http://jsfiddle.net/Avd5U/1/
ok, so just create a function with a parameter in it like:
function setValue(input){
tempStack.push(parseFloat(input.value));
viewTemp.value += input.value;
}
and then call the function on the click of that element like:
var one = document.getElementById("oneID");
one.click = setValue(one);
Good luck!

why can't I pass jquery objects as arguments in functions?

I'm trying to pass a jQuery selected object into a function, and the function will do a .html() on it.
Html:
<div id="box">this is a box</div>
Js:
var fillBox = function(box, text) {
box.html(text);
}
(function() {
var box = $("#box");
fillBox(box, "new text");
});
The box stays as "this is a box" and never gets updated, even tho the function is called. I even tried $(box).html(text) inside the function, but that doesn't fix it. Is this do-able?
http://jsbin.com/iqixoj/5/edit
You forgot a $.
$(function() {
var box = $("#box");
fillBox(box, "new text");
});

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.

empty div not getting recognised in javascript

i am creating an empty div in the javascript DOM. but when i call some function on it, for example,
var hover = document.createElement("div");
hover.className = "hover";
overlay.appendChild(hover);
hover.onClick = alert("hi");
the onClick function isn't working. Instead it displays an alert as soon as it reaches the div creation part of the script. What am i doing wrong?
Try addEventHandler & attachEvent to attach event to an element :
if (hover.addEventListener)
{
// addEventHandler Sample :
hover.addEventListener('click',function () {
alert("hi");
},false);
}
else if (hover.attachEvent)
{
// attachEvent sample :
hover.attachEvent('onclick',function () {
alert("hi");
});
}
else
{
hover.onclick = function () { alert("hi"); };
}
You need to put the onclick in a function, something like this:
hover.onclick = function() {
alert('hi!');
}
The property name is "onclick" not "onClick". JavaScript is case sensitive.
It also takes a function. The return value of alert(someString) is not a function.

Categories