JavaScript only works in debug mode with a break - javascript

I have JavaScript code that is supposed to add input boxes to my html and then save the user input into and array. When I run my code regularly the screen refreshes and nothing happens. If I run it a second time it works how it should. Similarly if I open up debug mode and put a break point in the code works just fine the first time I try to run it. Is there an asynchronous issue I'm not aware of?
Also the event listener is checking for when someone hits the enter key on the web page otherwise the code doesn't execute.
Also, I'm new to stack overflow I've found the help so far great and if I'm not doing something in proper etiquette of asking a question please let me know!
var recipients = document.getElementById("howMany");
recipients.addEventListener("keydown", function (e) {
if (e.keyCode === 13) {
validate(e);
}
})
function validate(e) {
var num2 = document.getElementById("howMany");
num2 = document.getElementById("howMany").value;
var values = new Array();
for (i = 1; i < num2; i++){
//loop set to repeat to the amount of guests inputed by user
container.appendChild(document.createTextNode("Recipient " + (i+1)+":"));
//creates a text for the user to read which recipient each input is for
var x = document.createElement("input");
//creates the input element
x.setAttribute("id", "empInput"+i);
x.setAttribute("type", "text");
x.setAttribute("value", "");
//sets the type and attribute
container.appendChild(x);
//places the input element in the container
values[i] = document.getElementById("empInput"+i).value;
}
//console.log(values);
}

Related

Multiplication of two input table element values on html form row not working (Google Webapp)

