How to take data .on change function? - javascript

i have this function in MVC View:
$(document).ready(function() {
colSum55();
});
function colSum55() {
var sumPP = 0;
var x = ($("[name='popust']").val());
var t = 0;
$(".Total").each(function() {
sumPP += parseFloat($(this).text());
});
t = (((sumPP) - ((sumPP) * (x / 100))));
var y = 0;
y = ($('#TotalPPO1').val((t).toFixed(0).replace(/(\d)(?=(\d{3})+(?!\d))/g, "$1.") + " €"));
}
$(function() {
$("[name='popust']").on("change", function() {
$("#TotalPPO").val($("#y").val());
});
});
in this function $("#y").val() not take data, where is the problem?
I want to take data on change value inputed in name='popust' field.

I solved and here is the solution which i need:
$(document).ready(function () {
colSum55();
});
function colSum55() {
$("[name='popust']").on("change", function () {
var pp = 0;
pp = $("#popust1").val($(this).val());
var sumPP = 0;
var x = ($(pp).val());
var t = 0;
var y = 0;
//iterate through each input and add to sum
$(".Total").each(function () {
sumPP += parseFloat($(this).text());
});
t = (((sumPP) - ((sumPP) * (x / 100))));
$('#TotalPPO').html((t).toFixed(0).replace(/(\d)(?=(\d{3})+(?!\d))/g, "$1.") + " €");
});
}

Related

Delete legend when updating leaflet map

