Click event added to appended html; element not working as anticipated - javascript

OK I am sure I am doing something simple fundamentally wrong but am unable to resolve this issue on my own. I have tried googling and searching this forum and reading through the relevant parts of the jquery documentation.
If you need any further information please let me know. Many thanks in advance.
What I am trying to do:
I have a table showing details of various tests at the bottom of which I have a button to ad a new test. As each test comprises several rows of the table I have a template in a hidden div which I have cloned and appended to the live table. I am the using jquery to add appropriate classes and ids based on a variable integer for the sake of uniqueness. I am also attempting to add a click event to an image within one of the table cell to delete the rows relating to that particular test.
My current function
function newTest(sampleID){
var testID = $("#testCount").val();
$("#newTest tr").clone(true)
.addClass("test"+testID)
.appendTo("#testsTable"+sampleID);
$(".newdelbox:first")
.attr("id","testDelete"+testID)
.addClass("delbox")
.removeClass("newdelbox");
$(".test"+testID).on('click',"#testDelete"+testID,delSample(testID));
testID++;
$("#testCount").val(testID);
}
What I need to happen
Function to be called when image is clicked.
What is happening
Function is called only when script is assigned (not clicked). Function will not subsequently run when clicked. I am seeing no errors within the console.
What I have tried
chained to preceeding code:
.click(delSample(testID));
.on("click",delSample(testID));
.bind("click",delSample(testID));
As new line within function:
$(".test"+testID).on('click',"#testDelete"+testID,delSample(testID));
document.getElementById("testDelete"+testID).onclick(delSample(testID));
document.getElementById("testDelete"+testID).addEventListener("click",delSample(testID),false);

try this:
.click(function(){
delSample(testID);
});
OR
.on("click",function(){
delSample(testID);
});

i do not know of your html but i supose something like
.on("click",function(){
var current_id = jQuery(this).attr('id');
delSample(current_id);
});
just locate your id

Related

Generate Bootstrap tooltip on-the-fly

I have a page with a text and some words in the text can change dynamically. These words have an element and should have a tooltip. When the user hovers the word (or I guess on a touch device clicks it), a tooltip should be generated using generateSpecialMarkupElement($(element).text()). Once the HTML has been rendered to the DOM another JavaScript function has to be called replaceMarkupHTML().
I don't have control over these functions unfortunately.
Now I'm wondering if there is a simple way in bootstrap get this done. For instance a before event to run the first function and an after event to call the second one.
Here is a simple example text and simplified versions of the functions:
http://jsfiddle.net/8aqz5auk/1/
So is there a bootstrap-way of hooking/intercepting this kind of thing? Or is there maybe another simple way it could be done?
Edit: I just had an idea. When bootstrap shows a tooltip, it seems to inject an element into the DOM. The interesting part is the container with the class 'tooltip-inner'. So I tried to listen on the body for new elements matching '.tooltip-inner' to be injected and whenever that happens I try to manipulate it:
$('body').on('DOMNodeInserted', '.tooltip-inner', function () {
var el = $(this)
el.html("") // empty the tooltip element
el.append(generateSpecialMarkupElement(el.text())) // insert the generated markup element
replaceMarkupHTML() // replace the markup element with normal html
});
Unfortunately it doesn't work. It just throws a a million errors and the site freezes when I try it.
Edit 2:
Thanks to Chris Barr, I got a little bit closer: http://jsfiddle.net/8aqz5auk/2/
But the tooltip doesn't always show up and the position of the tooltip seems to be kind of wrong (shows up on top of the word, rather then next to/above/below/...).
You might want to look into the tooltip events listed in the docs: https://getbootstrap.com/docs/3.3/javascript/#tooltips-events
$('.elements-with-tooltips').on('show.bs.tooltip', function () {
// do something…
})
You can run a function: before being shown, after being shown, before hiding, after hiding, and when the element is inserted into the DOM.

Materialize css initializing tabs for each result

I am doing a school project that is a Movie lookup app connected to guidebox API. I am using Materialize CSS and trying to organize the information into their tabs system. They are added dynamically so the documentation says to initialize in javascript. It says to use:
$(document).ready(function(){
$('ul.tabs').tabs();
});
However that doesn't work for me I guess since the tabs are not present at Doc Ready thaey are not pushed into the DOM until a submit request. I put just the
$('ul.tabs').tabs();
into a few places in my code and the best result was it working on the first movie returned on each search but for each subsequent return item the tabs break.
I could use some guidance on whether I can plug that in somewhere to make my existing code work.
https://github.com/jasonboru/group_project1_guidebox.git
There are some missing ending tags in your dynamically created dom elements.
Apart this, in this file assets/js/logic.js the following there are the following two lines:
$('.guidebox-search-results').append(movieResult);
$('ul.tabs').tabs();
That menas, whenever you add new tabs element you initialize them.
The mistake I see is: in this way you initialize every tabs not only the new one. And, because you have already initilized the old one I can suggest you to rewrite the previous two lines in this format:
$('.guidebox-search-results').append(movieResult);
$('.guidebox-search-results').find('ul.tabs').tabs();
You can bind on every event, when node inserted in dom and after that, do with it what you want.
$(document).bind('DOMNodeInserted', function(e) {
var element = e.target;
});

Jquery map won't retrieve selected options; always empty? Appears to skip variable, Works on jsfiddle, No console errors

