Running javascript on page back - javascript

I have the following problem:
I've created a form with several input fields like these:
<td>Pizza Margherita</td>
<td><input type="number" id="countMargherita" class="formnumbers" name="PizzaMargherita" onChange="validateForm(this);changeTotalFromCount(this);" data-unitprice="7"/></td>
<td><span id="totalMargherita"></span></td>
11 to be exact.
the onChange="changeTotalFromCount(this)" looks as follows:
function changeTotalFromCount(input) {
var unitPrice = parseFloat(input.getAttribute("data-unitPrice"));
var count = input.value;
var price = unitPrice * count;
var formattedPrice = '\u20ac ' + price.toFixed(2);
var label = input.parentNode.nextElementSibling;
label.innerHTML = '';
label.appendChild(document.createTextNode(formattedPrice));
}
Now what this does is say the user wants 5 pizza margherita's he enters a 5 in the input field and then immdediately shows the cost which in this case is 7*5= 35. This works just fine, but when the user submits the form he gets taken to another .php file where he sees the confirmation with all the details. There is also a button that needs to take them back to the order page again. I did this first by just sending it straight to my orderform.php but as this doesn't save the customer his input i decided to use this instead:
<input type='button' value='Bestelling Wijzigen' onClick="history.go(-1);return false;" class='printbutton'>
I don't know if this is the right thing to do or not, but i saves the user's his information as he goes back. Except it doesn't show the prices next to the input anymore unless he/she changes the input again. And there lies my problem, i'd like it so that if the user goes back to change his order he can still see the costs of each product without changing it before he can see it again.
Im not really an expert in JS or PHP.
(if you miss any information please let me know!)

You can use the onload event to run code that initializes all totals. It's fired when you go to a page with the backbutton as well as when you visit it in any other way.
So, for example
function initTotals()
{
var inputs = document.getElementsByTagName('input');
for(var i=0; i < inputs.length; i++)
{
changeTotalFromCount(inputs[i]);
}
}
window.onload = initTotals;
http://jsfiddle.net/XK99Z/

Related

Trying to prevent all form data from returning to default on button click

I am having an issue and well javascript is not my strong point. I am making a form that would be used to keep player stats in a game and was trying to automate some of the math that would be done on click for every time the player's turn comes around.
I managed to do the first code to work with on-blur in text boxes for the max health to increase or decrease as clothing items are used and taken off, this code worked fine so I tried changing it for the power given on the player's turn on click of a button. It's basically the same code set to different fields that had worked before but instead of on-blur of a text box, I just set a button to run the code on the click.
<button onclick="pta()">Click on your turn</button>
I see it work for a split second before all textboxes reset to empty or default. The javascript I am using is
<script>
function pta()
{
var pass1 = parseInt(document.getElementById("pass1").value);
var pass2 = parseInt(document.getElementById("pass2").value);
var pass3 = parseInt(document.getElementById("pass3").value);
var pass4 = parseInt(document.getElementById("pass4").value);
var car1 = parseInt(document.getElementById("car1").value);
var car2 = parseInt(document.getElementById("car2").value);
var car3 = parseInt(document.getElementById("car3").value);
var car4 = parseInt(document.getElementById("car4").value);
document.getElementById("aura").value = car1 + car2 + car3 + car4 - pass1 pass2 - pass3 - pass4;
}
</script>
I saw the code work for a very split second by making the correct number appear in the aura text box, at least for addition, have not tried the subtraction for the pass ones yet but I believe the code is working. I am just having a hard time finding any way to prevent the on-click of this function from clearing and resetting everything else.
All the information this code pulls is from a textbox or numberbox, there is preset value of at least "0". I have attached a picture of what I am working on. The code for "health: and "head-other" will add and display the results in "Player Max Health" with on-blur with no issues. (I have a seperate script on each box to prevent anything but numbers from being entered to prevent issues).
All I am trying to do is is to take the 4 lines that says "Caroh's", add them up, then take the 4 lines that says "Passive Aura" and subtract those then add that to what ever number is in the aura box. I also just realized I need to add the Aura text box to the script to be added but will get to that later.
Any help is greatly appreciated, Javascript is not my strong point. Thanks
OK, I have changed the code to this way and am still not sure. It is as if everything is being submitted and all fields reset
<script>
function pta()
{
var pass1 = parseInt(document.getElementById("pass1").value);
var pass2 = parseInt(document.getElementById("pass2").value);
var pass3 = parseInt(document.getElementById("pass3").value);
var pass4 = parseInt(document.getElementById("pass4").value);
var car1 = parseInt(document.getElementById("car1").value);
var car2 = parseInt(document.getElementById("car2").value);
var car3 = parseInt(document.getElementById("car3").value);
var car4 = parseInt(document.getElementById("car4").value);
var aura = parseInt(document.getElementById("aura").value);
var ansD = document.getElementById("aura");
ansD.value = car1 + car2 + car3 + car4 - pass1 - pass2 - pass3 - pass4 + aura;
}
I think the issue here is that you're using a surrounding <form> tag which you could omit if you're only performing javascript calculations client-side and not posting data back to a server.
With a form tag in place the default behaviour for any <button> inside the form is submit so even though you have an onclick that default behaviour will still fire and submit the form which is what clears all the fields.
If you want to keep the <form> in place and don't want this particular button to submit the form the easiest way to fix this it to add type="button" e.g.
<button type="button" onclick="pta()">Click on your turn</button>

