Is it a scope issue? - javascript

I add a close button to the card. I try this code but the close button seems not working.
$('#add-pet').on('click', e => {
// Grab info from the form
let $name = $('#pet-name').val();
let $species = $('#pet-species').val();
let $notes = $('#pet-notes').val();
let $newPet = $(
'<section class="six columns"><div class="card"><p><strong>Name:</strong> ' + $name +
'</p><p><strong>Species:</strong> ' + $species +
'</p><p><strong>Notes:</strong> ' + $notes +
'</p><span class="close">×</span></div></section>'
);
// Attach the new element to the page
$('#posted-pets').append($newPet);
});
$('.close').on('click', function() {
$(this).parent().remove();
});
However, when I move this code:
$('.close').on('click', function() {
$(this).parent().remove();
});
right after the $('#posted-pets').append($newPet);
Then it works OK.
Why it is like that?

Whenever you want to make an event for an element which may be appended via jquery, you can try:
$(document).on('click', '.close', function() {
$(this).parent().remove();
});
It works after you appending span.close tag. Even if outside the scope
$('#add-pet').on('click', /*...*/);
Update:
You can also try:
$('#add-pet').on('click', e => {
let close_tag = $('<span>').addClass('close');
// do stuff...
// set event
close_tag.on('click', function () {
$(this).parent().remove();
});
$('#posted-pets').append(close_tag);
});

When the close function is outside of the div, it's trying to attach to existing .close elements and the element you are trying to attach to doesn't exist at that point in time. You need to do it inside because you need to have the $newPet element actually created before you can attach to it.

$('.close') will search in the dom.
If you haven't appended your html, then it can't be found by jQuery

Related

jquery click function not working even after using $(document).ready(function() {}); and even after using $(function) block

