jQuery close button isnt working - javascript

I have the following code:
function getdata(id){
$.ajax({
type: "POST",
url: "mapa_llamadas.php",
data: { 'id' : id },
success: function(data) {
var resultado = $.parseJSON(data);
var html = '';
var contador = 0;
for (var columna in resultado){
contador++;
if(contador == 12){
contador = 1;
}
var num_parcela = resultado[columna]['num_parcela'];
var finca_registral = resultado[columna]['finca_registral'];
var ref_catastral = resultado[columna]['ref_catastral'];
var uso_1 = resultado[columna]['uso_1'];
var uso_2 = resultado[columna]['uso_2'];
var sup_m2_parcela = resultado[columna]['sup_m2_parcela'];
var edif = resultado[columna]['edif'];
var aprov_neto_m2 = resultado[columna]['aprov_neto_m2'];
var situacion = resultado[columna]['situacion'];
var adjudicatario = resultado[columna]['adjudicatario'];
var coord = resultado[columna]['coord'];
html += '<ul><li><strong>Número de parcela:</strong> '+num_parcela+'</li><li><strong>Finca registral:</strong> '+finca_registral+'</li><li><strong>Referencia catastral:</strong> '+ref_catastral+'</li><li><strong>Uso 1:</strong> '+uso_1+'</li><li><strong>Uso 2:</strong> '+uso_2+'</li><li><strong>Superficie:</strong> '+sup_m2_parcela+' m<sup>2</sup></li><li><strong>Edificio:</strong> '+edif+'</li><li><strong>Aprovechamiento neto:</strong> '+aprov_neto_m2+' m<sup>2</sup></li><li><strong>Situación:</strong> '+situacion+'</li><li><strong>Adjudicatario:</strong> '+adjudicatario+'</li></ul>';
///alert(contador + "index:" + columna + "\n value" + resultado[columna]['num_parcela']);
}
$('#mostrarparcela').html('<button title="Cerrar ventana" class="mfp-close"><i class="mfp-close-icn">×</i></button>'+html);
}
});
}
This exact line isnt working (it should close the window that appears):
$('#mostrarparcela').html('<button title="Cerrar ventana" class="mfp-close"><i class="mfp-close-icn">×</i></button>'+html);
#mostrarparcela are a number of <area></area> tags in my html file.
What am I missing?

You have to add close function to button.
Try with
<button title="Cerrar ventana" class="mfp-close" onclick="javascript:window.close();"><i class="mfp-close"><i class="mfp-close-icn">×</i></button>

I have found what I was missing, this is what I needed to add to make the close button functionality work:
$('#mostrarparcela').html('<button id="close" title="Cerrar ventana" class="mfp-close"><i class="mfp-close-icn">×</i></button>'+html);
$( "#close" ).click(function() {
var magnificPopup = $.magnificPopup.instance;
magnificPopup.close();
});

Related

Is there way to get the corresponding item using next and next all expression of jquery