Authentication script

Currently I am working on a script that does an authentication job one time for products with factory code to avoid the fake products.
My end goal is:
- Test a user input value if it matches a list of original codes.
- if the input is checked for the first time and matches one of the original codes-list redirects to a specific web page.
- if the user input is checked for the second time and matches before one of the original codes-checked-list display a paragraph.
- if the input is checked and NOT matches show FAKE.
Here what I write so far:
$(document).ready(function(){
var originalCodes = ['123','1234','12345'];
var userInputCode = document.getElementById('userInputCode');
$('form').submit(function(){
var checkedCodes = [];
var i;
for(i=0; i<originalCodes.length; i++){
if (userInputCode.value === originalCodes[i]){
window.location.href = "SomeLinkHere";
checkedCodes.push(i);
if (userInputCode.value === checkedCodes[i]){
$('checked').css('display', 'block');
}
}else{
$('.fake').css('display', 'block');
}
return false;
}
});
});
.fake {display:none;}
.checked{display:none;}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form method="post">
<p>Product Code: <input type="text" id="userInputCode"></p>
<input type="submit" value="Check" id="submit">
</form>
<h2 class="fake">Your've a Fake product.</h2>
<h2 class="checked">This code was previously authenticated.</h2>
I faced trouble in the loop of originalCodes array the if statement can't check all the values.
Does anyone have an idea?
Thanks in advance.
Four mistakes:
$('.form') means elements with class form, not the form tag. Use $('form') instead.
Once you navigate away with window.location.href = "SomeLinkHere";, the JavaScript state is cleared. You'll need to save the checked codes somewhere more persistent if you want to do that.
You're adding the code to list of checked codes, then seeing if it's there, which it always will be. You need to reverse these.
If the same code is checked multiple times, checkedCodes could eventually get bigger than originalCodes, and then your loop will miss some of them.

Place cursor back automatically into erroneous form field when js validation fails

Let's say there is a form field named txtphone and then with javascript I check it is at least 10 digits in length. User enters only 5 digits so validation fails. I want the cursor to go back to where the txtphone is input automatically so the user can not get any further without entering a 10 digit phone number. This is an example. I can not get it to go back to input field on fields like name, email, etc. On this example, on failure, this is how I am trying to accomplish this:
txtphone.focus()
txtphone.select()
return False
It shows the alert error message but the focus is placed on the next form field.
Please, respond only if you had this problem in the past and you solved it, and please, give me a few lines of actual working code. I have been fighting this for weeks and ready to give up. Answers like "have you tried..." do me no good. Thank you.
I created a JSFiddle showing how the focus method should work for what you're looking for. Let me know if it helps.
JSFiddle
HTML
<input id="txtphone" type="text">
<button id="btn">
Click me!
</button>
JavaScript
var txtphone = document.getElementById("txtphone");
var button = document.getElementById("btn");
button.addEventListener("click", function () {
if (txtphone.value.length < 10) {
txtphone.style.backgroundColor = "red";
txtphone.focus();
} else {
txtphone.style.backgroundColor = "white";
}
});

How do I autofill a widget with form inputs using Javascript?

