Jquery append() doesn't work on new <a>Add</a> - javascript

Append() working fine but it is working only on the first <a class="add">Add</a>. not able to add new input field with the latest <a class="add">Add</a>
Here is my code
$(document).ready(function(){
var scntDiv = $('#add_words');
$('.add').click(function() {
$("#add_words").append('<div class="line">Word is <input type="text" /><a class="add">Add</a></div>');
return false;
});
});
html code
<div id="add_words">
<div class="line">Word is 1<input class="input1" type="text" value="1" /><a class="add">Add</a></div>
</div>

That's because click only attaches the click event handler to existing DOM elements, not future ones. You need jQuery on:
$(document).ready(function() {
$("#add_words").on("click", ".add", function(e) {
// Do your append here
// e.delegateTarget is your <div id="add_words">
$(e.delegateTarget).append('<div class="line">Word is <input type="text" /><a class="add">Add</a></div>');
// Prevent default action (e.g. don't follow links)
e.preventDefault();
});
});

Use on() for event delegation instead of click():
$('#add_words').on('click', '.add', function(){
$("#add_words").append('<div class="line">Word is <input type="text" /><a class="add">Add</a></div>');
});

use Live like this: see this jsfiddle
$('.add').live("click", function(event) {
$("#add_words").append('<div class="line">Word is <input type="text" /><a class="add">Add</a></div>');
return false;
});

Related

Detect which element called a function, within function without passing it as a parameter?