I have module regarding getting the right corresponding parent item and parent child, so to get the each item and the child I use the next and nextAll expression of jquery. I will share to you guys my output right now, and the output I want to be.
This is my output right now (Which this output is wrong)
The output should be look like this
My output in my web app. as you can see on my highlighted items there is no children however in my console log when I submit the button the highlighted item repeat the output on the first item ordered
To append the item to that list I use this code.
$("tr#productClicked").click(function () {
var menu_name = $(this).closest("tr").find(".menu_name").text();
var menu_price = $(this).closest("tr").find(".menu_price").text();
var chain_id = $(this).closest("tr").find(".chain_id").text();
var menu_image = $(this).closest("tr").find(".menu_image").attr('src');
swal({
title: "Are you sure to add " + menu_name + " ?",
text: "Once you will add it will automatically send to the cart",
icon: "warning",
buttons: true,
dangerMode: true,
})
.then((willInsert) => {
if (willInsert) {
swal("Successfully Added to your form.", {
icon: "success",
});
if(chain_id == 0) {
$("tbody#tbody_noun_chaining_order").
append("<tr class='condimentParent' style='background-color:'black !important',color:'white !important' '><td></td><td>"+menu_name+"</td><td class='total'>"+menu_price+"</td><td><button class='removeorderWithOutCondi btn btn-danger form-control'><i class='far fa-trash-alt'></i></button></td></tr>");
}
else
{
$.ajax({
url:'/get_noun_group_combination',
type:'get',
data:{chain_id:chain_id},
success:function(response){
var noun_chaining = response[0].noun_chaining;
$("tbody#tbody_noun_chaining_order").
append("<tr class='condimentParent' style='background-color:'black !important',color:'white !important' '><td></td><td>"+menu_name+"</td><td class='total'>"+menu_price+"</td><td><button class='removeorderWithCondi btn btn-danger form-control'><i class='far fa-trash-alt'></i></button></td></tr>");
$.each(noun_chaining, function (index, el) {
var stringify_noun_chaining = jQuery.parseJSON(JSON.stringify(el));
// console.log(stringify['menu_cat_image']);
var Qty = stringify_noun_chaining['Qty'];
var Condiments = stringify_noun_chaining['Condiments'];
var Price = stringify_noun_chaining['Price'];
var allow_to_open_condiments = stringify_noun_chaining['allow_to_open_condiments'];
var condiments_section_id = stringify_noun_chaining['condiments_section_id'];
$("tbody#tbody_noun_chaining_order").
append("<tr class='editCondiments'>\
<td class='condiments_order_quantity'>"+Qty+"</td>\
<td>*"+Condiments+"</td><td class='total'>"+Price+"</td>\
<td class='allow_to_open_condiments_conditional' style='display:none;'>"+allow_to_open_condiments+"</td>\
<td class='condi_section_id' style='display:none;'>"+condiments_section_id+"</td>\
</tr>");
})
},
error:function(response){
console.log(response);
}
});
}
}
});
This is my add to cart button when inserting the item to the database.
$('button#add_to_cart').on('click',function () {
var customer_id = $('#hidden_customer_id').val();
$parent = $(this).closest("tr.condimentParent");
var menu= $('#noun_chaining_order').find('tr.condimentParent');
menu.next('.condimentParent').add(menu).each(function(){
if(menu.length > 0 ) {
var $tds_menu = $(this).find("td");
Qty_menu = $tds_menu.eq(0).text(),
Item_menu = $tds_menu.eq(1).text(),
Price_menu = $tds_menu.eq(2).text();
console.log(Item_menu);
var condiments= $('#noun_chaining_order').find('tr.editCondiments');
condiments.nextAll('.editCondiments').add(condiments).each(function(){
var $tds_condiments = $(this).find("td");
Qty_condiments = $tds_condiments.eq(0).text(),
Item_condiments = $tds_condiments.eq(1).text(),
Price_condiments = $tds_condiments.eq(2).text();
console.log(Item_condiments);
});
}
});
});
To solved my problem i use multiple add
$('button#add_to_cart').on('click',function () {
var customer_id = $('#hidden_customer_id').val();
$parent = $(this).closest("tr.condimentParent");
var condiments= $('#noun_chaining_order').find('tr.editCondiments');
var menu= $('#noun_chaining_order').find('tr.condimentParent');
menu.next('.condimentParent').add(menu).add(condiments).each(function(){
var $tds_menu = $(this).find("td");
Qty_menu = $tds_menu.eq(0).text(),
Item_menu = $tds_menu.eq(1).text(),
Price_menu = $tds_menu.eq(2).text();
console.log(Item_menu);
// condiments.nextAll('.editCondiments').add(condiments).each(function(){
// var $tds_condiments = $(this).find("td");
// Qty_condiments = $tds_condiments.eq(0).text(),
// Item_condiments = $tds_condiments.eq(1).text(),
// Price_condiments = $tds_condiments.eq(2).text();
// console.log(Item_condiments);
// });
});
});

Anchor tag not working with dynamic table

The anchor link is not working when I construct a dynamic table with javascript.
Code:
$(".genareteEmail").click(
function() {
alert("sdsds");
var incidentNo = $(this).attr('dataId');
$.ajax({
url : "generate?incident=" + incidentNo,
method : 'GET',
success : function(data) {
var subject = data;
var content = subject.split("END");
try {
var outlookApp = new ActiveXObject(
"Outlook.Application");
var nameSpace = outlookApp
.getNameSpace("MAPI");
mailFolder = nameSpace
.getDefaultFolder(6);
mailItem = mailFolder.Items
.add('IPM.Note.FormA');
mailItem.Subject = content[3];
mailItem.cc = content[2];
mailItem.To = content[1];
mailItem.HTMLBody += content[0];
var insp = mailItem.GetInspector;
var mySigline = mailItem.HTMLBody;
mailItem.display(0);
} catch (e) {
alert(e);
// act on any error that you get
}
}
});
});
$("#btnSubmit").click(function(){
callMe();
});
function callMe() {
$.ajax({
url : "ajaxTicketInfo",
type : 'GET',
error : function() {
},
success : function(result) {
var ticketCount = result.length;
var mytable = $('<table></table>');//.attr({ id: "basicTable" });
var rows = ticketCount;
var cols = 2;
var tr = [];
$('<tr></tr>').html("<th>Incidents</th><th>Mail Generation</th>").appendTo(mytable);
for (var i = 0; i < rows; i++) {
var row = $('<tr></tr>').appendTo(mytable);
for (var j = 0; j < cols; j++) {
if(j== 0){
$('<td></td>').text(result[i] + " "+ Math.random()).appendTo(row);
}else{
//var aTag = $('<a></a>').attr({ dataId: result[i] });
$('<td></td>').html('<a class="genareteEmail" href="#" dataId ="'+result[i]+'">Generate Email</a>').appendTo(row);
/* $('<td></td>').text("Generate Mail").append(row); */
}
}
}
$("#box").html(mytable);
},
cache: false
});
};
setInterval(callMe, 900000);
});
<body>
<h1>Acknowledgement Mail Generation</h1>
<div>
<div>
Next Refresh will be in <span id="time">05:00</span> minutes!
</div>
<div>
<button id = "btnSubmit">Refresh</button>
</div>
</div>
HTML Code:
<div id="box">
<table>
<tbody>
<tr><th>Incidents</th><th>Mail Generation</th></tr>
<tr><td>INC000013610276 0.15926314527814805</td><td>
<a class="generateEmail" href="#" dataid="INC000013610276">Generate
Email</a></td></tr>
<tr><td>INC000013608353 0.7894190043310691</td><td>
<a class="generateEmail" href="#" dataid="INC000013608353">Generate
Email</a></td></tr>
<tr><td>INC000013594620 0.8572899023472066</td><td>
<a class="generateEmail" href="#" dataid="INC000013594620">Generate
Email</a></td></tr>
<tr><td>INC000013592053 0.02202170976246076</td><td>
<a class="generateEmail" href="#" dataid="INC000013592053">Generate Email</a>
</td>
</tr>
</tbody>
</table>
</div>
As per my code when I click the corresponding anchor link the .genarateEmail jquery need to be executed. But the click functionality is not working.
Can anybody help me where I made wrong while creating the dynamic table.
All the events should be bound once the document is ready. Hence include your method within the document ready as commented by #Mark B
$(document).ready(function(){
$(".genareteEmail").click( function(){
//Your logic
})
})

