Remove only one div with query - javascript

Here is the JsFiddle
I have a button that will add a new header, textbox, and a link when it's click.
But when I click on the remove link. It's removes every new item that was added.
Html:
<div id='main'>
Top of Boby
<div id='main_1'>
<div>
<h3> Item</h3>
<input type="text" />
</div>
</div>
</div>
JS:
$(function() {
$('.AddItem').click(function() {
$('div#main_1').append("<div><h3>Item</h3><input type='text' class='remove_skill'/><a href=''>Remove</a</div>");
});
})
$(function() {
$('.remove_skill').click(function() {
$(this).remove();
});
})

2 issues..
You have never defined the class for the anchor. Add the class to the anchor
You need to remove the enclosing div and not the anchor. Use .closest
Also you need to delegate the event as the elements are being added dynamically
$('#main').on('click', '.remove_skill', function (e) {
e.preventDefault();
$(this).closest('div').remove();
});
Check Fiddle

The problem with the code you've posted is that no links exist at the moment you call $('.remove_skill').click, so you can't add event listeners to them.
I recommend a step-by-step approach. Create, add behaviour, append to the document.
$('.AddItem').click(function () {
var new_element = $('<div class="item"><h3>Item</h3><input type="text"/><a class="remove" href="#">Remove</a></div>');
new_element.find(".remove").click(remove_item);
$('div#main_1').append(new_element);
});
function remove_item() {
$(this).closest(".item").remove();
return false;
}
I recommend <a href="#"> for javascript-handled links.
Alternative solution using a closure:
$('.AddItem').click(function () {
var new_element = $("<div class="item"><h3>Item</h3><input type='text'/><a class="remove" href="#">Remove</a</div>");
new_element.find(".remove").click(function() {
new_element.remove();
});
$('div#main_1').append(new_element);
});

Your problem is that your "Remove" is in an 'a' tag. This causes the page to reload, and removing all of your previous changes.

Related

How to fire on onclick event on clicking on an anchor text

I would like to fire an onclick event using Javascript whenever an user clicks on "Remoe Item". Given below is the actual code available. The problem is I do not see any id, class to identify the click on this anchor text. Any idea how to do that?
Remove Item
Thanks in advance.
Roy
You can attach the Click Event using this selector [href="#"] and set an attribute data-value.
Run this code snippet:
var removeCartItem = function(value) {
console.log(`You're about to remove this item: ${value}`);
};
var anchors = document.querySelectorAll('[href="#"]');
for (a of anchors) {
a.addEventListener('click', function(e) {
removeCartItem(e.target.getAttribute('data-value'));
});
}
<a href="#" data-value='ci6223000698'>Remove Item</a>
<a href="#" data-value='ci6223000677'>Remove Item</a>
See? the value was printed from your function removeCartItem.
Bonus with jQuery
Using the .data() looks fancier.
Store arbitrary data associated with the matched elements or return the value at the named data store for the first element in the set of matched elements.
Run this code snippet:
var removeCartItem = function(value) {
console.log(`You're about to remove this item: ${value}`);
};
$('[href="#"]').click(function() {
removeCartItem($(this).data('value'));
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<a href="#" data-value='ci6223000698'>Remove Item</a>
<a href="#" data-value='ci6223000677'>Remove Item</a>
you need to add an EventHandler:
Remove Item
while you'd need to have a function like this:
function myFunction(myVar) { //... }
or if you prefer adding the handler js side:
document.getElementById('remove').addEventListener("click", function() {
// your stuff
})
or with jQuery:
$('#remove').click(function() { //.... })
example in fiddle:
https://jsfiddle.net/txy5tyg2/1/
further reading:
addEventListener vs onclick
https://www.w3schools.com/js/js_htmldom_eventlistener.asp
You can retrieve all tag and add an event listener.
you can find the examples here,
How to add click event to an element?

jQuery: add click event to specific id

I have a small jquery problem:
My code is like this:
<div id="select-word-5" class="select-word-link"> - some content - </div>
<div id="select-5" class="select"> - some content - </div>
I have throughout my document several select-word-link and select divs.
I want to add a click event to the first div, that reacts just to the second div.
My idea was to loop through all the "select-x" elements, but i think there is a much better way?
$('.select-word-link').each(function()
{
var id = this.id;
var idLink = this.id.replace("-word", "");
$('.select').each(function()
{
if (idLink == this.id)
{
$(id).click(function() {
alert("this does not work");
});
});
});
You can do this easier by triggering an action on an event.
$('#select-5').click(function(){
alert('Does this work?');
});
$('.select-word-link').click(function(){
$('#select-5').trigger('click'); // will behave as if #select-5 is clicked.
});
Info: http://api.jquery.com/trigger/
More advanced:
$('#select-5').click(function(){
alert('Does this work?');
});
$('#select-6').click(function(){
alert('Does this work?');
});
// etc
$('.select-word-link').click(function(){
var selectId = this.id.replace('-word', '');
$('#'+selectId).trigger('click'); // will behave as if #select-5 is clicked.
});
maybe this code help you
$(".select-word-link").click(function(){
$(this).next().hide();
});
});
try
$('.select-word-link').first().on('click',function(){
// you code goes here
})
jQuery as CSS uses # selector to identify that this string is an Id.
e.g.
<div id="someId"></div>
and you execute this code:
$('#someId')
this will select the DOM object that has the Id someId
while id property returns the id of the DOM object without the selector # i.e. this jQuery code:
var id = $('#someId').get(0).id
will initialize the variable id to 'someId'
Thus, in your code add '#' in the selector
$('#' + id).click(function() {
alert("this does not work");
});
You have to trigger click next() element not all .select
$(".word").click(function() {
var selectId = this.id.replace('-word', '');
console.log(selectId);
$('#'+selectId).trigger('click');
});
$(".next").click(function() {
alert($(this).html());
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="select-word-5" class="select-word-link word">- some content 5-</div>
<div id="select-word-6" class="select-word-link word">- some content 6-</div>
<div id="select-word-7" class="select-word-link word">- some content 7-</div>etc.
<div id="select-5" class="select-word-link next">- some content next 5-</div>
<div id="select-6" class="select-word-link next">- some content next 6-</div>
<div id="select-7" class="select-word-link next">- some content next 7-</div>
very simple solution
$('#select-5 , .select-word-link').click(function () {
// your code
});
If you want trigger same functionality from 2 or more different div ids or classes or combination of both then put separated by , like '#select-5 , .select-word-link' as shown in above example.

Toggle spans inside an <a>

I am trying to create a function that will toggle optional inputs if chosen, here is what I have done so far:
HTML:
<div>
<input>
<a class="input-toggle" href="#"><span>Toggle Option</span><span>Close</span></a>
<div class="input-toggle-content">
<input name="">
</div>
</div>
JavaScript:
$('.input-toggle').each(function() {
$(this).next("div").hide().end();
$("span:last-of-type").hide();
$(this).on('click', function() {
$(this).next("div").slideToggle();
$("span:first-of-type").hide();
$("span:last-of-type").show();
});
});
So, the way it should work is when clicked on .input-toggle the div that is just next to it will be toggled and if clicked again the div will go away... I got this bit working, however, I want to also toggle <span>Toggle Option</span> with <span>Close</span> and I can't get it working... I don't know if the way I structured my function is correct?
Try,
$('.input-toggle + div.input-toggle-content').hide();
$(".input-toggle span:last-of-type").hide();
$('.input-toggle').click(function () {
$(this).next('div.input-toggle-content').toggle();
var spans = $('span', this);
spans.not(spans.filter(':visible').hide()).show();
});
DEMO
here you go: http://jsfiddle.net/jPe3A/
$('.input-toggle').each(function() {
$(this).next("div").hide().end();
$("span:last-of-type").hide();
$(this).on('click', function() {
$(this).next("div").slideToggle();
if($("span:first").is(':hidden')){
$("span:first").show();
$("span:last").hide();
}
else{
$("span:first").hide();
$("span:last").show();
}
});
});

Javascript/jQuery close notification fade out

Hello I have made a basic sticky notification that shows on my website, I am trying to make it so you can manually close it by clicking a button but it won't seem to work? Here is my code:
<script>
$(function() {
$("#closeBtn").click(function () {
$(".notification").fadeOut(500);
return false;
});
});
</script>
<div class="notification" id="success">
Message sent
<a href="#" id="closeBtn">
<div class="close">
<div class="closeTxt">X</div>
</div>
</a>
</div>
try using .on() for the elements created dynamically
$(document).on('click','#closeBtn',function() {
$(".notification").fadeOut(500);
return false;
});
Because the element is added to the DOM after page load, you need to use .on() instead of .click():
$(document).on('click', '#closeBtn', function (e) {
e.preventDefault();
$('.notification').fadeOut(500);
});
When the element is added Dynamically you have two choices.
function myFadeOut() {
$(".notification").fadeOut(500);
return false;
}
Using the on:
$(document).on('click', '#closeBtn', myFadeOut);
Or more clean, adding the click directly on the node when you generate it:
var $myNode = $('<div class="someNode"></div>');
$myNode.click( myFadeOut);
$(".foobar").append($myNode);

Changing calling javascript function variable with jquery?

There is a html page like this:
<div id="list"><a onclick = "javascript:addplaylist('shv231a','1');" href="javascript:void(0);">+</a></div>
<div id="list"><a onclick = "javascript:addplaylist('jhr2a13','1');" href="javascript:void(0);">+</a></div>
<div id="list"><a onclick = "javascript:addplaylist('thy2b1k','1');" href="javascript:void(0);">+</a></div>
There are javascript functions
addplaylist('shv231a','1');
addplaylist('jhr2a13','1');
addplaylist('thy2b1k','1');
I want to change value '1' with '2' in javascript function (addplaylist) when user click this
<a id="make2" onclick="" href="javascript:void(0);">Change the value 2</a>
How can I do that with jquery?
The way to do this with jQuery is to move all of the Javascript code into a separate file or script block within the HTML. Any way which abstracts the display (HTML + CSS) from the behavior (Javascript)
This will require a bit of reworking of the HTML. In particular removing the duplicate id fields in favor of having id's be unique. Additionally removing the javascript references from the onclick handler.
<div id="list1"><a>+</a></div>
<div id="list2"><a>+</a></div>
<div id="list3"><a>+</a></div>
Then with jQuery you can specify the behavior of these links directly from the JavaScript. This is true for both the play list links and the one which modifies them to pass '2',
$(document).ready(function () {
var secondArg = '1';
$('#list1 a').click(function (e) {
addplaylist('shv231a1', secondArg);
e.preventDefault(); // Don't follow link
});
$('#list2 a').click(function (e) {
addplaylist('jhr2a13', secondArg);
e.preventDefault(); // Don't follow link
});
$('#list3 a').click(function (e) {
addplaylist('thy2b1k', secondArg);
e.preventDefault(); // Don't follow link
});
$('#make2').click(function (e) {
secondArg = '2';
e.preventDefault();
});
});
This is a possible solution:
<a id="make2" onclick="javascript:changeToTwo();" href="javascript:void(0);">Change the value 2</a>
Javascript
function changeToTwo() {
$('div#list a').each(function() {
$(this).attr('onclick', $(this).attr('onclick').replace("'1'","'2'"));
});
}
If I remember right ie will only select 1 element with the same id so you may want to consider moving it to a class selector
1) Ids should be unique on a page
2) use a class to select
3) keep your functional code out of the markup
HTML:
<div id="1" class="list"><a>+</a></div>
<div id="2" class="list"><a>+</a></div>
<div id="3" class="list"><a>+</a></div>
javascript:
$('.list').each(function ( index, element) {
addplaylist(element.id);
});

Categories

Resources