jquery on click event doesn't work when using ajax - javascript

I am doing an ajax to pull information from a spreadsheet on my google drive, and then using the following code to display them in HTML:
I have this HTML:
<section class="p-booking" id="booking">
<div class="container">
<div class="row">
<div class="event-box">
<!-- caixas puxados do drive -->
</div>
</div>
</section>
And this JS:
$.getJSON(url, function (data) {
var caixasEvento = [];
caixasEvento.push('<div class="col-md-3">');
caixasEvento.push('<div data-id="' + something + '" class="box">');
caixasEvento.push('<h1 class="day">' + something + '</h1>');
caixasEvento.push('<h1 class="local">' + something + '</h1>');
caixasEvento.push('<img class="local-img" src="' + image + '">');
caixasEvento.push('</div>');
caixasEvento.push('</div>');
$('.event-box').append(caixasEvento.join(''));
});
And then I need an alert every time someone clicks the box:
$('.box').on('click', function() {
alert('test')
});
I'm using a script link tag in the bottom of my html document.
the box is normally appearing with all the drive information.
It does not work. I believe that is a problem related to the ajax, because if I create a div with the 'box' class, the alert works.

I'm guessing this is happening because the box element doesn't exist on the page when you try to setup the listener. Try this:
$('.event-box').on('click', '.box', function() {
// do stuff here
});

Try this:
$('.box').each(function()
{
$(this).click(clickHandler);
});
function clickhandler()
{
alert('test')
}

Related

How to make a popover that shows an enlarged version of a dynamic image using JQuery?

I have to display a popover containing an enlarged version of a dynamic image that gets added via a file input #insert-image but I am not sure how to go about doing this since the image is dynamic and the url of the image changes depending on what is selected by using the file input. The code below basically just adds the image that is selected to a table cell.
var imagePrep = $("#insert-image").val().replace(/C:\\fakepath\\/i, 'images/');
$('td:contains("image")').html("<img src=" + imagePrep + " alt='selected-image' class='image'>");
I managed to get it working myself by adding a few attributes data-toggle='popover'" + "data-img=" + imagePrep + ">" with imagePrep being my variable. I also had to add a mouseover function to my image and within that function I added the popover using the popover function (ps. If you get an error saying that the popover function doesn't exist just make sure to have the bootstrap scripts in your html file, you cn find the bootstrap scripts on the bootstrap website).
This is a solution that solved my problem:
$('td:contains("image")').html("<img src=" + imagePrep + " alt='selected-image' class='image' data-toggle='popover'" + "data-img=" + imagePrep + ">").on('mouseover', function() {
$('[data-toggle="popover"]').popover({
trigger: 'hover',
html: true,
content: function() {
return '<img class="img-fluid" src="' + $(this).data('img') + '" />';
},
title: 'Enlarged Image'
});
});
Hope this helps.
Just copy the commented url and pest in text box dynamic image is created. You also use both jQuery and Javascript attributes. Below is the example:
<!DOCTYPE html>
<html>
<head>
<script src="http://code.jquery.com/jquery-1.8.3.min.js"></script>
</head><!--from ww w . ja v a2 s.c o m-->
<body>
<div>
<input type="text" id="insert-image" />
<input type="button" id="insert" value = "insert" />
</div>
<div id="imgwrapper"></div>
<script>
$(document).ready(function()
{
$("#insert").on("click",function(){
img = document.createElement("img");
// img.src = "http://www.java2s.com/style/download.png";
img.src = $('#insert-image').val();
img.mouseover = function(e){alert(e);}
$('#imgwrapper').append(img);
$("#imgwrapper").on("mouseover",function(){
alert("TEST");
});
});
});
</script>
</body>
</html>

How can I add jQuery information to a html form?