Put some style on each value of an array with jquery

i would that : If my status is equal to "open" I have the background-color yellow or if it's equal to "closed" I have the background-color red etc.... but i don't succeed it can you help me pls ?:
script.js :
//fonction pour afficher les tickets de l'associé
function displaytickets(y){
console.log(y);
var newid = {};
$("#mylist").empty();
$("#nbtick").html("");
$("#mycontent").html("");
$("#name").html("");
var newv = y;
$.ajax({
url: "https://cubber.zendesk.com/api/v2/users/"+y+"/tickets/requested.json?sort_by=date",
type: 'GET',
dataType: 'json',
cors: true ,
contentType:'application/json',
secure: true,
beforeSend: function (xhr) {
xhr.setRequestHeader ("Authorization", "Basic " + btoa(""));
},
success: function (data){
var sortbydate = data.tickets.sort(function(a,b){ return new Date(b.created_at)- new Date(a.created_at); });
var named = data.tickets[0].via.source.from.name;
localStorage.setItem("namestock", named);
for (i = 0; i < data.tickets.length; i++) {
var myticket = data.tickets[i];
var mydate = data.tickets[i].created_at;
var created = moment(mydate).format("MM-DD-YY");
var mytitle = data.tickets[i].subject;
var description = data.tickets[i].description;
var status = data.tickets[i].status;
var myid = data.tickets[i].id;
switch(status){
case "open":
console.log("open")
$("")
break;
case "closed":
console.log("closed")
break;
case "pending":
console.log("pending")
break;
case "solved":
console.log("solved")
break;
}
localStorage.setItem("mydescription", description);
$("#mylist").append('<li class="row col-md-12" id="newlist" value="'+myid+'" onclick="ticketcontent('+myid+')">'+ '<div class="open">'+status+ '</div>'+'<div class="identifiant col-md-2">'+" #"+ myid +'</div>'+'<div class="identifiant col-md-6">'+mytitle +'</div>'+'<div class="identifiant col-md-2">'+created+'</div>'+'</li><hr><br>')
}
var nbticket = data.tickets.length;
var monnom = localStorage.getItem("namestock");
$("#name").append('<h2 class="title">'+monnom+" "+nbticket+" ticket(s)"+'</h2>');
localStorage.clear();
},
});
$("#idisplay").css("display", "none");
}
and here what i get it is not the right colors !:
Put this CSS
.class_closed{
background-color:#ff0000;
}
.class_open{
background-color:#fff000;
}
now in jQuery append this (assuming status is the variable storing the status either open or closed)
<span class="class_'+status+' otherClasses">' + status + '</span>