I am trying to create an order form as a table, where a user enters a quantity required for a product in a row and the corresponding value is calculated by multiplying the user entry by the price held in another element of the same row of the table.
The form is loaded as a WebApp via Google and uses an Apps Script to retrieve the table values from a Google Sheet. The form loads OK with the data as expected but I just can't get the calculation part to work.
If I click the "place Order" button at the bottom of the form, the numberUsed values are included as parameters in the URL so it looks as though the values are updating in those elements but I haven't been able to access them to do the calculation and display it in the element called "value".
I am a novice programmer so I am sure it is something basic I am doing wrong (or not doing). I have created a JSBin https://jsbin.com/siwerat/edit?html,js,console,output and I have tried several variations of code derived from other answers and videos over the last couple of weeks without success so any help will be much appreciated.
//var numRows;
document.addEventListener('DOMContentLoaded', function() {
//new
var elems = document.querySelectorAll('cart');
var instances = M.FormSelect.init(elems);
// end new
document.getElementByname("cart").addEventListener("submit", getValues); //used to submit form - needs validation
//document.getElementByName("numberUsed").addEventListener("oninput",getValues);//used to submit form - needs validation
});
function test(event) {
"use strict";
event.preventDefault();
console.log("getValues function triggered");
}
function getValues() {
event.preventDefault();
var rows = document.querySelectorAll("package-row");
rows.forEach(function(currentRow) {
var numberUsed = Number(currentRow.querySelector('#numberUsed').value);
var price = Number(currentRow.querySelector('#price').value);
//var inPackage = Number(currentRow.querySelector('#inPackage').value);
var inPackage = 1;
var revenue = 1;
document.querySelectorAll('numberUsed');
if (numberUsed == "") {
if (isNaN(inPackage) || isNaN(price)) {
return;
}
revenue = price * inPackage;
} else {
if (isNaN(numberUsed) || isNaN(price)) {
return;
}
revenue = price * numberUsed;
}
var value = revenue * 5;
//currentRow.querySelector("#revenue").innerHTML = revenue;
currentRow.querySelector("#value").innerHTML = value;
});
}
Thanks Rafa for the guidance. After further reading/analysis I have got it working. The Event bubbling video by Learn Google Spreadsheets: [https://www.youtube.com/watch?v=fYpGe5ngujk][1] and an article on EncodeDNA.com (Dynamically create HTML table and Button using Javascript) helped narrow down the issues I had to get a solution.

Enable only backspace on onkeyevent?

I simply need javascript to automatically add a celsius degree sign after the user starts typing into a text box.
I already have this code which is working as intended. It is adding the degree sign after the text:
$(document).ready(function(){
var temp1 = new Value();
$("#Temperature1").on('keyup',function(e){
var oldstr=$("#Temperature1").val();
var tokens = oldstr.split('℃');
var suffix = tokens.pop() + '℃';
var prefix = tokens.join('');
$("#Temperature1").val(prefix+suffix);
});
});
<input type="textbox" id="Temperature1">
The issue: Once the user starts typing in this field, the "℃" appears correctly, after the text. However, once the user has typed something, it can't be removed. User might change their mind and not want to enter something in the Temperature field. How do I only enable backspace?
Thank you for your time.
try this
$(document).ready(function () {
var temp1 = new Value();
$("#Temperature1").on('keyup', function (e) {
if(e.which == 8) return; // added this line
var oldstr = $("#Temperature1").val();
var tokens = oldstr.split('℃');
var suffix = tokens.pop() + '℃';
var prefix = tokens.join('');
$("#Temperature1").val(prefix + suffix);
});
});
I've added a line which checks if the pressed key was backspace. If YES, it returns from the function (i.e. not executing the rest of the codes of the function).

Injected JS not posting to the database at all

I've been working around with this script for the past few days, as I want to save all the pots won at this website csblitz.com.
I can't seem to find the error.
I get no console errors, I targeted different things, the div where the last winner is shown and the message that pops up after the winner is chosen
//csblitz
function commaSeparateNumber(val){
while (/(\d+)(\d{3})/.test(val.toString())){
val = val.toString().replace(/(\d+)(\d{3})/, '$1'+'.'+'$2');
}
return val;
}
var counter = 0;
$(document).bind('DOMNodeInserted', function(event) {
var elem = $(event.target).find("div.round-last-winner.ng-binding.ng-scope");
var text = elem.text().trim();
if(text.length > 0){
var firstIndex = text.lastIndexOf("$")+1;
text = text.substring(firstIndex, text.length);
$.post("https://mywebsite.net/api/stats?sourceid=0&value="+text);
}
});
Can't seem to find the issue, since I have other crawlers posting correctly to the database.

transfer data from textbox to textarea with javascript

I have a small problem with my javascript code, im trying make a small application with 2 textboxes and 1 textarea. When textbox 1 is filled in you can press enter and then the focus will go to textbox 2. When textbox 2 is filled then the data from textbox 2 will go automaticly to the textarea as somekind of storage. And i fould like it to work with only plain javascript so it could support all the browsers and older browsers like IE 8
I have a massive javascript and every function works but somehow the big picture doesnt work. Can someone help me figure out why my javascript isnt doing what i want. And what i want is explained above.
https://jsfiddle.net/LLfwhL3L/2/
I cleaned the fiddle up fith the jshint functions from jsfiddle and get no erros, but it still doesnt work
These are the functions where i think it goes wrong:
function AddToList() {
var bonregel = document.getElementById("bonregel");
var val = bonregel.value.toString();
if (val != "") {
var box = document.getElementById("bonregelbox");
if (box.value != "")
box.value += "\n";
box.value = box.value + val;
}
bonregel.value = "";
bonregel.focus();
}
var delayrec = [];
function delay(callback, id, calldelay) {
clearTimeout(delayrec[id]);
delayrec[id] = setTimeout(callback, calldelay);
}
function keyup(event) {
var locatiebox = document.getElementById("locatie");
var bonregelbox = document.getElementById("bonregelbox");
var bonregels = bonregelbox.value.split(/\r\n/).join(",");
var locatie = locatiebox.value;
if (event.keyCode == 125)
SubmitContent(locatie, bonregels);
else
delay(AddToList, "AddToList", 500);
}
The working fiddle
https://jsfiddle.net/LLfwhL3L/5/
This is the working fiddle and how it should work, but on my device with IE 8 it doesnt work. The text from textbox 2 isnt goeing into the textaera. How can i solve this?

How is it possible, that ajaxing is much more slower in Chrome and IE than Mozilla?

I would like to ask you to find the point, why the site -I'm working on- is slow.
the conditions of the problem:
large row count (so I think maybe the problem is related to this.)
there is ajaxing event (I have tired to comment it out and the problem disappeared)
using not Mozilla (this freeze effect appear in IE and Chrome)
description of the problem (see the image):
I change the value of input
after there is an ajax call (in order to calculate prize) and it takes in FF about 30 ms otherwise more than 1 s
there is a freeze until the ajax finished (but ajax is not set to async:false)
only after that can I change the next input
I have tired to reproduce the error, but I could't. So see the original site:
site: foto/fotokidolgozas/elohivas-beallitasok.php
Log in and pass: d838292#rtrtr.com
Update: It works now fine, the trick is the following:
I use hidden input fields, their values are json_encode-d strings. I can process them anytime with js.
Thank you for any help!
Code:
$('#cikkek,#magic_bar').on("change","select,textarea,input[type!=hidden]",function(event_object){
if( $(this).attr('name') == "kijelolve" && !$(this).parents('#magic_bar').length)return true;
var cikk_id = $(this).parents('.cikk').attr('id');
var cikk_tipus = $("input[name=cikk_tipus]").val();
var tulajdonsag = $(this).attr('name');
var ertek = $(this).val();
if(ertek == "-1")return false;
if($(this).is('[type=checkbox]'))ertek = $(this).prop("checked")?'1':'0';
if(cikk_tipus=='fotokidolgozas' && (tulajdonsag=='meret'||tulajdonsag=='vagas'))
{
var sor = $(event_object.target).parents('.cikk');
var act_meret = sor.find('select[name=meret]').val();
var act_fill = sor.find('select[name=vagas]').val();
var act_zold_class = sor.find("input[name=zold_"+act_meret+"]").val()=="1" ?"zold":"feher" ;
var name = "src_"+act_meret+"_"+act_fill;
var name2 = "szoveges_uzenet_"+act_meret+"_"+act_fill;
sor.find(".img_cont").find("img").attr("src",sor.find("input[name="+name+"]").val());
sor.find(".szoveges_uzenet").text(sor.find("input[name="+name2+"]").val());
sor.find(".dpi_megfelel").text(sor.find("input[name=minoseg_"+act_meret+"]").val()+" ("+sor.find("input[name=dpi_"+act_meret+"]").val()+" dpi)");
sor.find("select[name=meret]").removeClass("feher zold").addClass(act_zold_class);
}
var before = now();
//this is the ajax part
if(ajax_modositaskor)
$.post('/_fn/cikk/mod.php',{
'cikk_tipus':cikk_tipus,
'cikk_id':cikk_id,
'tulajdonsag':tulajdonsag,
'ertek':ertek
},function(a){
var elapsed = now() - before;
if(a[0]!="1")
{
//error
alert(a[0]);
return;
}
if(a[1]!="-1")
{
//there is new price
$(event_object.target).parents('.cikk').find('.ar').text(a[1]);
}
if(a[2]!="-1")$('#cikkek_ara').text(a[2]);
osszegzest_frissit(a[3]);
var php_time = Math.round(a[4])
a_min = Math.min(a_min,elapsed);
p_min = Math.min(p_min,parseFloat(php_time));
a_max = Math.max(a_max,elapsed);
p_max = Math.max(p_max,parseFloat(php_time));
if(!a_avg)a_avg = elapsed;else a_avg= Math.round((a_avg+elapsed)/2);
if(!p_avg)p_avg = php_time;else p_avg = Math.round((p_avg+php_time)/2);
trace("ajax="+elapsed+"\tphp="+php_time+"\tajax_min="+a_min+"\tphp_min="+p_min+"\tajax_max="+a_max+" \tphp_max="+p_max+"\tajax_avg="+a_avg+" \tphp_avg="+p_avg);
},"json").error(function() { postHiba() });
});
The problem was that the hidden data was too large (see my other question), and it decreased the processing time. (Firefox seems to be well coded, because this does not mattered)
Now the problem is fixed.

Categories

Resources