This html form gets displayed by a bit of javascript code. Now I want to add the information of the cells in my table, when I click on them, to this kind of alert.
How can I do that?
<div class='alertBox' id='box'>
<script type="text/javascript">
$(document).ready(function() {
$('#tableBody td').on('click', function() {
alert($(this).html() + ' ' + months[currentMonth] + ' ' + currentYear);
});
});
</script>
<form>
<input name='Event' type='text' value='Event'> <br>
</form>
<a onclick='unpop()' class='close'>Close</a>
</div>
...
This is a website, where you can add appointments to a calendar and afterwards the appointments will be displayed by a raspberry pi.
Thank you for your answer.
I already found another solution.
Here it is if you are interested:
$(document).ready(function() {
$('#tableBody td').on('click', function() {
var cellIndex = document.getElementById('displayDate').innerHTML = $(this).text() + ' ' + months[currentMonth] + ' ' + currentYear;
});
});
function pop() {
document.getElementById('box').style.display = 'block';
cellIndex;
}
function unpop() {
document.getElementById('box').style.display = 'none';
}
If the HTML for the alert box is added by javascript, then you will need to use .on() to catch user events (this is called event delegation). Also, when you do that, you must attach the .on() method to an element that definitely exists before the javascript is run - $(document) is always safe.
Try this:
$(document).ready(function() {
$(document).on('click', '#tableBody td', function() {
let txt = $(this).text();
$('#box input[name=Event]').val(txt);
$('#box').show();
});
$(document).on('click', '#box a.close', function(){
$('#box').hide();
});
});
table{border-collapse:collapse;}
th,td{border:1px solid #ccc;}
#box{position:absolute;top:5vh;left:20vw;padding:2vh;background:wheat;display:none;}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.2.4/jquery.min.js"></script>
<div class='alertBox' id='box'>
<form>
<input name='Event' type='text' value='Event'> <br>
</form>
<a class='close'>Close</a>
</div>
<table>
<thead><th>Name</th><th>Vehicle</th></thead>
<tbody id="tableBody">
<tr><td>Bob</td><td>Car</td></tr>
<tr><td>Sam</td><td>Truck</td></tr>
<tr><td>Fred</td><td>Bike</td></tr>
</tbody></table>

Get JSON appended items in another div

I am trying to get a JSON appended item to show on click in another div.
For example -
$.getJSON("URLHERE", function(result){
$.each(result, function(i, field){
$(".mydiv").append( "<div class='newdiv'>" + field.name + "," + field.event + "</div>");
});
this gets my JSON information and adds it to .mydiv for each item.
Now - I am trying to get this information again, to show in another div, but only for the selected item. I have tried to add a click function to show the JSON information but only for the selected, but with no luck.
$('.mydiv').click(function() {
$(".seconddiv").append(field.name);
});
If anyone can put me on the right track it would be much appreciated.
Thanks!
EDIT
My HTML
<div class="container">
<div class="row">
<div class="col-md-8">
<div class="mydiv">
<h1>...</h1>
</div>
</div>
<div class="col-md-4">
<div class="seconddiv">
<h1>...</h1>
</div>
</div>
</div>
</div>
EDIT 2
$.getJSON("URLHERE", function(result){
$.each(result, function(i, field){
$(".mydiv").append( "<div class='newdiv'>" + field.name + "," + field.event + "</div>");
$(document).on('click', 'div.newdiv', function(){
$('div.seconddiv').append( $(this).html() );
});
});
EDIT 3:
So, This is working, BUT it is looping through each JSON and pulling the name through, I basically need only this name.
$(document).ready(function() {
$.getJSON("URLHERE", function(result){
$.each(result, function(i, field){
$(".mydiv").append( "<div class='newdiv'>" + field.name + "," + field.event + "</div>");
});
$('.newdiv').click(function() {
$(".seconddiv").append(field.name); // HOW TO ONLY GET THIS FIELD NAME, NOT FOR EACH JSON ITEM
});
});
});
Functionality is a little unclear but here is a solution for when you want to display info and on click display only a selected name in a different div. I would recommend storing JSON attributes as data elements on newly created divs which can be later easily retrieved via a simple click handler.
jsfiddle here: https://jsfiddle.net/7961d87z/
And just the code
HTML
<!-- placeholder for your data -->
<div class="mydiv"></div>
<!-- placeholder for click events -->
<div class="result"></div>
Javascript
//fake data
result= [{name:"item1", event: "something"}, {name:"item2", event: "someevent"}];
$.each(result, function(i, field){
//create an element and append data attribute to the element - in this case field name
el = $("<div class='newdiv'>" + field.name + "," + field.event + "</div>").data("name", field.name);
//append element to DOM
$(".mydiv").append( el );
})
//define a click handler for all new elements to display data in a div
$(".mydiv").on( "click", ".newdiv", function() {
$(".result").text( $( this ).data("name") );
});
It isn't in your DOM element on load as you append it. What you want to do is actually manage the clicked element:
jQuery(document).on('click', 'div.mydiv', function(){
});
You must also remember, that you can't access the JSON outside of your $.getJSON() call.
Edit
To only show your clicked one, you'll need to fetch the .html() and append that to the new div. That looks something like this:
jQuery(document).on('click', 'div.mydiv', function(){
jQuery('div.mynewdiv').append( jQuery(this).html() );
});
This creates HTML for element having class mydiv
$.getJSON("URLHERE", function(result){
$.each(result, function(i, field){
$(".mydiv").append( "<div class='newdiv'>" + field.name + "," + field.event + "</div>");
});
Use this to append to .seconddiv the information you want
$(document).on('click','.newdiv',function() {
$(".seconddiv").append($(this).html()); // fieldName,fieldEvent
});

Unable to hide the file attachment browse button

I am sending attachments in email, while sending user can actually add multiple attachments. My code is keep displaying the browse button for every time. I want to display only one button and let the user opens the file picker for any no of attachments.
Please tell me whats wrong with my code.
Also see the attached image. Which is something I don't want that behavior.
What I want is on clicking the attach more button it should automatically open the file picker. Currently it is displaying the
Thank you.
<div class="col-sm-10">
<div class="element">
<label>Attachment</label>
<span class="upload_file_button"><input type="file" name="upload_file1" id="upload_file1"/></span>
</div>
<div id="moreImageUpload"></div>
<div id="moreImageUploadLink" style="display:none;margin-left: 10px;">
Attach More
</div>
</div>
</div>
</div>
javascript
<script type="text/javascript">
// onclick browse button attach the file id and show the attachmore link
$(document).ready(function() {
$("input[id^='upload_file']").each(function() {
var id = parseInt(this.id.replace("upload_file", ""));
$("#upload_file" + id).change(function() {
if ($("#upload_file" + id).val() != "") {
$("#moreImageUploadLink").show();
}
});
});
var upload_number = 2;
$('#attachMore').click(function() {
//add more file. Everytime clicking on attachmore link show the browse button also attach more as well.
var moreUploadTag = ''
moreUploadTag += '<div class="element"><label for="upload_file"' + upload_number + '>Upload File ' + upload_number + '</label>';
moreUploadTag += '<span class="upload_file_button"><input type="file" id="upload_file' + upload_number + '" name="upload_file' + upload_number + '"/></span>';
moreUploadTag += ' Delete ' + upload_number + '</div>';
$('<dl id="delete_file' + upload_number + '">' + moreUploadTag + '</dl>').fadeIn('slow').appendTo('#moreImageUpload');
upload_number++;
});
});
function del_file(eleId) {
var ele = document.getElementById("delete_file" + eleId);
ele.parentNode.removeChild(ele);
}
</script>
On click + Attach More it is displaying the browse button. Instead I want to open the file picker right away upon clicking + Attach more.
Just add this line
$('#upload_file' + upload_number).trigger('click');
before
upload_number++;
in order to have the "Attach more" button to trigger the opening of the file pickup.
Then you could hide the input file tag with CSS.

Dynamic Checkboxes getting reset?

I have a fullcalendar displayed and a list of resources with checkboxes displayed next to their name. They checkboxes show up correctly and if i dont do anything with them they stay checked like they normally would. But, when i call fullcalendar with jquery and go to add or remove a resource, the checkboxes uncheck themselves after running the jquery/fullcalendar functions.
here is how i create the checkboxes:
$(document).ready(function() {
for(p in dsnrs){
$('#specialists').append(
'<input type="checkbox" name="designer" id="' + dsnrs[p].name +'" onChange="addOrRem(dsnrs['+p+'] )" />' +dsnrs[p].name+ '<br />');
}
});
And here are my functions for adding/removing the calendar resources
function addOrRem(spec){
//alert("Specialist: " + spec.name + ", Checked: " +document.getElementById(spec.name).checked);
if(document.getElementById(spec.name).checked==true){
remRes(spec.id);
addRes(spec);
}if(document.getElementById(spec.name).checked=false){
remRes(spec.id);
}
}
function addRes(spec) {
$('#calendar').fullCalendar( 'addEventResource', spec );
}
function remRes(id) {
$('#calendar').fullCalendar( 'removeEventResource', id);
}
Here is the relevant HTML
<div id='designersbox' style='float:left;margin-top:5px'>
<div id='specialists' onload='specList()'></div>
Add resource
Remove resource
</div>
<div id='calbox' style="width:1000px;height:900px;position:relative;float:left;margin-bottom:10px; padding:10px">
<div id='calendar' style="float:left;height:1000px;width:1000px;"></div>
</div>
I'm not really sure why the checkboxes are getting reset. If i comment out the calls to the add/remove functions and just do the alert, they work fine. Any help or clues would be much appreciated.
added a var, checked = document.getElementById(spec.name).checked;
Seemed to fix the problem. I'm not sure why it works, but replacing the if statements with checked==true/false instead of not using the variable fixed the issue.
new function:
function addOrRem(spec){
//$(":checkbox[value=designer]").attr("checked", true);
//alert("Specialist: " + spec.name + ", Checked: " +document.getElementById(spec.name).checked);
var checked = document.getElementById(spec.name).checked;
if(checked==true){
remRes(spec.id, '#calendard');
addRes(spec, '#calendard') ;
}if(checked==false){
remRes(spec.id, '#calendard');
}
}

Categories