in Javascript Dom ,the newly added element can't be selected? - javascript

<body>
<div id="options">
<p class="input">
<input type="text"/>
<a class="remove" >Remove</a>
</p>
<p class="input">
<input type="text"/>
<a class="remove" >Remove</a>
</p>
</div>
<a href = "#" id ="click" >Add Option</a>
</body>
And:
$(function() {
$("#click").click(function add_option(){
var options = document.getElementById("options");
var p=document.createElement("p");
p.setAttribute("class","input");
var input=document.createElement("input");
input.setAttribute("type","text")
options.appendChild(p);
p.appendChild(input);
var a=document.createElement("a");
a.setAttribute("class","remove");
var text = document.createTextNode(" Remove");
a.appendChild(text);
insertAfter(a,input);//if exist insertAfter
}
)
$(".remove").click(function remove_option(){
$(this).parent().remove();
})
})
when i click Add Option,it works,but when i click the remove of the newly added,it doesn't remove .whether the $(".remove") selector have effects on it?(the initial two remove work).how to make the newly added elements work?

try using it with .live()
$(".remove").live("click",function(){
$(this).parent().remove();
});

At the time you bind the event handler to the .remove elements, the new elements don't exist yet (obviously). That's why jQuery cannot find them and bind the event handler.
You can solve this using .live [docs] or .delegate [docs]:
$(".remove").live('click', function(){
$(this).parent().remove();
});
These methods bind the event handler to the document root and inspect every click event (in this case) and test whether the target matches the selector. If it does, the handler is executed.
I also would advise you to not mix plain DOM operations and jQuery like that. Your click event handler can be written in a more concise way:
$("#click").click(function(){
$('<p />', {'class': 'input'})
.append($('<input />', {type: 'text'})
.append($('<a />', {'class': 'remove', href: '#', text: 'Remove'})
.appendTo('#options');
});
There are exceptions, like accessing properties of DOM elements, but here you really should make use of jQuery.

This works: http://jsfiddle.net/UJERQ/
$("#click").click(function add_option(){
$("#options").append('<p class="input"><input type="text"/><a class="remove" > Remove</a></p>')
addTheClicks();
})
function addTheClicks(){
var btns = $(".remove");
var btnsLength = btns.length;
for(i=0;i<btnsLength;i++){
var hasClickAlready = $.data(btns.eq(i).get(0), 'events' );
if(hasClickAlready == null){
btns.eq(i).click(function(){
$(this).parent().remove()
})
}
}
}
addTheClicks();

Related

Change title of fa-icon using jquery [duplicate]

In my JSP page I added some links:
<a class="applicationdata" href="#" id="1">Organization Data</a>
<a class="applicationdata" href="#" id="2">Business Units</a>
<a class="applicationdata" href="#" id="6">Applications</a>
<a class="applicationdata" href="#" id="15">Data Entity</a>
It has a jQuery function registered for the click event:
$("a.applicationdata").click(function() {
var appid = $(this).attr("id");
$('#gentab a').addClass("tabclick");
$('#gentab a').attr('href', '#datacollector');
});
It will add a class, tabclick to <a> which is inside <li> with id="gentab". It is working fine. Here is my code for the <li>:
<li id="applndata"><a class="tabclick" href="#appdata" target="main">Application Data</a></li>
<li id="gentab">General</li>
Now I have a jQuery click handler for these links
$("a.tabclick").click(function() {
var liId = $(this).parent("li").attr("id");
alert(liId);
});
For the first link it is working fine. It is alerting the <li> id. But for the second <li>, where the class="tabclick" is been added by first jQuery is not working.
I tried $("a.tabclick").live("click", function(), but then the first link click event was also not working.
Since the class is added dynamically, you need to use event delegation to register the event handler
$(document).on('click', "a.tabclick", function() {
var liId = $(this).parent("li").attr("id");
alert(liId);
});
You should use the following:
$('#gentab').on('click', 'a.tabclick', function(event) {
event.preventDefault();
var liId = $(this).closest("li").attr("id");
alert(liId);
});
This will attach your event to any anchors within the #gentab element,
reducing the scope of having to check the whole document element tree and increasing efficiency.
.live() is deprecated.When you want to use for delegated elements then use .on() wiht the following syntax
$(document).on('click', "a.tabclick", function() {
This syntax will work for delegated events
.on()
Based on #Arun P Johny this is how you do it for an input:
<input type="button" class="btEdit" id="myButton1">
This is how I got it in jQuery:
$(document).on('click', "input.btEdit", function () {
var id = this.id;
console.log(id);
});
This will log on the console: myButton1.
As #Arun said you need to add the event dinamically, but in my case you don't need to call the parent first.
UPDATE
Though it would be better to say:
$(document).on('click', "input.btEdit", function () {
var id = $(this).id;
console.log(id);
});
Since this is JQuery's syntax, even though both will work.
on document ready event there is no a tag with class tabclick. so you have to bind click event dynamically when you are adding tabclick class. please this code:
$("a.applicationdata").click(function() {
var appid = $(this).attr("id");
$('#gentab a').addClass("tabclick")
.click(function() {
var liId = $(this).parent("li").attr("id");
alert(liId);
});
$('#gentab a').attr('href', '#datacollector');
});
Here is the another solution as well, the bind method.
$(document).bind('click', ".intro", function() {
var liId = $(this).parent("li").attr("id");
alert(liId);
});
Cheers :)
I Know this is an old topic...but none of the above helped me.
And after searching a lot and trying everything...I came up with this.
First remove the click code out of the $(document).ready part and put it in a separate section.
then put your click code in an $(function(){......}); code.
Like this:
<script>
$(function(){
//your click code
$("a.tabclick").on('click',function() {
//do something
});
});
</script>

After appending an element the event click is not working on the appended element in jQuery

I am appending item by jQuery. But after appending can't bind the event on the appended item. I am appending as follows:
var item = '<div id="'+newInputId+'" class="col-md-9" style="padding-right: 0px;">';
item += '<input id="txtInScope" type="text" value="'+currentScopeVal+'" class="form-control" readonly="readonly"/>';
item += '</div>';
item += '<div id="inScopeActionDiv'+newInputId+'" class="col-md-3" style="padding-left: 2px;">';
item += '<button type="button" class="btn btn-warning btn-sm remButton" title="Remove this item">Remove Item</button>';
item += '</div>';
$('#inScopeDiv').append(item);
And after appending this I want to bind a click event on the above remButton class as below:
$("#inScopeDiv").delegate(".remButton", "click", function(){
alert('you clicked me again!');
});
$('#inScopeDiv').on('click', '.remButton', function() {
alert("working");
})
$('.remButton').live('click', function() {
alert('live');
})
But no result. What can I try next?
$('.remButton').live('click', function() {
alert('live');
})
jquery method live is not valid anymore:
"As of jQuery 1.7, the .live() method is deprecated. Use .on() to attach event handlers. Users of older versions of jQuery should use .delegate() in preference to .live()."
Source: jquery live
Little explanation about event attachment:
You must realize that a target what you want to add a event, exists BEFORE to call the add event function(in this case with the method on of jQuery).
on another hand, exists with jquery a manner to make work a event attachment without the existence of the element before:
$('html').on('click', '#inScopeDiv .remButton', function () {
alert('works!');
});
Bind it on a parent that is not dynamic but always in the DOM.
You need to add the listener each time you add an item:
$('#inScopeDiv').append(item)
.off() //unbind old listeners so no duplicate listeners
.on('click', '.remButton', function() {
alert("working");
});
You could store the appended div in a variable using .appendTo and then you could attach the click event directly to the variable. See it working: JSFiddle
$(".appendDiv").click(function () {
var item = "<div>I'm a new div!</div>";
var appended_div = $(item).appendTo(".container");
appended_div.click(function () {
alert("Working!");
});
});

Remove buttons added by jQuery

I am adding extra selects and text fields to a form using jQuery. However I want to be able to remove added text fields using the remove button.
Once a field has been added jQuery can not seem to detect it.
jQuery
var counter = 2;
$("#addButton").click(function () {
var newTextBoxDiv = $(document.createElement('div'))
.attr("id", 'contact-list-div-' + counter).attr("class", 'contact-list-div');
newTextBoxDiv.after().html('<select></select>' +
'<input type="text" name="textbox' + counter +
'" id="textbox' + counter + '" value="" >' + '<button type="button" class="removeButton" id="removeButton-' + counter + '">Remove Button</button>');
newTextBoxDiv.appendTo("#contact-list");
counter++;
});
$(".removeButton").click(function() {
alert(this.id); //this never shows, only on the element that was
//added directly added using html, in this case removeButton-1
});
HTML
<div id="contact-list">
<div class="contact-list-div" id="contact-list-div-1">
<select></select>
<input>
<button type='button' class='removeButton' id='removeButton-1'>Remove Button</button>
</div>
</div>
<input type='button' value='Add Button' id='addButton'>
$('#contact-list').on('click', '.removeButton', function() {
//Your code
});
You need to use event-delegation:
$(document).on('click', '.removeButton',function() {
$(this).parents('.contact-list-div').remove();
});
You appending content to your DOM after the event-listener for your click on .removeButton is registered. So this element does not exist at the time your binding a click event to it.
Through event-delegation you are able to bind an event-listiner to an existing parent (document in this case, but #contact-list would be working too). And this will listen to all events of its descendants matching the .removeButton - selector.
Demo
This is because you are binding the events to elements that do not yet exist.
Use jQuery delegation to enable handlers on not yet existing elements:
$("body").on("click", ".removeButton", function() {
alert(this.id);
});
You add the click listener only at the first button.
Try using delegate:
$(document).delegate(".removeButton", "click", function() {
alert(this.id);
});
This tells the document that whenever a event click occours on an element with class "removeButton" it should call that callback
(You can see it working here)
Because the element is dynamicly added with jQuery, the normal .click event of jQuery will be not able to detect the new added elements.
Use instead .on. See the example below:
$("body").on("click", ".removeButton", function() {
alert(this.id); //this never shows, only on the element that was
//added directly added using html, in this case removeButton-1
});

how to judge which button has been clicked using there className instead of ID

I have 100 buttons in a table having same class name but different id c-1,c-2,....,c-n <input type="button" class="btn-c" id="c-1" value="ADD">
how will i Know which button has been clicked using their className and whithout using onclick event on the each button
<input type="button" ... onclick="call_function(this);"
for simplicity let say I want to alert(button.id); on the click of any of the 100 buttons
If you have so many buttons, it makes sense to use event delegation:
$('table').on('click', '.btn-c', function() {
alert(this.id); // will get you clicked button id
});
This is optimal approach for performance standpoint as you bind only one event handler to parent element and benefit from child element event bubbling.
UPD. This is pure javascript version of the same code:
document.getElementById('table').addEventListener('click', function(e) {
if (/\bbtn-c\b/.test(e.target.className)) {
alert(e.target.id);
}
}, false);
Demo: http://jsfiddle.net/zn0os4n8/
Using jQuery - attach a click handler to the common class and use the instance of this to get the id of the clicked button
$(".btn-c").click(function() {
alert(this.id); //id of the clicked button
});
You need to attach an event to a parent element and listen for the clicks. You can than use the event object to determine what is being clicked on. You can check if it is the element you want and do whatever you want.
document.body.addEventListener("click", function (e) { //attach to element that is a parent of the buttons
var clickedElem = e.target; //find the element that is clicked on
var isC = (clickedElem.classList.contains("c")); //see if it has the class you are looking for
var outStr = isC ? "Yes" : "No"; //just outputting something to the screen
document.getElementById("out").textContent = outStr + " : " + clickedElem.id;
});
<button class="d" id="b0">x</button>
<button class="c" id="b1">y</button>
<button class="c" id="b2">y</button>
<button class="c" id="b3">y</button>
<button class="d" id="b4">x</button>
<div id="out"></div>
Note: this is not going to work in older IEs without polyfills.

JavaScript/jQuery How to do .click function properly?

I have some buttons generated dynamically based on form inputs selected:
$.each(fields, function (i, field) {
var field_id = $('[name=' + field.name + ']').closest("fieldset").attr('id');
$("#results").append('<button id="jumpToThisStep" data-id="'+field_id.replace('q','')+'">'+field.value+ ' ' +'</button>');
});
}
In my doc.ready function I have the following:
$('#jumpToThisStep').click(function() {
var jump_to = $(this).data('id');
showStep(jump_to);
});
HTML:
<button id="jumpToThisStep" data-id="0"> ... </button>
<button id="jumpToThisStep" data-id="1"> ... </button>
<button id="jumpToThisStep" data-id="2"> ... </button>
Upon inspecting the elements they all have the proper data-id binding. But the only one that fires is the first one. What is preventing the others from preforming their .click?
You need to use event delegation here since your buttons are added dynamically so event delegation will help you to attach the click event to these newly created button:
$('#results').on('click', '.jumpToThisStep', function() {
var jump_to = $(this).data('id');
showStep(jump_to);
});
Also id is unique, you need to use class for your button instead.
HTML DOM id must be unique. use class instead of.
<button class="jumpToThisStep" data-id="0"> ... </button>
<button class="jumpToThisStep" data-id="1"> ... </button>
<button class="jumpToThisStep" data-id="2"> ... </button>
If you want to bind event on DOM which you add to document after document ready event, must to use event delegation.
$('#results').on('click', '.jumpToThisStep',function() {
var jump_to = $(this).data('id');
showStep(jump_to);
});

Categories