Ajax change text on page - javascript

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.

Related

html not appending to the carousel on popover

I Am Trying to make a popover with a bootstrap carousel and where the carousel items are to be generated and appended from a script but I get the carousel but I am unable to append the item. I tried hard but I didn't come up with a solution.
the HTML initialized is as below
HTML:
<div class="popup" data-popup="popup-1">
<div class="popup-inner">
<i class="fas fa-bars"></i>
<div class="frame">
<div id='carousel' class='carousel slide' data-bs-ride='carousel'>
<div class='carousel-inner items-slider1'>
</div>
</div>
</div>
</div>
</div>
the script I have tried was
Javascript:
function findallchord(currentchord , currenttype) {
for (let i = 1; i < 10; i++) {
if (Raphael.chord.find(currentchord ,currenttype,i)) {
Raphael.chord("div3", Raphael.chord.find(currentchord , currenttype,i), currentchord +' ' +currenttype).element.setSize(75, 75);
}
}
}
var getChordRoots = function (input) {
if (input.length > 1 && (input.charAt(1) == "b" || input.charAt(1) == "#"))
return input.substr(0, 2);
else
return input.substr(0, 1);
};
$('.popup').on('shown.bs.popover', function () {
$('.carousel-inner').carousel();
});
$('[data-bs-toggle="popover"]').popover({
html: true,
content: function() {
return $('.popup').html();
}}).click(function() {
var oldChord = jQuery(this).text();
var currentchord = getChordRoots(oldChord);
var currenttype = oldChord.substr(currentchord.length);
findallchord(currentchord , currenttype);
var chordsiblings = $('#div3').children().siblings("svg");
for (let i = 1; i < 10; i++) {
if (Raphael.chord.find(currentchord , currenttype,i)) {
var itemid = "chord" + i;
var theDiv = "<div class='carousel-item"+((itemid=="chord1") ? ' active':'')+" ' id='"+currentchord+''+itemid+"'> "+chordsiblings[i-1].outerHTML+" </div>";
$('.items-slider1').append(theDiv);
}
}
});
I have also tried appendTo also as
$(theDiv).appendTo('.items-slider1');
Please Help to solve this
This is the output I get, the appended elements are not in the carousel
Note: I am using Bootstrap 5
Try instantiating the carousel after you've set it up
/*
$('.popup').on('shown.bs.popover', function () {
$('.carousel-inner').carousel();
});
*/
$('[data-bs-toggle="popover"]').popover({
html: true,
content: function() {
return $('.popup').html();
}}).click(function() {
var oldChord = jQuery(this).text();
var currentchord = getChordRoots(oldChord);
var currenttype = oldChord.substr(currentchord.length);
findallchord(currentchord , currenttype);
var chordsiblings = $('#div3').children().siblings("svg");
for (let i = 1; i < 10; i++) {
if (Raphael.chord.find(currentchord , currenttype,i)) {
var itemid = "chord" + i;
var theDiv = "<div class='carousel-item"+((itemid=="chord1") ? ' active':'')+" ' id='"+currentchord+''+itemid+"'> "+chordsiblings[i-1].outerHTML+" </div>";
$('.items-slider1').append(theDiv);
}
}
$('.carousel-inner').carousel();
});
It was needed to do call the click function first before popover as below
$('[data-bs-toggle="popover"]').click(function() {
var oldChord = jQuery(this).text();
var currentchord = getChordRoots(oldChord);
var currenttype = oldChord.substr(currentchord.length);
findallchord(currentchord , currenttype);
var chordsiblings = $('#div3').children().siblings("svg");
for (let i = 1; i < 10; i++) {
if (Raphael.chord.find(currentchord , currenttype,i)) {
var itemid = "chord" + i;
var theDiv = "<div class='carousel-item"+((itemid=="chord1") ? ' active':'')+" ' id='"+currentchord+''+itemid+"'> "+chordsiblings[i-1].outerHTML+" </div>";
$('.items-slider1').append(theDiv);
}
}
}).popover({
html: true,
content: function() {
return $('.popup').html();
}});