Ajax change text on page

Hello i have some html like this:
<div class="col-md-4" id="sk6x4">
<a href="/razbornye/models6x4/sk6x4">
<span class="sceneName">СК6x4</span> <span class="scenePrice">671 384p.</span></a>
</div>
<div class="col-md-4" id="sk6x4">
<a href="/razbornye/models6x4/sk6x4">
<span class="sceneName">СК6x4</span> <span class="scenePrice">671 384p.</span></a>
</div>
<div class="col-md-4" id="sk6x4">
<a href="/razbornye/models6x4/sk6x4">
<span class="sceneName">СК6x4</span> <span class="scenePrice">671 384p.</span></a>
</div>
And some JS:
jQuery(document).ready(function($) {
var col = $('.preview').find('.col-md-4 .sceneName');
var urls = [];
var ids = [];
col.each(function(i) {
var yy = $(this).closest('.col-md-4').find('a').attr('href');
var xx = $(this).closest('.col-md-4').attr('id');
urls.push(yy);
ids.push(xx);
});
var dataUrls = function() {
$.each(urls, function (i, url) {
$.ajax({
url: url,
type: 'POST',
success: function (data) {
var apronFactor = (($(data).find('.table.table-bordered tr:eq(6) td:eq(2)').text()).replace(/\s+/g, ''))*1;
var apronPrice = ($(data).find('.table.table-bordered tr:eq(6) td:eq(3)').text()).replace(/\s+/g, '');
var apronPriceMR = apronPrice.substring(0, apronPrice.length - 2);
var apronPriceToNum = apronPriceMR*1;
var apronTotalPrice = apronFactor * apronPriceToNum;
/**/
var plankFactor = (($(data).find('.table.table-bordered tr:eq(7) td:eq(2)').text()).replace(/\s+/g, ''))*1;
var plankPrice = ($(data).find('.table.table-bordered tr:eq(7) td:eq(3)').text()).replace(/\s+/g, '');
var plankPriceMR = plankPrice.substring(0, plankPrice.length - 2);
var plankPriceToNum = plankPriceMR*1;
var plankTotalPrice = plankFactor * plankPriceToNum;
/**/
var tentFactor = (($(data).find('.table.table-bordered tr:eq(8) td:eq(2)').text()).replace(/\s+/g, ''))*1;
var tentPrice = ($(data).find('.table.table-bordered tr:eq(8) td:eq(3)').text()).replace(/\s+/g, '');
var tentPriceMR = tentPrice.substring(0, tentPrice.length - 2);
var tentPriceToNum = tentPriceMR*1;
var tentTotalPrice = tentFactor * tentPriceToNum;
/**/
var totalOptionsPrice = apronTotalPrice + plankTotalPrice + tentTotalPrice;
/**/
var complexWithoutOptionsPrice = ($(data).find('#cel_1 > .value').text()).replace(/\s+/g, ''); //cWOP
var cWOPMR = complexWithoutOptionsPrice.substring(0, complexWithoutOptionsPrice.length - 2);
var cWOPToNum = cWOPMR * 1;
/**/
var newTotalPrice = cWOPToNum + totalOptionsPrice;
var newTotalPriceToString = newTotalPrice.toString().replace(/\B(?=(\d{3})+(?!\d))/g, " ") + "р.";
$(ids[i] + ' .scenePrice').text(newTotalPriceToString));
}
});
});
}
dataUrls();
});
The task is:
Take prices from another page and replace price on this page
The problem is
$(ids[i] + ' .scenePrice').text(newTotalPriceToString));
It's not work.
Replace this line:
$(ids[i] + ' .scenePrice').text(newTotalPriceToString));
With:
$('#'+ids[i] + ' .scenePrice').text(newTotalPriceToString));
I guess you are just passing the string of id but not # along with it.
try to find out why is problematic line not working:
alert(ids[i] + ' .scenePrice'); //check whether your selector is correct
alert($(ids[i] + ' .scenePrice').length); //check whether jQuery matched element
But from the look at your code, you are probably just missing '#' in front of id.

