Get the id of a link when clicked using Javascript - javascript

I'm new to Javascript, and trying to design a form with elements that are created and deleted by clicks on links without submitting a form.
The script depends on getting the unique id of a clicked button (css and <a> link), and calculating the id of the row containing the link, and then deleting the entire <tr> element.
For this, I'm trying to get the id of a clicked link. The link and the elements it is embedded in, is itself generated by javascript on clicking another button.
I tried the following:
var btnDel=document.createElement("a");
btnDel.id="NS_D"+count;
btnDel.className="btn btn-danger";
btnDel.addEventListener('click', function()
{
alert(e.id);
}, false);
var btnText=document.createElement("span");
btnText.className="btn-label";
btnText.innerHTML="Delete";
btnDel.appendChild(btnText);
td.appendChild(btnDel);
Though the button is generated, I'm not getting an alert as expected. Where can I have gone wrong?

You need use this rather than e:
alert(this.id);
in your event handler.
Demo here.
(You also need to get used to running your code with the Console visible - that would have told you that the reason you weren't seeing your alert is that e doesn't exist.)

In the event handler, this refers to the element, so you can do:
alert(this.id);
To get to the <tr> you can go up the tree using parentNode:
console.log(this.parentNode.parentNode);
MDN docs

Related

How can I get a DOM element generated by script?

I want to get a DOM element by clicking on it. The script looks like this:
document.onclick = function(e) {
e.target.style.backgroundColor = "green";
e.target.style.color = "white";
alert(e.target.tagName);
for (let attr of e.target.attributes) {
alert( `${attr.name} = ${attr.value}` );
};
};
The script works fine for the HTML elements, but it does not work for the elements generated by script. Actually nothing happens while I am clicking on the dropdown and selecting a value from it (no alert appears). Google Dev tools displays the element and some of its attributes including its id as far as I can see is autogenerated. I even can use its autogenerated id for doing automation job with this element. But is their any way to catch the element with my script?
Unfortunately I am not able to provide the original web page as it is internal company product, but I have found something similar that can be checked and by the way in this case it looks like the reason of not working script is different that those I have with auto generated elements in my original application. As you can see for the general Google page the script does not work for any element located on the page, but for the Google URL shown on the second image the same script works fine for all elements located on the page. And the shovn element itself is differnt (represented by div on the first image and by img on the second)
The reason it does not work for dynamically generated elements is simply because event listener is bound upfront on pre-existing elements.
You should have a function that re-binds the event every time a new element is added to the DOM. The function should be either targeted for the single element, or whole page.
window.onElementAdded = (element) = >{
element.onclick = ...
}
This function needs to be invoked every time an element is added to the DOM from your code.

Delete a selected div

Script explanation : I have a text area which user is typing notes and those notes are added to the DOM (as div elements) . I created an icon inside that divs that when you click on it i want the parent of the icon that is clicked to be removed from the DOM . I achieve this with JQuery , but i cant do it in pure JS. The code i use to achieve this in:
$('.fa-window-close').on('click', function(event){
event.preventDefault();
console.log($(this).parents('div')[0]);
$(this).parents('div')[0].remove();
});
Iam posting a link from gist, its a part code of my project so you can understand what iam trying to achieve.
https://gist.github.com/Clickys/43856fe26ee4c061cf910a9211f0c142
Basically what i want to achieve is , lets assume that we have a button that is creating divs elements inside DOM. Each of this div has an icon(fontawesome) that if we click on it , the selected target should be removed from the DOM(the target div) but not the other divs . I tried to use event.target and a lot of things but sadly i couldn't solve this with pure JS.
I tried this
closeTolPos.addEventListener('click', function(e){
var parentEl = e.currentTarget.parentNode.parentNode;
parentEl.removeChild(this.parentElement);
console.log(this.parentElement);
});
But it seems that when there are more than 1 element , it doesnt work . It only works if there is one element.
We make some changes and now the code works:
(function() {
document.addEventListener('click',function(e) {
if (e.target.closest('.notesDecoration')) {
e.target.closest('.notesDecoration').parentNode.removeChild(e.target.parentNode);
}
});
})();
Now click event is binded to a document, so the element exists, when the page is loaded. Then I check if the clicked element was the element, which was recently created and added to DOM.