SOLVED:
Final fiddle:
http://jsfiddle.net/AcfUz/220/
*used the selector indicated in the chosen answer and moved the console.log value ahead of the text input the selected options were to be listed in and boom--working as it should!
Please reference this fiddle:
http://jsfiddle.net/AcfUz/218/
jQuery(document).on('click', '#go', function() {
console.log("woo");
var selMulti = jQuery.map(jQuery("#inf_custom_Choosealocation_select :selected"), function(e) {
return jQuery(e).val();
console.log("hoo");
});
//var selMulti = jQuery("#inf_custom_Choosealocation_select :selected").val();
console.log(selMulti + "hmm...");
console.log("hootie");
//jQuery("#inf_custom_Choosealocation").val(selMulti.join(", "));
jQuery("#inf_custom_Choosealocation").val(selMulti);
console.log("who");
});
This works perfectly on fiddle but no matter how many iterations I try it won't work on the live site. The variable containing the desired values is always empty. I can't for the life of me figure out why?????
Can anyone shed some light in my hour of desperation? It's been 7 hours and I need to solve this before the morning.
I suppose to expand on this--the code in the fiddle is the code I include in the site. The form and then the script before the closing body tag. The form is dynamically loaded (takes about a second). What I need to accomplish is grabbing whatever values a user selects from any of the multi select fields (I'm starting with the one) and copy those as a comma separated list into another single line text input. The fiddle works splendidly, but I'm coming up empty on the live site. I just returns blank/empty--it doesn't give me any console errors what so ever (save for a missing img) and I can see my console.log checkpoints.
Here is the live link:
http://goo.gl/ll1Hz4
On the live website if I try $("#inf_custom_Choosealocation_select option") in the console, the options are listed twice. Using $('select') 2 #inf_custom_Choosealocation_select are returned. (although I didn't see 2 instances in the page source) ($("#inf_custom_Choosealocation_select"); returns one, but that uses getElementbyID and skips the search). Perhaps the second select is created by some sort of overlay?
All in all, I didn't search any further where the 2nd select come from. A quick fix would be to use a selector searching the attribute. The following selector worked while testing on the live site:
$("select[id=inf_custom_Choosealocation_select] :selected")
But that might be only a temporary work around. You'll probably want to find the ghost select culprit too ;)
You are not using jQuery map in fiddle, where as you have jquery map in your live code...
Try to update your live site with the code you have in fiddle.
Live Code: (has jQuery map)
So, yeah, I am not sure why :selected isn't working in your case, but you can try to go through the options and check manually... jQuery("#inf_custom_Choosealocation_select option").each(function(i, o){ console.log(o.selected) })
Try wrapping your code inside
jQuery(document).ready(function(){});
Instead of using
var selMulti = jQuery.map(jQuery("#inf_custom_Choosealocation_select :selected"), function(e) {
return jQuery(e).val();
console.log("hoo");
});
use
var selMulti=jQuery("#inf_custom_Choosealocation_select").val();

Add div to table column

Is it possible to add a div-element to a table cell/td by using jquery?
In my HTML code I have have div called s (just for testing):
<div id="s">12</div>
In my $(document).ready(function(){ function I I have added the following $("#sale_graph1").html('<div id="s"></div>'); where sale_graph1 is the id of the <td>/cell i want to add the <div>-element to. The cell gets populated with text if I write $("#sale_graph1").text
so I know it is the right cell I'm operating on. But when trying to add the div content nothing shows up in the cell.
Thanks for any help!
This working just fine. See here: http://jsfiddle.net/va5gr/
$('#sale_graph1').html("<div id='s'>12</div>");
(I've added the css to make it more visible)
If however you want to use the contents of your existing div#s then you can do this:
$('#sale_graph1').html($('div#s').html());
Try this code:
$("#sale_graph1").append($('#s'));
and ensure that you have only one element called sale_graph1
After this line:
$("#sale_graph1").html('');
You can add stuff inside your div doing this:
$("#sale_graph1 #s").text('12'); //to add text
or
$("#sale_graph1 #s").html('12'); //to add text with html content
Is this what you want:
$("#sale_graph1").html($('#s').html());
It seems the code is right? But I think maybe some errors at some place.
You can check it like as follow:
1. check if you got the right dom
console.log($('#sale_graph1').length);
insure that you can get '1' in the debugger tool's console
if you pass first step, then you can do
$("#sale_graph1").html('<div id="s">some text</div>');
to make sure you add some text in div#s
then if it dosen't work, you can say the four words;

Can you use a jQuery selector on a HTML tag that a JS string printed?

Sorry if the question was misleading, I couldn't find a better way to describe my problem. Anyway, here goes:
Suppose I had a button start that initially displays a string for me. Said string (let's call it stringA) is output through jQuery like this:
$(".start").click(function() {
$(".startButton").hide('slow', function() {
$("#table1").html(stringA);
});
});
Alright. Cool. That worked without a hitch. Now inside stringA I have multiple
<span class="optButton">this is a button</span> buttons. I have another onClick handler for my optButton button, and it goes like this:
$(".optButton").click(function() {
alert("Testing");
$("#table1").html(stringB);
});
Needless to say, clicking on optButton is supposed to replace the contents of #table1 with stringB. However, when I tried it, it doesn't work. I tried adding alert() to test and see if jQuery managed to select optButton, but it seems that it didn't because I get no popup from the alert() function.
My theory is that since optButton was not part of the original HTML and is within a string stringA, jQuery is unable to select optButton as a result. If this is true, is there a workaround to this issue? If it is not, what is the actual cause of the problem here?
You need to use event delegation since your span element has been dynamically added to the DOM:
$('#table1').on('click', '.optButton', function() {
alert("Testing");
$("#table1").html(stringB);
});
This technique will helps you to attach click handler to these newly created span elements.

Categories

Resources