How can I load images in a loop correctly?

I have a loop that calls a function that loads images. It is not working correctly. The images all load but they all get appended to the last div.
For this example, I have three divs on my page:
<div id="opening_0"></div>
<div id="opening_1"></div>
<div id="opening_2"></div>
Javascript:
$.ajax(
{
type: "GET",
url: xml_source, //call this url - SEE XML BELOW
dataType: 'xml',
async: false,
success: function(xml) //if we have data...
{
openings = $(xml).find("opening"); //Find the openings in the xml
mattes_create_openings(openings);
}
});
function mattes_create_openings(openings)
{
$(openings).each(function(i, el) //loop through the openings xml
{
//more code...
var photos_selected_fid = $(el).find("imgsrc").text();
clipX = 0;
clipY = 0;
photos_create_preview_image(document.getElementById("opening_" + i), clipX, clipY, photos_selected_fid);
});
}
function photos_create_preview_image(element, clipX, clipY, photos_selected_fid)
{
photos_selected_opening = element.id; //Sets the selected opening to the div that calls this function
photos_selected_opening_value = photos_selected_opening.replace("opening_", "");
var new_img = new Image();
new_img.onload = function()
{
$(element).empty(); //Empty the div
element.appendChild(new_img); //Append the image to the div
}
new_img.src = SITE_URL + "/system/photo/cf_preview/" + photos_selected_fid; //Set the source of the image
}
XML that is loaded:
<?xml version="1.0"?>
<Order>
<size width="20" height="10">
<width>20</width>
<height>10</height>
</size>
<type>photo</type>
<overlay/>
<Mats selected_type="17" selected_design="81">
<mat layer_name="top">
<item size="0">
<imgsrc>11852997eab43ff5c7b1803692bee608</imgsrc>
<size>0</size>
<cpu/>
<cid>4208</cid>
<id/>
</item>
<fillet index="0">
<imgsrc>5ade25e607b6302691c318a94792e6eb</imgsrc>
<width>0.31</width>
<cid>9349</cid>
<sku>TD00060GL1</sku>
</fillet>
</mat>
</Mats>
<Openings>
<opening>
<item>
<x>7.75</x>
<y>1.75</y>
<width>4.5</width>
<height>6.5</height>
<type>rectangle</type>
<clipX>0</clipX>
<clipY>0</clipY>
<imgsrc>a0d3b6664b2fef68c279c5f58e6af5d6</imgsrc>
<photos_hires_width>1024</photos_hires_width>
<photos_hires_height>768</photos_hires_height>
</item>
</opening>
<opening>
<item>
<x>14</x>
<y>2.25</y>
<width>3.5</width>
<height>5.5</height>
<type>rectangle</type>
<clipX>0</clipX>
<clipY>0</clipY>
<imgsrc>148d39e78620ed03dc6bf0fee199ec97</imgsrc>
<photos_hires_width>1024</photos_hires_width>
<photos_hires_height>768</photos_hires_height>
</item>
</opening>
<opening>
<item>
<x>2.5</x>
<y>2.25</y>
<width>3.5</width>
<height>5.5</height>
<type>rectangle</type>
<clipX>0</clipX>
<clipY>0</clipY>
<imgsrc>971e9044a3f1fca2291d62d64470a1bd</imgsrc>
<photos_hires_width>1024</photos_hires_width>
<photos_hires_height>768</photos_hires_height>
</item>
</opening>
</Openings>
<Moulding>
<imgsrc>5f52a13c425655fa62058418542b95ca</imgsrc>
<width>1.13</width>
<cid>174</cid>
<sku>TD01600B0</sku>
<cpu>0.00</cpu>
</Moulding>
<Glass>
<cid>GAPC</cid>
</Glass>
</Order>
I have a jsfiddle: http://jsfiddle.net/allisonc/am83wp4m/1/
When I run the jsfiddle, it tries set the source as all of them combined (ex: SITE_URL + "/system/photo/cf_preview/" + imgsrc1 + imgsrc2 + imgsrc3)
See: http://jsfiddle.net/allisonc/am83wp4m/2/
var openings = document.createElement("Openings");
var opening1 = document.createElement("opening");
var imgsrc1 = document.createElement("imgsrc");
imgsrc1.appendChild(document.createTextNode("a0d3b6664b2fef68c279c5f58e6af5d6"));
opening1.appendChild(imgsrc1);
openings.appendChild(opening1);
var opening2 = document.createElement("opening");
var imgsrc2 = document.createElement("imgsrc");
imgsrc2.appendChild(document.createTextNode("148d39e78620ed03dc6bf0fee199ec97"));
opening2.appendChild(imgsrc2);
openings.appendChild(opening2);
var opening3 = document.createElement("opening");
var imgsrc3 = document.createElement("imgsrc");
imgsrc3.appendChild(document.createTextNode("971e9044a3f1fca2291d62d64470a1bd"));
opening3.appendChild(imgsrc3);
openings.appendChild(opening3);
var new_openings = $(openings).find("opening");
mattes_create_openings(new_openings);
function mattes_create_openings(openings)
{
$(openings).each(function(i, el) //loop through the openings xml
{
console.log(el);
console.log(i);
//more code...
var photos_selected_fid = $(el).find("imgsrc").text();
console.log(photos_selected_fid);
clipX = 0;
clipY = 0;
//photos_create_preview_image(document.getElementById("opening_" + i), clipX, clipY, photos_selected_fid);
photos_create_preview_image(document.getElementById("opening_" + i), clipX, clipY, photos_selected_fid);
});
}
function photos_create_preview_image(element, clipX, clipY, photos_selected_fid)
{
var photos_selected_opening = element.id; //Sets the selected opening to the div that calls this function
var photos_selected_opening_value = photos_selected_opening.replace("opening_", "");
var new_img = new Image();
new_img.onload = function()
{
$(element).empty(); //Empty the div
element.appendChild(new_img); //Append the image to the div
}
new_img.src = "http://example.com" + "/system/photo/cf_preview/" + photos_selected_fid; //Set the source of the image
}
May be like this
var yourxml = '<your xml data>';
$($.parseXML(yourxml)).find('opening').each(function (index, opening) {
$('#opening_'+index).html('<img src= "http://example.com/system/photo/cf_preview/"' + $(opening).find('imgsrc').text() + ' />');
});
Your code is correct except one thing: I pasted it the following plunker, adjusted to have valid images and separate divs backgrounds and saw an issue in your iteration. Indeed, jQuery's .each() iterates from index 0, which mean you either should use i + 1 or create opening_# containers from 0
http://plnkr.co/edit/8zrEfRfq1dtAeX5voUfK?p=preview
See in the Plunker:
photos_create_preview_image(document.getElementById("opening_" + (i+1)), clipX, clipY);
Note that I separated opening_#s with background color:
<div id="opening_1" style="background:red"></div>
<div id="opening_2" style="background:green"></div>
<div id="opening_3" style="background:blue"></div>
<!-- Include your script AFTER your image containers -->
<script src="script.js"></script>
Ensure your js script is included after your DOM elements (at the end of your HTML's body)

Categories

Resources