How to work with dynamically created fields?

I have web layout, which can contains several links on it. Those links are dynamically created, using AJAX functions. And it works ok.
But, I don't know how can I work with those "dynamically created links" (ie. how to call some JS or jQuery function if I click on them). I guess that browser can not recognize them, since there are created after page is loaded.
Is there some function, that can "re-render" my page and elements on it?
Tnx in adv on your help!
You can use the 2 following methods jQuery provides:
The first one, is the .live() method, and the other is the .delegate() method.
The usage of the first one is very simple:
$(document).ready(function() {
$("#dynamicElement").live("click", function() {
//do something
});
}
As you can see, the first argument is the event you want to bind, and the second is a function which handles the event. The way this works is not exactly like a "re-rendering". The common way to do this ( $("#dynamicElement").click(...) or $("#dynamicElement").bind("click", ...) ) works by attaching the event handler of a determinate event to the DOM Element when the DOM has properly loaded ($(document).ready(...) ). Now, obviously, this won't work with dynamically generated elements, because they're not present when the DOM first loads.
The way .live() works is, instead of attaching the vent handler to the DOM Element itself, it attaches it with the document element, taking advantage of the bubbling-up property of JS & DOM (When you click the dynamically generated element and no event handler is attached, it keeps looking to the top until it finds one).
Sounds pretty neat, right? But there's a little technical issue with this method, as I said, it attaches the event handler to the top of the DOM, so when you click the element, your browser has to transverse all over the DOM tree, until it finds the proper event handler. Process which is very inefficient, by the way. And here's where appears the .delegate() method.
Let's assume the following HTML estructure:
<html>
<head>
...
</head>
<body>
<div id="links-container">
<!-- Here's where the dynamically generated content will be -->
</div>
</body>
</html>
So, with the .delegate() method, instead of binding the event handler to the top of the DOM, you just could attach it to a parent DOM Element. A DOM Element you're sure it's going to be somewhere up of the dynamically generated content in the DOM Tree. The closer to them, the better this will work. So, this should do the magic:
$(document).ready(function() {
$("#links-container").delegate("#dynamicElement", "click", function() {
//do something
});
}
This was kind of a long answer, but I like to explain the theory behind it haha.
EDIT: You should correct your markup, it's invalid because: 1) The anchors does not allow the use of a value attribute, and 2) You can't have 2 or more tags with the same ID. Try this:
<a class="removeLineItem" id="delete-1">Delete</a>
<a class="removeLineItem" id="delete-2">Delete</a>
<a class="removeLineItem" id="delete-3">Delete</a>
And to determine which one of the anchors was clicked
$(document).ready(function() {
$("#links-container").delegate(".removeLineItem", "click", function() {
var anchorClicked = $(this).attr("id"),
valueClicked = anchorClicked.split("-")[1];
});
}
With that code, you will have stored in the anchorClicked variable the id of the link clicked, and in the valueClicked the number associated to the anchor.
In your page initialization code, you can set up handlers like this:
$(function() {
$('#myForm input.needsHandler').live('click', function(ev) {
// .. handle the click event
});
});
You just need to be able to identify the input elements by class or something.
How are these links dynamically created? You can use use the correct selector, given that they are using the same class name or resides in the same tag, etc.
consider the html form
<form>
<input type="text" id="id" name="id"/>
<input type="button" id="check" name="check value="check"/>
</form>
jquery script
$('#check).click(function() {
if($('#id).val() == '') {
alert('load the data!!!!);
}
});
here on clicking the button the script check the value of the textbox id to be null. if its null it will return an alert message....
i thin this is the solution you are looking for.....
have a nice day..
Noramlly , the browser process response HTML and add it to DOM tree , but sometimes , current defined events just not work , simply reinitialize the event when u call the ajax request ..
All you need to do to work with dynamically created elements is create identifiers you can locate them with. Try the following code in console of Firebug or the developer tools for Chrome or IE.
$(".everyonelovesstackoverflow").html('<a id="l1" href="http://www.google.com">google</a> <a id="l2" href="http://www.yahoo.com">yahoo</a>');
$("#l1").click(function(){alert("google");});
$("#l2").click(function(){alert("yahoo");});
You should now have two links where the ad normally is that were dynamically created, and than had an onclick handler added to bring up an alert (I didn't block default behaviour, so it will cause you to leave the page.)
jQuery's .live will allow you to automatically add handlers to newly created element.
If your links are coming in via AJAX, you can set the onclick attributes on the server. Just output the links into the AJAX like this:
Holy crap I'm a link
The return false makes sure the link doesn't reload the page.
Hope this helps!

Using jQuery on dynamically added content

I am newbie to jQuery and javascript. In my application I have a list of users. When a particular user is clicked from the list, a div element is replaced with details about the user dynamically. When another user is clicked, again I replace the same div element with this user details. So at a time only one user details can be seen.
I use jquery, so my code to the above description looks like.
$('table#moderate_users tr').click(function() {
$.get('/moderate/user/'+uid, function(data){ $('div.user_info').html(data);
});
});
This works perfect and the content is inserted dynamically.
I have a dropdown(html select tag) in the dynamically added content. So I get the dropdown only when i click on a user from the list and it changes repectively when I click on another user. I wanted to find the value of the select tag using jquery whenever it is changed. So I wrote
$('select#assign_role').change(function(){
alert(this.val());
});
Since this dropdown is added after document.ready, adding this script inside document.ready function never worked. I also tried to insert the above script along the with the user details which is dynamically added.For my surprise this script is not inserted into the document at all, while the rest of the HTML content are inserted perfect. I am not aware if i can add insert javascript after the document has loaded. I am not aware how i could use jQuery to find out the value of the select tag which is added dynamically.
Thanks.
you want jQuery's "live" functionality:
$('select#assign_role').live('change',function(){
alert($(this).val());
});
also notice I changed alert(this.val()); to alert($(this).val()); considering that this inside a jQuery event handler references the actual dom element, not a jQuery object.
From the looks of your code, it seems that you are inserting a chunk of HTML into that div. So even if you wire your event to the dropdown after the page load, it will not work, since all of your event binding will be ignored when you insert new HTML code into div.
Try moving your code inside the function that inserts HTML. Something like this:
$('table#moderate_users tr').click(function() {
$.get('/moderate/user/'+uid, function(data){
$('div.user_info').html(data);
$('select#assign_role').change(function(){
alert(this.val());
});
});
});
On IE the live function doesn't work for onchange on <select> elements.
http://www.neeraj.name/blog/articles/882-how-live-method-works-in-jquery-why-it-does-not-work-in-some-cases-when-to-use-livequery
You will need to either add the select then do a setTimeout and then bind with the jquery.bind type of functionality, or, what I have done, is when you create the element then just set the onchange event handler there directly.
If you don't need to support IE then the live function works great.

JQuery - Appended Links don't work

I have created a dynamic list picker script using Jquery 1.3 and PHP that sends a JSON AJAX request and returns a list of items to choose from. The AJAX call works perfectly returning an array of items that I use Jquery to append them as an unordered list to an empty container DIV. That portion of the process works as expected.
The problem comes from the fact that from that list of items, I'm drawing them as links whose clicks are handled by a rel attribute. Here's an example:
<a rel="itemPick" id="5|2" href="#">This is the link</a>
The JQUERY handler looks like:
$('a[rel=itemPick]').click(function () {
code here...
});
These links and click handlers work fine when the page loads, but when they are appended to the container DIV, the click event does not get picked up. I don't want to have to refresh the entire HTML page again, so is there something I need to do in addition to append() to get JQUERY to recognize the newly added links?
When you use the jQuery.click method, it's looking for all of the "a" elements that currently exist on the page. Then, when you add a new "a" element, it has no knowledge of that click event handler.
So, there's a new event model in jQuery that allows you to bind functions to all current and future elements called Live Events. You can use Live Events the same way that you use normal event binding, but they will work for all future elements specified. So, you can simply switch your binding logic to:
$('a[rel=itemPick]').live('click', function () {
//code here...
})
$('a[rel=itemPick]').live("click", function (){ code here... });
Do you bind the event after adding the links?

Categories