I'm working on a donation form that has a widget embedded in it. The widget opts users into our Mobile Giving giving program which uses separate software than our donation forms. I've been asked to see if we can make the widget invisible but transfer the form data to it and submit it when the user submits the donation form. I've already run into a problem with getting the form data to transfer to the widget though.
The form should get the donors first name, last name and phone number from the form and then autofill the widget when a checkbox is clicked stating that the user would like to receive mobile updates.
Below is what I've tried but it doesn't seem to be working. The code for the form is relatively long so I just included the relevant fields but here is link to the full form: http://support.ddfl.org/site/Donation2?df_id=9442&mfc_pref=T&9442.donation=form1
I'm very new to Javascript so I'm not entirely sure if this is possible. Just an fyi, I also included console statements so I could see if the values were working.
<input type="text" name="billing_first_namename" id="billing_first_namename"
<input type="text" name="billing_last_namename" id="billing_last_namename"
<input type="text" name="donor_phonename" id="donor_phonename"
<input type="checkbox" name="mcoptin" onclick="FillMobileCause(this.form)" value="this.form"> Opt in to receive mobile updates.
Mobile messaging powered by Mobilecause<script>!function(d,s){var s=d.createElement("script"),h=(document.head||d.getElementsByTagName('head')[0]);s.src="https://app.mobilecause.com/public/messaging_widgets/q71xd/source";h.appendChild(s);}(document);</script>
<script>
function FillMobileCause(f){
if(f.mcoptin.checked == true){
console.log(f.billing_first_namename.value);
console.log(f.billing_last_namename.value);
console.log(f.donor_phonename.value);
if(f.billing_first_namename.value.length>=1){
f.firstname.value = f.billing_first_namename.value;
}else {
f.firstname.value = '';
}
if(f.billing_last_namename.length>=1){
f.lastname.value = f.billing_last_namename.value;
}else{
f.lastname.value = '';
}
if(f.donor_phonename.length>=1){
f.mobilenumber.value = f.donor_phonename.value;
}else{
f.mobilenumber.value = '';
}
console.log(f.firstname.value);
}
}
</script>
Please let me know if I'm leaving off important details. This is also my first StackOverflow post. ;)
I appreciate your help!
Your main issue is that you were referring to inputs in the mobilecause form as if they were in the same form, but they are in another (nested in your f main form).
function FillMobileCause(f){
var mcF = f.getElementsByClassName('mc-triggersubscription')[0];
if(f.mcoptin.checked == true){
mcF.firstname.value = f.billing_first_namename.value;
mcF.lastname.value = f.billing_last_namename.value;
mcF.mobilenumber.value = f.donor_phonename.value;
}
}
f is still the main form (the one that is the parent of the checkbox).
But now we have another one, mcF (mobilecauseForm), which is selected using the getElementsByClassName (this will search for a child with the mc-triggersubscription class). The [0] part is so the first match is selected (getElementsByClassName returns an array.
After that, all we need to do is assign the f inputs' values to the mcF ones.
Note: I left behind the "if empty" validation for simplifying. Anyway I don't think it's really needed, if a value is empty, there is no major issue in just copying it to the mobilecause value.

Submitting hidden field data on Android/iOS browsers does not work

I am working on a site which connects to a MySQL database and lets you display/edit the data in it. The site uses JavaScript and PHP, with HTML and CSS parts (these are added using JS).
The site works, does everything I wanted it to do, but only from PC. When I try to use it from a smartphone, some of the hidden fields' value doesn't get submitted correctly to the PHP page responsible to working with them.
First, I have a few of this select box:
var maxLvl;
var select = document.createElement( 'select' );
var trooplist = [archerLvl, giantLvl, wizardLvl, balloonLvl, dragonLvl]; //this array contains numbers, which will be used to set the starting option in the select
select.id = "select" + k + " " + i; //k and i are both variables in their respective for loop: k goes from 0 to 2, in it there's another with i.
select.onblur = function() {
var selectid = this.id;
var last = selectid.slice(-1);
if(last==0){
document.getElementById("hiddenArcherid").value = this.value;
alert(document.getElementById("hiddenArcherid").name + " " + document.getElementById("hiddenArcherid").value);
}else if(last==1){
document.getElementById("hiddenGiant").value = this.value;
alert(document.getElementById("hiddenGiant").name + " " + document.getElementById("hiddenGiant").value);
}else if(last==2){
document.getElementById("hiddenWizard").value = this.value;
alert(document.getElementById("hiddenWizard").name + " " + document.getElementById("hiddenWizard").value);
}else if(last==3){
document.getElementById("hiddenBalloon").value = this.value;
alert(document.getElementById("hiddenBalloon").name + " " + document.getElementById("hiddenBalloon").value);
}else if(last==4){
document.getElementById("hiddenDragon").value = this.value;
alert(document.getElementById("hiddenDragon").name + " " + document.getElementById("hiddenDragon").value);
}
};
select.style.position = "absolute";
select.style.left = 250 + (i*(width + (width/10))) +"px";
select.style.top = 110 + height + (rowcounter * (height * 1.5)) + "px";
select.style.width = width;
if(i==0 || i==1 || i==2 || i==3)
maxLvl = 6;
else
maxLvl=4;
for(var l=0; l <= maxLvl; l++){
var option = document.createElement( 'option' );
option.setAttribute("value", l);
option.innerHTML = "Level " + l;
select.appendChild(option);
}
select.selectedIndex = trooplist[i];
IDarray.push(select.id);
document.body.appendChild(select);
This code runs in a for loop, and creates 5 select boxes using data passed by a function. Then, when the user selects a new option, the option's value is stored in a HTML hidden input field with. Like this one:
var hiddenArcher = document.createElement('input');
hiddenArcher.setAttribute("type","hidden");
hiddenArcher.name = "hiddenArcher";
hiddenArcher.id = "hiddenArcherid";
hiddenArcher.setAttribute("value", document.getElementById("select1 0").value);
formNew.appendChild(hiddenArcher);
These input fields have a basic value, which is the default of the select box - 0 if the user creates a new entry, or an already known value if the user wants to modify an already existing entry. All the input fields have the same structure, only the JS var, the name, the id and the default value changes.
The input fields are part of the formNew form, which has multiple submit buttons - pressing those buttons posts the fields' values to a PHP page, which executes the MySQL queries, depending on which button was pressed. For this, I use if/else if (isset). Then the PHP redirects (by using header("Location: http://my_sites_address"); exit();) to the main page - the one I where the select boxes are.
If I try it from Chrome, the site works - The right values get passed, the PHP executes the right queries correctly. I can add new entry, and both delete or modify existing ones. When I try it on Android (via emulator) or iOS (via my friend's phone), although I can select the values I want to change, and the alerts display the correct data, too, when I hit submit, nothing happens within the database, it seems like I did nothing. The browser gets redirected to the PHP, so I guess the submit does happen, but there will be no changes in the database. The PHP simply redirects to the main page, and that's all.
The only function can be used successfully on phone is deleting the entry, most likely because the hidden field responsible for storing the row's ID gets it's value the moment it's added to (a different) form, and the value never changes, only when the user switches to a different entry.
The hidden fields "physically" (based on their location in the file) are declared later than the select boxes.
Currently, the code acts this way on phone:
1) I start editing the entry. The select boxes show up.
2) I can select the desired value.
3) An alert pops up, confirming the value got passed to the hidden field.
4) I press the submit button, comes the PHP, then the redirects, and I am back where I started. There are no changes in the database.
I already tried to switch onchange to onblur at the select boxes; I made sure JS is enabled (which was totally unnecessary, because the images/texts displayed with JS). Right now I have no idea what's wrong.
Are any of you experienced something similar, or has any idea what should I do?
Some browsers fail to correctly and completely recognize the programmatic change of a hidden input's value immediately after it is changed. If you submit the form directly after changing the hidden input's value via javascript, the value sent for that input will be the pre-change value, rather than the value you set in javascript.
Unfortunately, I don't have a list of browsers that exhibit this behavior, nor do I know the exact mechanics behind it. What I do know is that I've run into the issue you're describing, and I have always been able to solve it by triggering a change event on the hidden input after changing its value via javascript.
For those using plain javascript with no external libraries, your code would look something like this (see here):
<input id="myHidden" name="myHidden" type="hidden" value="old value"/>
<script type="text/javascript">
var hiddenInput = document.getElementById('myHidden');
hiddenInput.value = 'new value';
console.log(hiddenInput.value); // = 'new value'
// Submit the form now, and myHidden='old value' will be sent to the server
// Set up and trigger the change event on our input:
var changeEvent = document.createEvent("UIEvents");
changeEvent.initUIEvent("change", true, true);
hiddenInput.dispatchEvent(changeEvent);
// Submit the form now, and myHidden='new value' will be sent to the server
</script>
For those using jQuery or a similar library, the code is a little more concise:
<input id="myHidden" name="myHidden" value="old value"/>
<script type="text/javascript">
var $hiddenInput = $('#myHidden');
$hiddenInput.val('new value');
console.log($hiddenInput.val()); // = 'new value'
// Submit the form now, and myHidden='old value' will be sent to the server
// Trigger the change event on our input:
$hiddenInput.change();
// Submit the form now, and myHidden='new value' will be sent to the server
</script>
Really concise example (one-liner) using jQuery:
<input id="myHidden" name="myHidden" value="old value"/>
<script type="text/javascript">
$('#myHidden').val('new value').change();
// Submit the form now, and myHidden='new value' will be sent to the server
</script>
Here's a working example using a slightly simplified version of the code supplied in the original question.
In our case, the issue was simply that we had this check in PHP:
if (isset($POST['myvalue']) && !empty($POST['myvalue'])) {
// save
}
However, in PHP 0 is considered empty in PHP and thats exactly what the passed value was!

Categories

Resources