I have this code for a map that I want to update based on a campaign (2 different json files) (I cut the first part of the code because If not I couldn't post the question)
// Load in GeoJson data
var geoData = "static/data/dma_shp.json";
var dmaData = "static/data/dma_info.json";
var geojson;
var dmajson;
window.getData = function() {
var e = document.getElementById("selCamp");
var v = e.value;
console.log(v)
if (v == "campaign1") { dmaData = "static/data/dma_info.json"; } else if (v == "campaign2") { dmaData = "static/data/dma_info2.json"; }
// console.log(dmaData)
}
//Grab data with d3
d3.json(geoData, data => {
console.log(data.features)
d3.json(dmaData, data_legend => {
const vcr_array = Object.values(data_legend);
vcr_array.sort();
const len = vcr_array.length;
var per16 = Math.floor(len * .166) - 1;
var per33 = Math.floor(len * .332) - 1;
var per50 = Math.floor(len * .498) - 1;
var per66 = Math.floor(len * .664) - 1;
var per83 = Math.floor(len * .83) - 1;
function getColor(d) {...
} // END of getColor
for (let i = 0; i < data.features.length; i++) {
const curr_dma = data.features[i].properties.dma
var filtered = Object.fromEntries(Object.entries(data_legend).filter(([k, v]) => k == curr_dma));
for (var key in filtered) {
const key_value = filtered[key]
data.features[i].properties.vcr_value = key_value;
}
};
geojson = L.geoJson(data, {
onEachFeature(feature, layer) {
layer.on({
mouseover: highlightFeature,
mouseout: resetHighlight,
click: function(event) {
myMap.fitBounds(event.target.getBounds());
}
});
layer.bindPopup(...).addTo(myMap)
var legend = L.control({ position: 'topright' });
legend.onAdd = function(map) {
var div = L.DomUtil.create('div', 'info legend'),
grades = [0, vcr_array[per16], vcr_array[per33], vcr_array[per50],
vcr_array[per66], vcr_array[per83]
],
labels = [];
for (var i = 0; i < grades.length; i++) {
div.innerHTML +=
'<i style="background:' + getColor(grades[i]) + '"></i> ' +
grades[i] + (grades[i + 1] ? '–' + grades[i + 1] + '<br>' : '+');
}
return div;
};
legend.addTo(myMap);
})
// window function
window.getData = function() {
// Get the select element
var e = document.getElementById("selCamp");
// Get the value of the selected index
var v = e.value;
console.log(v)
// Verify the value and set the map to the new center
if (v == "campaign1") { dmaData = "static/data/dma_info.json"; } else if (v == "campaign2") { dmaData = "static/data/dma_info2.json"; }
// console.log(dmaData)
d3.json(dmaData, data_legend => {...
all the code above again
})
// Clear layer
geojson.clearLayers();
}
})
But the legend appears to repeat itself everytime I change from campaign to campaign... I also don't know if there is a more efficient way to update my map having 2 or more jsons where the data can come from... Thank you in advance!!!

TinyMce 5 setcontent unable to set html properly

I am writing a tinymce custom plugin called Mergetable. which will merger two user selected table.
Problem statement:
TinyMce is not allowing to select two table , by using shift and mouse I can select content of the table. So I can't use tinmce.activeeditor.selection.getNode() method instead using tinmce.activeeditor.selection.getContent().
Form getcontent() method I am getting proper html of both table. After do some operation while setting content using tinmce.activeeditor.selection.setContent() both table merged properly but two more table with empty td created one in top and one in bottom . Please see below plugin code.
code:
(function () {
var mergeTable = (function () {
'use strict';
tinymce.PluginManager.add("mergeTable", function (editor, url) {
function Merge(){
var selectedhtml=editor.selection.getContent();
//using getContent() as getnode returning body node
var dv=document.createElement('div');
dv.innerHTML= selectedhtml;
var tableElements = dv.getElementsByTagName('TABLE');
if (tableElements.length == 2) {
var tableOne = tableElements[0];
var tableTwo = tableElements[1];
var tempTable = null;
var offsetLeft = tableOne.offsetLeft;
var offsetTop = tableOne.offsetTop;
var elem = tableElements[0];
if (tableOne.nodeName == "TABLE" && tableTwo.nodeName == "TABLE") {
for (var r = 0; r < tableTwo.rows.length; r++) {
var newTR = tableOne.insertRow(tableOne.rows.length);
for (var i = 0; i < tableTwo.rows[r].cells.length; i++) {
var newTD = newTR.insertCell()
newTD.innerHTML = tableTwo.rows[r].cells[i].innerHTML;
newTD.colSpan = tableTwo.rows[r].cells[i].colSpan;
newTD.rowSpan = tableTwo.rows[r].cells[i].rowSpan;
newTD.style.cssText = tableTwo.rows[r].cells[i].style.cssText;
if (tableOne.style.border != "") {
newTD.style.border = "1px dotted #BFBFBF"
}
}
}
tableTwo.remove();
console.log(dv.innerHTML);
editor.selection.setContent(dv.innerHTML);
editor.nodeChanged();
}
else {
alert("Please select two tables");
}
}
}
editor.ui.registry.addButton('mergeTable', {
text: "Merge Table",
onAction: function(){ Merge();}
});
});
}());
}());
I am able to fix my problem by using some work around . Instead use setContent() method. I have remove selected content and use insertContent().
Please find working code below.
(function () {
var mergeTable = (function () {
'use strict';
tinymce.PluginManager.add("mergeTable", function (editor, url) {
var cmd = function (command) {
return function () {
return editor.execCommand(command);
};
};
function Merge(){
var selectedhtml=editor.selection.getContent();
var dv=document.createElement('div');
dv.innerHTML= selectedhtml;
var tableElements = dv.getElementsByTagName('TABLE');
if (tableElements.length == 2) {
var tableOne = tableElements[0];
var tableTwo = tableElements[1];
var tempTable = null;
var tableOneMaxCell=0
var tabletwoMaxCell=0
var tempCellcount=0
var tableOneRowcount=tableOne.rows.length;
tableOne.querySelectorAll("tr").forEach(function(e){
tempCellcount= e.querySelectorAll("td").length ;
if(tempCellcount>tableOneMaxCell)
{
tableOneMaxCell=tempCellcount;
}
});
tableTwo.querySelectorAll("tr").forEach(function(e){
tempCellcount= e.querySelectorAll("td").length ;
if(tempCellcount>tabletwoMaxCell)
{
tabletwoMaxCell=tempCellcount;
}
});
if (tableOne.nodeName == "TABLE" && tableTwo.nodeName == "TABLE") {
for (var r = 0; r < tableTwo.rows.length; r++) {
var newTR = tableOne.insertRow(tableOne.rows.length);
for (var i = 0; i < tableTwo.rows[r].cells.length; i++) {
var newTD = newTR.insertCell()
newTD.innerHTML = tableTwo.rows[r].cells[i].innerHTML;
newTD.colSpan = tableTwo.rows[r].cells[i].colSpan;
newTD.rowSpan = tableTwo.rows[r].cells[i].rowSpan;
newTD.style.cssText = tableTwo.rows[r].cells[i].style.cssText;
if (tableOne.style.border != "") {
newTD.style.border = "1px dotted #BFBFBF"
}
if(i==tableTwo.rows[r].cells.length-1 && tableOneMaxCell>tabletwoMaxCell){
newTD.colSpan = tableTwo.rows[r].cells[i].colSpan + (tableOneMaxCell-tabletwoMaxCell);
}
}
}
for( var t1=0; t1<tableOneRowcount; t1++ ){
var celllen=tableOne.rows[t1].cells.length;
tableOne.rows[t1].cells[celllen-1].colSpan=tableOne.rows[t1].cells[celllen-1].colSpan+(tabletwoMaxCell-tableOneMaxCell)
}
tableTwo.remove();
// cmd('mceTableDelete');
// var selObj = editor.selection;
// var selstartRange = selObj.getStart();
// var selectendRange= selObj.getEnd();
// var selrng=selObj.getRng();
// console.log(selstartRange);
// console.log(selectendRange);
// editor.execCommand('mceTableDelete');
// selObj.removeAllRanges();
editor.selection.getSelectedBlocks().forEach(function(elm){
elm.remove();
});
// selObj.setRng(selrng,true);
editor.insertContent(dv.innerHTML);
editor.nodeChanged();
}
else {
editor.notificationManager.open({
text: 'Please select two table.',
type: 'error'
});
}
}
else {
editor.notificationManager.open({
text: 'Please select two table.',
type: 'error'
});
}
}
editor.ui.registry.addButton('mergeTable', {
text: "MergeTable",
onAction: function(){ Merge();}
});
});
}());
}());

String is empty after first iteration in loop

I'm replacing the contents in a string using a setTimeout-function. The code looks as follows:
(function ($) {
"use strict";
/*
GENERAL DESCRIPTION:
*/
$(document).ready(function () {
var page_title = $(".page-content")[0].title;
var replacement_string = "åpöälokjixrytgöh";
//$(window).scroll(function () {
window.setInterval(function () {
var fixed = $(".changing-title");
var fixed_position = $(".changing-title").offset().top;
var fixed_height = $(".changing-title").height();
var title_array = [];
var offset_array = [];
var height_array = [];
var $pageGridPictures = $(".page-grid-picture");
$pageGridPictures.each(function (index, element) {
var $this = $(element);
title_array.push(element.title);
offset_array.push($this.offset().top);
height_array.push($this.height());
});
for (var i = 0; i < offset_array.length; i++) {
if (fixed_position + fixed_height > offset_array[i] && fixed_position + fixed_height < offset_array[i + 1]) {
if (title_array[i] !== fixed.text()) {
var j;
var text_one = title_array[i];
var text_two = "";
fixed.text(title_array[i]);
for (j in title_array[i]) {
(function (j) {
setTimeout(function () {
text_two = text_one.substring(0, j) + replacement_string[j] + text_one.substring(j + 2, text_one.length);
fixed.text(text_two);
if (j == text_one.length - 1) {
fixed.text(text_one);
}
}, 80 * j);
}(j))
};
}
}
}
}, 1200);
});
})(jQuery);
The problem is that the last substring added to text_two in the setTimeout-function is empty after the first iteration. It works the first time. It then contains the correct substring and has the correct length. After that it's just empty. Why is that? I'm going crazy over here! ^^
Thanks in advance.

How to get variable data by id

Recently i have used code in project that is still working it it http://kreditka.testovi-site.pw. But when i tried to reuse javascript the default rules js got broken and i got an error in console explaining that varibale cannot be found. Is it somehow related that sme o the code is not resusable and each line should be rewritten one by one for defferent projects?
(function () {
console.log("()");
"use strict";
var polosa = document.querySelector("#polosa");
alert(polosa);
var x = document.querySelectorAll("#slide1");
var o;
for (o = 0; o < x.length; o++) {
x[o].style.left = o*300+"px";
}
var x = document.querySelectorAll("#slide");
var a;
for (a = 0; a < x.length; a++) {
x[a].style.left = a*300+"px";
}
var doc = document.querySelectorAll('.btn-click');
for (var i = 0; i < doc.length; i++) {
doc[i].addEventListener("click", highlightThis, true);
}
var doc1 = document.querySelectorAll('.btn1-click');
for (var j = 0; j < doc.length; j++) {
doc1[j].addEventListener("click", highlightThis1, true);
}
var polosa = document.querySelector('#polosa');
polosa.style.left = '0px';
var left = 0;
var sliderItem = document.querySelector('#slide');
function highlightThis(event) {
console.log("highlightThis");
var currentActiveButton = document.querySelector(".btn-click.btn-slide-active");
currentActiveButton.classList.toggle("btn-slide-active");
event.target.classList.toggle("btn-slide-active");
console.log(event.target.dataset.value);
shiftSlide({
prev: currentActiveButton.dataset.value,
next: event.target.dataset.value
});
}
function highlightThis1(event) {
console.log("highlightThis1");
var currentActiveButton1 = document.querySelector(".btn1-click.btn-slide-active");
currentActiveButton1.classList.toggle("btn-slide-active");
event.target.classList.toggle("btn-slide-active");
console.log(event.target.dataset.value);
shiftSlide1({
prev: currentActiveButton1.dataset.value,
next: event.target.dataset.value
});
}
function shiftSlide(obj) {
var polosa = document.querySelector('#polosa');
console.log("shiftSlide");
var currentSliderPosition = parseInt(polosa.style.left);
if (obj.prev === obj.next) {
return
} else {
var left = (obj.prev - obj.next) * 300;
polosa.style.left = currentSliderPosition + left + "px";
}
}
function shiftSlide1(obj) {
var polosa = document.querySelector('#polosa1');
console.log("shiftSlide");
var currentSliderPosition = parseInt(polosa1.style.left);
if (obj.prev === obj.next) {
return
} else {
var left = (obj.prev - obj.next) * 300;
polosa1.style.left = currentSliderPosition + left + "px";
}
}
})();

JavaScript Observable Property

In trying to learn more about JavaScript patterns I created the following 2 "Meters" based on an example I found. Is Meter1 better because it uses the Observable Property (or so I think) pattern? Would this pattern be used real-world or not really because of all the frameworks available?
//Meter1 - Observable Property Pattern
var Meter1 = function (count) {
var countChanging = [],
countChanged = [];
this.count = function (val) {
if (val !== undefined && val !== count) {
for (var i = 0; i < countChanging.length; i++) {
if (!countChanging[i](this, val)) {
return count;
}
}
count = val;
for (var i = 0; i < countChanged.length; i++) {
countChanged[i](this);
}
}
return count;
};
this.increment = function () {
return count = count + 1;
}
this.onCountChanging = function (callback) {
countChanging.push(callback);
};
this.onCountChanged = function (callback) {
countChanged.push(callback);
};
};
var meter = new Meter1(5);
var btnClick = document.getElementById('btnClick');
btnClick.addEventListener('click', function () {
meter.count(meter.count() + 1);
}, false);
meter.onCountChanging(function (b, count) {
if (count > 10) {
document.getElementById('numClicks').innerHTML = "Enough already!!!!!";
return false;
}
return true;
});
meter.onCountChanged(function () {
document.getElementById('numClicks').innerHTML = "Test " + meter.count();
});
//Meter2 - Does the same thing, is Observable Property pattern better?
var Meter2 = function (count) {
this.count = 0;
};
var meter2 = new Meter2(5);
var btnClick2 = document.getElementById('btnClick2');
btnClick2.addEventListener('click', function () {
meter2.count = meter2.count + 1;
if (meter2.count > 10) {
document.getElementById('numClicks2').innerHTML = "Enough already!!!!!";
} else {
document.getElementById('numClicks2').innerHTML = "Test " + meter2.count;
}
}, false);
<body>
<div id="numClicks">Test</div>
<div id="numClicks2">Test</div>
<button id="btnClick">Click - Meter</button>
<button id="btnClick2">Click - Meter 2</button>
</body>
</html>
<script src="../js/generalTesting.js"></script>

Categories