This is my html markup:
<a onclick="cart.add('10');" class="product-10">Add to cart</a>
<a onclick="cart.add('11');" class="product-11">Add to cart</a>
<a onclick="cart.add('12');" class="product-12">Add to cart</a>
And this is my javascript object:
var cart = {
'add': function(product_id) {
//What I want console.log(element_that_was_clicked.attr('class'));
}
}
Is there a way to detect which a called cart.add without editing html markup?
UPDATE
the a tag has no class, I added those classes just for demo, actually I need a object itself, because I want to access to its next sibling, my markup is something like this:
<div><a onclick="cart.add('10');">Add to cart</a><input type="text" name="quantity" /></div>
And I want:
var cart = {
'add': function(product_id) {
//What I want console.log(element_that_was_clicked.next().val());
}
}
First of all remove inline onclick (it is bad practice) and register an event listener:
HTML
<a id="10" class="product-10">Add to cart</a>
jQuery
$(document).on('click', 'a', function() {
var product_id = $(this).attr('id'); // Or any other attribute
cart.add(product_id);
});
EDIT
Check this workaround, basically, by executing removeInlineHandlers you remove the inline onclick property and assign an event handler that calls the add function passing the clicked element:
function removeInlineHandlers() {
$('a').each(function() {
var that = $(this);
var thisId = that.attr('onclick').match(/\d+/);
that.removeAttr('onclick')
.on('click', function() {
cart.add(thisId, that);
});
})
}
var cart = {
'add': function(product_id, elem) {
alert('Added id: ' + product_id + ' with quantity of: ' + elem.next('input').val());
}
}
removeInlineHandlers();
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<a onclick="cart.add('10');">Add to cart</a><input type="text" name="quantity" />
<a onclick="cart.add('11');">Add to cart</a><input type="text" name="quantity" />
<a onclick="cart.add('12');">Add to cart</a><input type="text" name="quantity" />
The best or ideal way is to use jQuery event listener. Personally, I will find a way to change the HTML instead.
But if you really really can't change the HTML, you can do use the onclick attribute as a selector. This is bad practise.
Something Like:
var cart = {
'add': function(product_id) {
//$("[onclick=\"cart.add('" + product_id + "');\"]") <-- Getting the clicked a using onclick attribute
$("[onclick=\"cart.add('" + product_id + "');\"]").next().val("TEST");
}
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div><a onclick="cart.add('10');">Add to cart</a><input type="text" name="quantity" /></div>
<div><a onclick="cart.add('11');">Add to cart</a><input type="text" name="quantity" /></div>
<div><a onclick="cart.add('12');">Add to cart</a><input type="text" name="quantity" /></div>
The ideal is adding an event listener using a class. Like:
$(function(){
$(".product").click(function(){
$(this).next().val("TEST");
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div><a class="product">Add to cart</a><input type="text" name="quantity" /></div>
<div><a class="product">Add to cart</a><input type="text" name="quantity" /></div>
<div><a class="product">Add to cart</a><input type="text" name="quantity" /></div>

Append Another Div

I'm trying to append another form-group.
The button at the form-group added is not working.
Can anyone tell me why?
<div class="form-group">
<input type="text"/>
<button class="add">Add</button>
</div>
JS
$('.add').click(function(){
$('.form-group').append(
'<input type="text"/>'+
'<button class="add">Add</button>'
);
})
You need to use event delegation via .on() for dynamically added elements:
$('.form-group').on('click', '.add', function() {
$('.form-group').append(
'<input type="text"/>' +
'<button class="add">Add</button>'
);
})
jsFiddle example

jQuery Field Not Being Removed After Appending it

I am running into an issue where I can't seem to get my jQuery script to remove fields after they have been added. I have tried a few changes, but nothing has worked.
$(function() {
var dataSourceField = $('#sign-up-organization-discovery-source');
var i = $('#sign-up-organization-discovery-source p').size() + 1;
$('#sign-up-add-discovery-source').on('click', function() {
$('<p><label for="discovery-source-field"><input type="text" id="discovery-source-field" size="20" name="discoverySource" value="" placeholder="Input Value" /></label> Remove</p>').appendTo(dataSourceField);
i++;
return false;
});
$('#remScnt').on('click', function() {
if (i > 2) {
$(this).parents('p').remove();
i--;
}
return false;
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="container">
<div class="col-md-6 col-md-offset-3">
<form action="/app/sign-up/organization" method="post">
<p>{{user.email}}</p>
<input type="hidden" name="admin" value="{{user.email}}">
<input type="hidden" name="organizationId">
<label for="sign-up-organization">Company/Organization Name</label>
<input type="text" class="form-control" id="sign-up-organization" name="organizationName" value="" placeholder="Company/Organization">
Add Another Discovery Source
<div id="sign-up-organization-discovery-source">
<input type="text" id="discovery-source-field" placeholder="Discovery Source" name="discoverySource">
</div>
<br />
<button type="submit">Submit</button>
</form>
Already have an account? Login here!
</div>
</div>
There are a couple problems here.
Firstly, an id is suppose to be unique! You are duplicating id attribute values each time you append the element.
Secondly, even if you were to use a class rather than an id, it still wouldn't work as expected because the clickable/removable a element doesn't exist in the DOM when you are attaching the event listeners.
You would either need to attach the event after appending the element, or you could use event delegation and attach the event to a common parent element that exists at the time.
Example Here
$('#sign-up-organization-discovery-source').on('click', '.remove', function() {
// ...
});
I changed Remove to: Remove.
Then I delegated the click event to the #sign-up-organization-discovery-source element.
$('##sign-up-organization-discovery-source').on('click', '#remScnt', function() {
if (i > 2) {
$(this).parents('p').remove();
i--;
}
return false;
});

Append and remove not working as they should

For some weird reason, my append is only adding but not removing.
Here is the HTML:
<div class="insert-links"></div>
<a href="#" id="button" onclick="return false;">
<img src="http://a.dryicons.com/images/icon_sets/blue_extended_icons_set/png/64x64/add.png" ">
</a>
and the jQuery is the following:
<script type='text/javascript'>//<![CDATA[
$(function() {
var i = 0;
$('#button').click(function() {
if (i < 10) {
$('.insert-links').append('<p style="display: none;" class="new-link"><input tabindex="1" placeholder="Command eg: give #user# 264" style="width:285px\;margin-top: 12px\;" type="text" name="fname" id="fname"/> <input tabindex="1" placeholder="Price" style="width:45px\;background-color:#f4faff\;" title="Price in points of this item" type="text" name="fname" id="fname"/><img src="http://c.dryicons.com/images/icon_sets/blue_extended_icons_set/png/128x128/remove.png" style="width: 20px;float: right;margin-top: 19px;margin-right: 19px;"></p>');
$('.insert-links').find(".new-link:last").slideDown("slow");
i++;
}
});
$('#buttonremove').click(function() {
if (i > 0) {
$('#buttonremove').parent('p').remove();
i--;
}
});
});//]]>
</script>
Could anyone please help me?
Use jQuery Event Delegation for this:
Fiddle Demo
$('.insert-links').on('click', '#buttonremove', function() {
if (i > 0) {
$('#buttonremove').parent('p').remove();
i--;
}
});
The problem is that you are binding the click event to the "buttonremove" when the page is loading , in that specific moment the paragraph containing all other elements does not exists yet. What you have to do is to move the binding code inside the click of the #button.

How to display one div and hide all others

I want to display a div on each button click and also want to hide the other all divs how I can do it.
HTML
<div id=a style="display:none">1</diV>
<div id=b style="display:none">2</diV>
<div id=c style="display:none">3</diV>
<div id=d style="display:none" >4</diV>
<input type=button value=1 id=w>
<input type=button value=2 id=x>
<input type=button value=3 id=y>
<input type=button value=4 id=z>
jQuery
$​('#w').live('click', function () {
$('#a').css('display', 'block');
});
$('#x').live('click', function () {
$('#b').css('display', 'block');
});
$('#y').live('click', function () {
$('#c').css('display', 'block');
});
$('#z').live('click', function () {
$('#d').css('display', 'block');
});
​ http://jsfiddle.net/6UcDR/
In your JSFiddle, you are using jQuery 1.7.2. If you are using this version in your real app, you should not be using $.live(), but use $.on() instead - the former is deprecated in favour of the latter.
The simplest and cleanest way to solve your problem would be to wrap both your buttons and divs in containers, and use $.index() to associate a button with a div:
<div class="showThese">
<div id="a" style="display:none">1</div>
<div id="b" style="display:none">2</div>
<div id="c" style="display:none">3</div>
<div id="d" style="display:none" >4</div>
</div>
<div class="buttons">
<input type="button" value="1" id="w">
<input type="button" value="2" id="x">
<input type="button" value="3" id="y">
<input type="button" value="4" id="z">
</div>
Note that your attributes must be quoted, as in the above HTML.
Then, in JavaScript, you only need to bind one delegated event to the buttons container. I'll use $.on() in this case:
$('div.buttons').on('click', 'input', function() {
var divs = $('div.showThese').children();
divs.eq($(this).index()).show().siblings().hide();
});
Here is a demo.
The above method does away with having to use IDs and other attributes, however you will need to be careful if you want other elements in the containers, as $.index() will begin to fail if you do.
Just start by hiding all other div's, then showing the one you want to be shown.
$​('#w').live('click', function(){
$('div').hide();
$('#a').show();
});
If understand you correctly, it should be just setting the display:none for the divs before showing your specific div.
$('#w').live('click', function(){
$('div').css('display','none');
$('#a').css('display','block');
});
$('#x').live('click', function(){
$('div').css('display','none');
$('#b').css('display','block');
});
$('#y').live('click', function(){
$('div').css('display','none');
$('#c').css('display','block');
});
$('#z').live('click', function(){
$('div').css('display','none');
$('#d').css('display','block');
});
​
live is deprecated, use on
$​('input').on('click', function(){
var index = $(this).index();
$('div').hide().eq(index).show();
});
example from jQuery.com:
function notify() { alert("clicked"); }
$("button").on("click", notify);
Check the demo http://jsfiddle.net/6UcDR/2/ Is this the thing that you want to achieve.
Try this jQuery-
$​('#w').click(function(){
$('#a').show()
$('#b,#c,#d').hide()
});
$('#x').click(function(){
$('#b').show();
$('#a,#c,#d').hide()
});
$('#y').click(function(){
$('#c').show();
$('#b,#a,#d').hide()
});
$('#z').click(function(){
$('#d').show();
$('#b,#c,#d').hide()
});
Add a class to all the divs u want to show or hide
eg:
<div id=a class="hide" style="display:none">1</diV>
And then add the following statement to each onclick function
$('.hide').css('display','none'); /* Replace .hide with whatever class name u have chosen*/
To see the answer in action: http://jsfiddle.net/6UcDR/1/

Categories