I am trying to extract the id=obj1 from the string html_doc and trying to attach an onclick function to it
document.addEventListener("DOMContentLoaded",
function (event) {
$ajaxUtils.sendGetRequest("data/GOG123.json",
function (res) {
var residue=res.residues;
var html_doc = "<div>" + "<Button id = obj1>" + residue[0].index + "</Button> " + "</div>";
console.log(html_doc);
var html_doc2;
html_doc2= $("html_doc").find("obj1");
$(document).ready(function(){
html_doc2.click(function () {
alert("Hello!");
});
});
var div1=$("#infoDiv");
div1.append(html_doc);
}
);
});
It is not working (i.e not showing an alert message) neither it is throwing any error.
Can someone please help me with the same?
I referred to Why is this jQuery click function not working? but it did not work out for me.
you can also use .on() click event.
$(document).on("click", "#obj1", function(){
alert("clicked");
});
Try to put ajax in either function or inside document ready.without extracting id you can do same thing if you know id.
var html_doc = "<div>" + "<Button id = obj1> Click" + "</Button> " + "</div>";//instead of click put ur code
var div1 = $("#infoDiv");
div1.append(html_doc);
$(document).ready(function() {
$("#obj1").click(function() {
alert("Hello!");
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id=infoDiv>This is div info</div>

jQuery added form elements cannot be selected

I apologise for the description if it's not fitting. It was hard to describe what's going on.
I have set up a jsFiddle here.
function addNewForm() {
$('body').html(function () { //display log in form
return "<input type=\"text\" placeholder=\"Word or Phrase\" id=\"prompt\" />\n" +
"<textarea id=\"answer\" placeholder=\"Answer text\"></textarea>\n" +
"<input type=\"button\" id=\"addnew\" value=\"Add This!\" />\n" +
"<p> </p>";
});
}
$("#addnew").click(function () {
$("p").html("ADD NEW CLICKED<br />");
});
$("a").click(function () {
addNewForm();
});
Is my syntax correct? For some reason, $("#addnew").click works when generated outside of its own function but the button stops working since I have tidied my code and placed it within its own function. Is there a reason that jQuery may not recognise an element that has been created through a function?
Cheers!
When you are trying to attach an onclick event handler onto #addnew, the element doesn't exist at that time.
You need to attach it when you add the form into DOM or use delegated events
$(document).on("click", "#addnew", function () {
$("p").html("ADD NEW CLICKED<br />");
});
You would probably also like to prevent the page from reloading, when you click the <a> link
$("a").click(function (e) {
e.preventDefault();
addNewForm();
});
Fixed jsfiddle: https://jsfiddle.net/5rb6koog/
The solution is here :
https://jsfiddle.net/wvepd6ge/7/
When you add your button, you need to attach the event like this :
function addNewClicked() {
$('.result').html("ADD NEW CLICKED<br/>");
}
$("a").click(function () {
addNewForm();
$("#addnew").click(function () {
addNewClicked();
});
});

Jquery .replaceWith not working proper

i have a jquery code that is preventing a link to go to that link but executing it. The problem i have is that after it executs the script and script is returning data i want to replace it with a new one but with the same class. The replace is doing inside the dom but next time i press that link is not prevening going to that link but the class is the same, here is my code:
<script>
$(".recomanda").click(function(e){
e.preventDefault();
var test=$(this);
var href = $(this).attr('href');
$.getJSON(href, function(data) {
if(data.recom==1)
{
$(test).replaceWith('<a class="recomanda" href="app/recomanda_produs.php?id=' + data.id + '&recom=' + data.recom + '">Recomandat</a> ');
}
if(data.recom==0)
{
$(test).replaceWith('<a class="recomanda" href="app/recomanda_produs.php?id=' + data.id + '&recom=' + data.recom + '">Recomanda</a> ');
}
});
});
</script>
html
<a class="recomanda" href="app/recomanda_produs.php?id='.$row['ID_Produs'].'&recom=0">Recomanda</a>
yeah, I ran into that problem too before, it's because when you attach click to recomanda on ready(), but when ajax load, everything in ready() won't fire again, that why you need to attach the event to non-dynamic elements, and let it find it's child selector.
$('body').on('click', '.recomanda', function() {});
When you call a replaceWith actually you are removing elements that are bound to onclick handler:
.replaceWith()
Description: Replace each element in the set of matched elements with
the provided new content and return the set of elements that was
removed.
The main idea is that you handler must be bound to the same element (that is not removed when clicking).
So instead of using replaceWith method use method that modify existing element like this:
test.attr('href', blablabla);
And this is not a problem, but second time you don't need to use $ with test variable.
You need to delegate the event to a parent so that it can be applied to specific children wether they exist now or in the future.
See: http://learn.jquery.com/events/event-delegation/
$("body").on("click", ".recomanda", function(e){
e.preventDefault();
var test=$(this);
var href = $(this).attr('href');
$.getJSON(href, function(data) {
if(data.recom==1){
$(test).replaceWith('<a class="recomanda" href="app/recomanda_produs.php?id=' + data.id + '&recom=' + data.recom + '">Recomanda"+((data.recom==1)?"t":"")+"</a> ');
}
if(data.recom==0){
$(test).replaceWith('<a class="recomanda" href="app/recomanda_produs.php?id=' + data.id + '&recom=' + data.recom + '">Recomanda</a> ');
}
});
});

Why is my JQuery function not triggered on a cloned element when the event becomes "true"?

I have been making this form that must enable the back-end user to create new questions for users to answer. The form is cloned and appended to a div (selector #content) successfully after the first .on(click) event, but it won't duplicate the form again if the cloned button is pressed. The .on(change) event applied to my drop-down selection does change the content of respective divs like it is supposed to, but only on the original form.
Here's the JQuery code:
$(document).ready(function () {
$('.addAnswer').on("click", function () {
var idx = $('#mp div[name^="antwoord"]:last').index() + 1;
$clone = $('#mp div[name^="antwoord"]:first').clone(true, true).attr('class', 'answer content_' + idx);
$('.removeAnswer').show;
$('#mp').append($clone);
$('.answer:last').each(function () {
$('b:last').empty();
$('b:last').prepend(String.fromCharCode(64 + idx) + ". ")
$('.addAnswer').on("click", function () {
idx++;
});
});
if (idx == 2) {
$('.removeAnswer').show();
}
});
$('.nextq').click(function () {
var newqid = $('#content form:last').index() + 1;
$('.done, .nextq, .remove').hide();
$('#content').append('<hr>');
$('#content').append($('form').html()).attr('class', 'q_' + newqid);
$('.nextq').on("click", function () {
newqid++;
});
$('.done:last, .nextq:last, .remove:last').show();
return false;
});
$('.group').hide();
$('#text:last').show();
$('.select:last').on("change", function () {
$('.group').hide();
$('#' + $(this).val() + ':last').fadeIn();
$('button.' + $(this).val() + ':last').fadeIn();
});
});
Because I thought posting the whole HTML template would be a tad bit too much, I provided a JSFiddle for you people.
One extra question for the ones that are feeling kind: In the JQuery code it is seen that the contents of the HTML are being parsed using .html() and appended with .append.(Line 33 on the JSFiddle) As the .on(change) function switches the contents of the divisions it should change, .html() sees those changes and takes those along with it. I'd like the .on(click) function to append the div's content in its original state, unchanged by the changes made beforehand by the back-end user. Any help with this would be much obliged.
In order to have jQuery trigger on new elements you would do something like
$( document ).on( "click", "<your id or class>", function() {
//Do stuff
});

How can I get to know which anchor tag got clicked?

I am creating my content dynamically, When a anchor tag is clicked navigate() function is called. How can i determine which anchor tag was clicked?
function navigate()
{
//var location=$(this).attr("id");
switch(location)
{
/*case "Configuration": $('#detailTable').empty();
$('#detailTable').append(navigateConfig);
break;*/
default: alert(location+" a tag was clicked");
}
}
$('#detailTable').empty();
$('<div width="100%">')
.attr('id','javainfoSpan')
.html('<div class="titleBlue">Configuration>'+productname+'>Java Properties</div>'+
//some other stuff
'</div>')
.appendTo('#detailTable');
Update:
My question is simple
there will be a number of a elements inside detailTable.
how can I get to know in some js function, which a element was clicked?
I see what you're doing now, you're creating the a elements on the fly. If you call javascript:navigate() then you're using standard javascript, and not jquery (jquery is required to use the $(this) selector).
Instead you should have this:
$("body").on('click', 'a', function() {
var location = $(this).attr('id');
switch(location){ /* ... */ }
});
This will catch the click event in jquery for any a element that you either create on the fly or that's already there when the page loads.
Remember, if you're using id then you need to set the id attr on the a element.
Here is a way to handle this too:
$(document).ready(function() {
var productname = "mytest";
$('#detailTable').empty();
$('<div width="100%">').attr('id', 'javainfoSpan').html('<div class="titleBlue">Configuration>' + productname + '>Java Properties</div>' + '<table id="list1" width="100%"></table>' + '<div id="gridpager"></div>' + '</div>').appendTo('#detailTable');
$(".navigate").click(function() {
var location = $(this).attr("id");
switch (location) {
case "Configuration":
$('#detailTable').empty();
$('#detailTable').append(navigateConfig);
break;
case "mytest":
alert("My test was clicked");
break;
default:
alert(location + " a tag was clicked");
}
});
});
See it live on jsfiddle
Try this:
function navigate($element) {
//var location = $element.attr("id");
switch (location) {
/*case "Configuration": $('#detailTable').empty();
$('#detailTable').append(navigateConfig);
break;*/
default: alert(location+" a tag was clicked");
}
}
$('#detailTable').empty();
$('<div width="100%">')
.attr('id','javainfoSpan')
.html('<div class="titleBlue">Configuration>'+productname+'>Java Properties</div>'+
//some other stuff
'</div>')
.appendTo('#detailTable');
// Pre jQuery 1.7...
$(".titleBlue").delegate("A", "click", function() {
navigate($(this));
}
// jQuery 1.7...
$(".titleBlue A").on("click", function() {
navigate($(this));
}
I changed the handler to use the delegate() method of jQuery (or the on() method for jQ 1.7+). Using this it makes it easier to pass the element which caused the event to your processing function, which it does as the $element variable.
You can then do with this as you need.
you have to iterate through each element of using jquery "each" function. By "this" you can get the click object.

Categories

Resources