I remove a file that I uploaded, I got a error

When I remove a file that I uploaded, I got a error. That is js:42 Uncaught TypeError: Cannot read property 'removeChild' of null. I have to use removeChild and var for IE. Is there a good way to fix the error?
html
<form action="" enctype="multipart/form-data" class="page_form">
<label class="ui_upload upload_label" for="upload-doc">
<input type="file" name="file" id="upload-doc"
accept=".pdf,.doc,.docx,application/msword,application/vnd.openxmlformats-officedocument.wordprocessingml.document"
multiple />
<span class="btn sm label upload_btn">upload file</span>
</label>
<div class="upload_documents_wrap visually_hide">
<div class="upload_documents"> </div>
</div>
<div class="visually_hide" id="upload-file">
<div class="upload_info shadow light upload_file">
<span class="tit sm file_name"> </span>
<span class="tit sm file_size"> </span>
<button class="file_remove" type="button">Remove</button>
</div>
</div>
<button type="submit" class="btn sm">submit</button>
</form>
js
(function () {
var formElement = document.querySelector(".page_form");
var fileChooserEl = formElement.querySelector('.upload_label input[type="file"]');
var uploadDocumentsWrap = formElement.querySelector(".upload_documents_wrap");
var uploadDocuments = uploadDocumentsWrap.querySelector(".upload_documents");
var templateItemParent = document.querySelector("#upload-file");
var templateItem = templateItemParent.querySelector(".upload_file");
var uploadFiles = [];
var myFileList = [];
var onFileChooserChange = function () {
for (var i = 0; i < fileChooserEl.files.length; i++) {
var position = templateItem.cloneNode(true);
var uploadFileName = position.querySelector(".file_name");
var uploadFileSize = position.querySelector(".file_size");
var uploadFileRemove = position.querySelector(".file_remove");
var fileName = fileChooserEl.files[i].name.toLowerCase();
uploadDocumentsWrap.classList.remove("visually_hide");
uploadFileName.textContent = fileName; // file size
var suffix = "bytes";
var size = fileChooserEl.files[i].size;
if (size >= 1024 && size < 1024000) {
suffix = "KB";
size = Math.round(size / 1024 * 100) / 100;
} else if (size >= 1024000) {
suffix = "MB";
size = Math.round(size / 1024000 * 100) / 100;
}
uploadFileSize.textContent = size + suffix;
uploadFileRemove.addEventListener("click", function (evt) {
evt.preventDefault();
myFileList = myFileList.filter(function (item) {
return item.name.toLowerCase() !== uploadFileRemove.previousElementSibling.textContent;
});
console.log(myFileList);
var index = uploadFiles.indexOf(evt.target.parentNode);
uploadFileRemove.parentNode.parentNode.removeChild(uploadFileRemove.parentNode);
uploadFiles.splice(index, 1);
myFileList.splice(index, 1);
console.log(index);
if (!uploadFiles.length) {
uploadDocumentsWrap.classList.add("visually_hide");
}
});
uploadDocuments.appendChild(position);
uploadFiles.push(position);
myFileList.push(fileChooserEl.files[i]);
}
fileChooserEl.value = "";
};
console.log(uploadFiles);
var getFormData = function () {
var data = new FormData(formElement);
for (var i = 0; i < myFileList.length; i += 1) {
data.append(fileChooserEl.name, myFileList[i]);
}
return data;
};
fileChooserEl.addEventListener("change", onFileChooserChange);
})();
The error is on this line:
uploadFileRemove.parentNode.parentNode.removeChild(uploadFileRemove.parentNode);
I debugged the code and find that you removed wrong file every time when clicking the "Remove" button. It's easier and more clear to identify which file to remove using index. I edit the code like this and it works well:
...
var index = uploadFiles.indexOf(evt.target.parentNode);
//edit
var removefile = document.querySelectorAll(".upload_info")[index];
uploadDocuments.removeChild(removefile);
//uploadFileRemove.parentNode.parentNode.removeChild(uploadFileRemove.parentNode);
uploadFiles.splice(index, 1);
myFileList.splice(index, 1);
console.log(index);
...
Result:

jQuery formatting negative numbers

I am working on a local weather site through freecodecamp. I was wondering if anyone could help me figure out how to assign jQuery to show parenthesis around negative numbers. i.e. when it is -5 degrees I am trying to get it to say (-5).
Here is the jQuery I am currently working with...
$(document).ready(function() {
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(function(position) {
var long;
var lat;
lat = position.coords.latitude;
long = position.coords.longitude;
var api = "http://api.openweathermap.org/data/2.5/weather?lat=" + lat + "&lon=" + long + "&appid=79b001616877b59c717616181ee219ec";
$.getJSON(api, function(info) {
var farh;
var cels;
var kelvin;
var tempMin;
var minTemp;
var tempMax;
var maxTemp;
var tempMinC;
var minTempC;
var tempMaxC;
var maxTempC;
var strF = ("\u00B0'F'");
var tempSwitch = false;
kelvin = info.main.temp;
farh = Math.round((kelvin) * (9 / 5) - 459.67);
cels = Math.round(kelvin - 273);
tempMinC = info.main.temp_min;
minTempC = Math.round(tempMinC - 273);
tempMaxC = info.main.temp_max;
maxTempC = Math.round(tempMaxC - 273);
tempMin = info.main.temp_min;
minTemp = Math.round((tempMin) * (9 / 5) - 459.67);
tempMax = info.main.temp_max;
maxTemp = Math.round((tempMax) * (9 / 5) - 459.67);
var city = info.name;
var weatherInfo = info.weather[0].description;
var forecastLow = minTemp;
var forecastHigh = maxTemp;
var forecastLowC = minTempC;
var forecastHighC = maxTempC;
var currCond = info.weather[0].icon;
$('#farh').html(farh);
$('#city').html(city);
$('#weatherInfo').html(weatherInfo);
$('#forecastLow').html(forecastLow);
$('#forecastHigh').html(forecastHigh);
$('#currCond').html(currCond);
$('#switch').click(function() {
if (tempSwitch === false) {
$('#farh').html(cels);
$('#forecastLow').html(forecastLowC)
$('#forecastHigh').html(forecastHighC)
tempSwitch = true;
} else {
$('#farh').html(farh);
$('#forecastLow').html(forecastLow);
$('#forecastHigh').html(forecastHigh);
tempSwitch = false;
}
});
});
});
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.3/jquery.min.js"></script>
<h2 class="weather-header" id="city"></h2>
<h1><span class="curr-temp" id="farh"></span><span class="curr-temp">&deg</span></h1>
<div class="col-md-5"></div>
<div class="col-md-2">
<label class="switched">
<input type="checkbox" id="switch">
<div class="slider"></div>
</label>
</div>
<div class="col-md-5"></div>
<h3><span class="hi-lo" id="forecastLow"></span> Low - <span class="hi-lo" id="forecastHigh"></span> High</h3>
<p class="forecast" id="weatherInfo"></p>
You can create a function like this to format your Output:
function formatTemperature(value){
if(value < 0)
return "(" + value + ")";
else
return value;
};
and wrap your values calling this function, passing the values.
I've updated your snippet example.
$(document).ready(function() {
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(function(position) {
var long;
var lat;
lat = position.coords.latitude;
long = position.coords.longitude;
var api = "http://api.openweathermap.org/data/2.5/weather?lat=" + lat + "&lon=" + long + "&appid=79b001616877b59c717616181ee219ec";
$.getJSON(api, function(info) {
var farh;
var cels;
var kelvin;
var tempMin;
var minTemp;
var tempMax;
var maxTemp;
var tempMinC;
var minTempC;
var tempMaxC;
var maxTempC;
var strF = ("\u00B0'F'");
var tempSwitch = false;
kelvin = info.main.temp;
farh = Math.round((kelvin) * (9 / 5) - 459.67);
cels = Math.round(kelvin - 273);
tempMinC = info.main.temp_min;
minTempC = Math.round(tempMinC - 273);
tempMaxC = info.main.temp_max;
maxTempC = Math.round(tempMaxC - 273);
tempMin = info.main.temp_min;
minTemp = Math.round((tempMin) * (9 / 5) - 459.67);
tempMax = info.main.temp_max;
maxTemp = Math.round((tempMax) * (9 / 5) - 459.67);
var city = info.name;
var weatherInfo = info.weather[0].description;
var forecastLow = minTemp;
var forecastHigh = maxTemp;
var forecastLowC = minTempC;
var forecastHighC = maxTempC;
var currCond = info.weather[0].icon;
function formatTemperature(value){
if(value < 0)
return "(" + value + ")";
else
return value;
}
$('#farh').html(farh);
$('#city').html(city);
$('#weatherInfo').html(weatherInfo);
$('#forecastLow').html(forecastLow);
$('#forecastHigh').html(forecastHigh);
$('#currCond').html(currCond);
$('#switch').click(function() {
if (tempSwitch === false) {
$('#farh').html(formatTemperature(cels));
$('#forecastLow').html(formatTemperature(forecastLowC));
$('#forecastHigh').html(formatTemperature(forecastHighC));
tempSwitch = true;
} else {
$('#farh').html(formatTemperature(farh));
$('#forecastLow').html(formatTemperature(forecastLow));
$('#forecastHigh').html(formatTemperature(forecastHigh));
tempSwitch = false;
}
});
});
});
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.3/jquery.min.js"></script>
<h2 class="weather-header" id="city"></h2>
<h1><span class="curr-temp" id="farh"></span><span class="curr-temp">&deg</span></h1>
<div class="col-md-5"></div>
<div class="col-md-2">
<label class="switched">
<input type="checkbox" id="switch">
<div class="slider"></div>
</label>
</div>
<div class="col-md-5"></div>
<h3><span class="hi-lo" id="forecastLow"></span> Low - <span class="hi-lo" id="forecastHigh"></span> High</h3>
<p class="forecast" id="weatherInfo"></p>

Google Chrome Local Storage Adding Links

So I'm trying to add an option on my options page for people to set 1-3 letters as a link to a website. Currently I'm getting a NaN value for the linkNumber when I run the function.
The Function:
function addLink () {
chrome.storage.local.get('linkNumber', function (x) {
if (x.linkNumber == undefined) {
chrome.storage.local.set({'linkNumber': '0'}, function() {
addLink();
});
} else {
var linkNumberInteger = parseInt(x.linkNumber);
var handle = document.getElementById("short");
var link = document.getElementById("long");
var handleValue = handle.value;
var linkValue = link.value;
var handleNumber = x.linkNumber + '-handle';
var urlNumber = x.linkNumber + '-link';
var objectOne = {};
var objectTwo = {};
objectOne[handleNumber] = x.linkNumber + '-handle';
objectTwo[urlNumber] = x.linkNumber + '-link';
console.log(x.linkNumber);
console.log(handleNumber);
chrome.storage.local.set({handleNumber: handleValue}, function(y) {
console.log(y.handleNumber + ' handle saved');
});
chrome.storage.local.set({urlNumber: linkValue}, function(z) {
console.log(z.handleNumber + ' link saved');
});
var linkNumberIntegerNext = linkNumberInteger++;
var n = linkNumberIntegerNext.toString();
chrome.storage.local.set({'linkNumber': n}, function() {
});
alert('Link Added');
}
});
}
The Html:
<h3 class="option">Add Quick Link:</h3>
<input contenteditable="true" type="text" class="short-quicklink" id="short" maxlength="3">
<span>http://</span><input contenteditable="true" type="text" class="long-quicklink" id="long">
<button class="add">Add Quick Link</button>

jQuery close button isnt working

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();
});

Categories

Resources