Hi I am trying to install a merchant facility onto my website and it needs to submit a value $vpc_Amount which is the amount purchased in cents.
What I need to do is multiply the amount entered by the user ($amount) by 100 to get $vpc_Amount.
I tried the following but it isn't working.
<input type="text" ID="A1" name="amount"onkeypress="process1()">
<input type="hidden" id="A2" name="vpc_Amount">
And then the javascript
function process1() {
f1 = document.getElementById("A1").value;
total = f1*1000;
document.getElementById("A2").value = total;
}
What is happening is it is occasionally working but most of the time it doesn't. I know there is something wrong with the script so hence asking here.
Try to use onkeyup function -
<input type="text" id="A1" name="amount" value="" onkeyup="process1();" />
<input type="hidden" id="A2" name="vpc_Amount" />
javascript function -
function process1() {
var f1 = document.getElementById("A1").value;
var total = (f1 * 100);
document.getElementById("A2").value = total;
}
Use Jquery. http://jquery.com/
$(function() {
$('#form_id').submit(function(){
$('#form_id').find('#A2').val('New value');
return true;
});
});
Have you tried to use onkeyup event? It might be so that onkeypress event is triggered before the character is added to text field.
<input type="text" ID="A1" name="amount" onkeyup="process1()">
Also, I would suggest that you try to convert the value of the textfield to integer and add other input handling too. Users might enter any kind of data there and it can crash your javascript code.
This code should work:
document
.getElementById('A1')
.addEventListener('keyup', function (e) {
document.getElementById('A2').value = parseInt(this.value) * 1000;
})
keypress event triggers before value changes in text field and keyup after value has changed.
Basically event trigger in order:
keydown (onkeydown)
keypress (onkeypress)
keyup (onkeyup)
Force value to be integer or you will get NaN in some cases.
I will suggest to use onblur this is the best way if you want to use the build in attribute listener if you don't use jquery. Here is example:
<!DOCTYPE html>
<html>
<body>
Enter your name: <input type="text" id="fname" onblur="myFunction()">
<p>When you leave the input field, a function is triggered which transforms the input text to upper case.</p>
<script>
function myFunction() {
var x = document.getElementById("fname");
x.value = x.value.toUpperCase();
}
</script>
</body>
</html>
And url to the example in w3 school :) http://www.w3schools.com/jsref/event_onblur.asp
First of all, I think you should use onkeypup event and not onkeypress
<input type="text" id="A1" name="amount" onkeyup="process1()" value="" />
<input type="hidden" id="A2" name="vpc_Amount" value="" />
Javascript code -
function process1() {
var f1 = parseFloat(document.getElementById("A1").value);
var total = f1*100; //you said 100 so, I changed to 100
document.getElementById("A2").value = total;
}
jQuery code for the same -
jQuery(document).ready(function($){
$("#A1").keyup(function(){
var total = parseFloat($("#A1").val()) * 100;
$("#A2").val(total);
});
});
Your code can be simplified by making use of the fact that form controls are available as named properties of the form baed on their name. This removes the requirement to add IDs to form controls that must have a name anyway.
Pass a reference to the control in the listener:
<input type="text" name="amount" onkeyup="process1(this)">
<input type="hidden" name="vpc_Amount">
Then use the passed reference to get the form and other controls:
function process1(element) {
element.form.vpc_Amount.value = element.value * 100;
}
You may wish to use the change event instead to save updating the hidden field unnecessarily while the user is typing and also to catch changes that aren't based on key presses (e.g. pasting from the context menu).
You should also do some validation of the values entered so the user doesn't attempt to send the form with invalid values (noting that you must also do validation at the server as client side validation is helpful but utterly unreliable).
Related
I have an input
<input type="number" max="100">
However, if the user write manually for example 200, the input accept it. Is it something normal ?
I can validate the entry with javascript but if there is a build in in the html input it would be great :)
Thanks
There is actually no "native" HTML way outside a form post to avoid the faulty manual entry. You could do something like this (here jquery code):
$('input[type="number"]').on('change input keyup paste', function () {
if (this.max) this.value = Math.min(parseInt(this.max), parseInt(this.value) || 0);
});
This code applies to all inputs of type number in case of keyboard input, pasting, changing a validation method that checks, whether a max value exists and if so Math.min() returns the lowest-valued number passed into it. If the value is not a number 0 is returned.
See a demo at JSFiddle
In Vanilla JavaScript the handler would look like this:
var numElement = document.querySelector('input[type="number"]')
numElement.addEventListener('change', validateMax);
numElement.addEventListener('input', validateMax);
numElement.addEventListener('keyup', validateMax);
numElement.addEventListener('paste', validateMax);
function validateMax() {
if (this.max) this.value = Math.min(parseInt(this.max), parseInt(this.value) || 0);
}
See a demo of the vanilla version at JSFiddle
This handler should do the trick.
I don't think there is a solution directly with HTML; the max and min attributes only work when clicking the up arrow and down arrow keys. Check out the post in the references section for more information. The image below shows that the input does not change when the up arrow button is clicked, since the max attribute is 100:
In the solution below, when the input event of the <input> element is triggered, the data input is checked by checking the max attribute with the isValid() method. You can change the disabled property of the submit button according to the result returned by the isValid() method.
const inputElement = document.querySelector('input');
function isValid(value){
if(parseInt(value) <= inputElement.getAttribute('max'))
return true;
return false;
}
inputElement.addEventListener('input', function () {
if(isValid(this.value))
console.log("true");
else
console.log("false");
});
<input type="number" max="100">
References
How can I limit possible inputs in a HTML5 "number" element?
If you are using form, you can just mark it as required and the form does the validation for you.
document.getElementById("myForm").addEventListener("submit", function (event) {
event.preventDefault();
console.log(document.getElementById("myNumber").value);
});
<form id="myForm">
<input id="myNumber" name="myNumber" type="number" max="100" required >
<button>Send It</button>
</form>
Now if you want to know if it is valid in JavaScript directly there is built in methods for that
document.getElementById("myForm").addEventListener("submit", function(event) {
event.preventDefault();
console.log(document.getElementById("myNumber").value);
});
document.getElementById("check").addEventListener("click", function(event) {
console.log("form: ", document.getElementById("myForm").checkValidity());
console.log("input: ", document.getElementById("myNumber").validity.valid);
});
<form id="myForm">
<input id="myNumber" name="myNumber" type="number" max="100" required>
<button>Send It</button>
</form>
<button type="button" id="check">Check It</button>
Using the code below, I am able to use .on("invalid") function to detect if there was an error with a field when submitting a form. If there was an error, I then check if both the input and textarea if either of them or empty, too long or too short and add the class .error.
However I am wondering if there is any way to simplify my code so that I don't have to run additional if statements inside the function.
$("form input, form textarea").on("invalid", function(event) {
var input1 = document.getElementById('input1');
var input2 = document.getElementById('input2');
if (!input1.value || input1.value.length < 9 || input1.value.length > 69) {
input1.classList.add('error');
setTimeout(function() {
input1.classList.remove('error');
}, 500);
}
if (!input2.value || input2.value.length < 21 || input2.value.length > 899) {
input2.classList.add('error');
setTimeout(function() {
input2.classList.remove('error');
}, 500);
}
});
.error {
border: 1px solid red;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form>
<input type="text" id="input1" minlength="8" maxlength="70" required>
<textarea id="input2" maxlength="900" required></textarea>
<input type="submit">
</form>
Here is an example of what I am looking for, where x is the field (the input or textarea) which caused the form to be invalid.:
$("form input, form textarea").on("invalid", function(event) {
x.classList.add('error'); // variable x
setTimeout(function() {
x.classList.remove('error'); // variable x
}, 500);
});
I would ideally like to stick to JavaScript, however I appreciate that jQuery may be needed.
Here is a possible solution that doesn't exactly find the target with javascript, but uses the oninvalid event listener in html.
<input type="text" oninvalid="alert('You must fill out the form!');" required>
When the form returns invalid, instead of it being packaged as a form event, this will trigger as an input event. You can make it do whatever you like in javascript when that specific input is incorrect upon form submission.
https://www.w3schools.com/jsref/event_onsubmit.asp
The event onsubmit perhaps will be a better option. Is valid for all browsers
https://www.w3schools.com/jsref/event_oninvalid.asp
Instead, if you use oninvalid you will find problems with the Safari browser
<form onsubmit="validateForm()">
Enter name: <input type="text">
<input type="submit">
</form>
function validateForm() {
//your code here
if(validationfails){
return false; //if arrives here means the form won't be submited
}
}
I was able to solve this, particularly thanks to the suggestion by John Paul Penaloza, by using oninvalid on the input and textarea field. I called a function which then added the class .error to the input field - it does the same as the code in my question, but simpler:
function error(field) {
field.classList.add('error');
setTimeout(function() {
field.classList.remove('error');
}, 500);
}
.error {
border: 1px solid red;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form>
<input type="text" id="input1" oninvalid="error(this);" minlength="8" maxlength="70" required>
<textarea id="input2" oninvalid="error(this);" maxlength="900" required></textarea>
<input type="submit">
</form>
Or you can think differently and offer real time error reporting.
Add an id="myForm" to your <form> element, and then use Js in a lines of:
var allInputs = $('#myForm :input');
var inputsFuked = []
allInputs.each(function( index ) {
console.log(allInputs[index]);
$(allInputs[index]).change(function() {
if (allInputs[index].checkValidity()) inputsFuked[index]=1;
else inputsFuked[index]=0;
});
});
Here is working JSfiddle with couple of more elements without validation.
This will bind on change code to be executed every time some input changes. This is an example so it only toggles values in array. When you wanna validate, you simply check which are wrong. If you stored elements in array you could state which element. Simply switch toggle index logic to add/remove from array.
But with this contraption you can do way better, you can write instant reaction to invalid element. Instead changing index in array you could prompt alert, display error, make element red. Basically interact with the user the moment he focused out of element where he made input error instead doing it passively at some point after.
I have a very simple piece of Javascript that works perfectly onLoad, but I need it to work onChange.
My script;
<form action="" method="post" name="product_search">
<p><strong>Existing Part Number:</strong>
<input name="v_prodref" type="text" id="v_prodref" size="25" maxlength="25" onChange="searchValue()">
<input type="text" name="prodref" id="prodref">
<input type="submit" name="search_Submit" id="search_Submit" value="Submit">
</p>
<div>
<%=(rs_ProductCheck.Fields.Item("prodref").Value)%>
// <%=(rs_ProductCheck.Fields.Item("proddesc").Value)%></div>
<script>
function searchValue() {
var add = "NW";
var c_ProdRef = document.getElementById('v_prodref');
if(c_ProdRef.search(/GST/i) == -1) {
n_ProdRef = c_ProdRef.concat(add) }
else {
n_ProdRef = c_ProdRef.replace(/GST/i,"NWGST") }
document.getElementById("prodref").value = n_ProdRef;
}
</script>
</form>
So, I enter a part number in the first text box, and I want my javascript to run and enter the new value in the second text box, but it doesn't seem to work.
What am I missing?
search does not exist on an HTMLInputElement. You need to use c_ProdRef.value.search.
(Actually, since you're using it in many places as a string, and never as an input, you probably intended to define c_ProdRef as var document.getElementById('v_prodref').value)
You would've seen this error on load as well.
you want onkeyup if it works perfectly onLoad, and you want to start typing in something in textbox 1 and the javascript to run, you dont want onchange
onchange triggers after blur of focused element
onkeyup triggers after you release a keyboard input
Thanks to everyone for their help. After a little tweaking I have managed to get my code working.
function myFunction() {
var add = "NW";
var c_ProdRef = document.getElementById('v_prodref').value;
if (c_ProdRef.search(/GST/i) == -1) {
n_ProdRef = c_ProdRef.concat(add)
} else {
n_ProdRef = c_ProdRef.replace(/GST/i, "NWGST")
}
document.getElementById("prodref").value = n_ProdRef;
}
Along with #indubitablee suggestion of onKeyup and specifying the .value of my first text field it all works.
Say I got a HTML form like below and want to pass the values in the textfields to JS variables.
<form name="testform" action="" method="?"
<input type="text" name="testfield1"/>
<input type="text" name="testfield2"/>
</form>
I've only passed values to variables in PHP before. When doing it in javascript, do I need a method? And the main question, how is it done?
Here are a couple of examples:
Javascript:
document.getElementById('name_of_input_control_id').value;
jQuery:
$("#name_of_input_control_id").val();
Basically you are extracting the value of the input control out of the DOM using Javascript/jQuery.
the answers are all correct but you may face problems if you dont put your code into a document.ready function ... if your codeblock is above the html part you will not find any input field with the id, because in this moment it doesnt exist...
document.addEventListener('DOMContentLoaded', function() {
var input = document.getElementById('name_of_input_control_id').value;
}, false);
jQuery
jQuery(document).ready(function($){
var input = $("#name_of_input_control_id").val();
});
You don't really need a method or an action attribute if you're simply using the text fields in Javascript
Add a submit button and an onsubmit handler to the form like this,
<form name="testform" onsubmit="return processForm(this)">
<input type="text" name="testfield1"/>
<input type="text" name="testfield2"/>
<input type="submit"/>
</form>
Then in your Javascript you could have this processForm function
function processForm(form) {
var inputs = form.getElementsByTagName("input");
// parse text field values into an object
var textValues = {};
for(var x = 0; x < inputs.length; x++) {
if(inputs[x].type != "text") {
// ignore anything which is NOT a text field
continue;
}
textValues[inputs[x].name] = inputs[x].value;
}
// textValues['testfield1'] contains value of first input
// textValues['testfield2'] contains value of second input
return false; // this causes form to NOT 'refresh' the page
}
Try the following in your "submit":
var input = $("#testfield1").val();
I have a simple HTML form that asks a user to input their name, SKU, quantity, and comments. This is for a simple inventory request system.
<html>
<body>
<form id="myForm" method="post">
<input type="submit">
<br>Name: <input type="text" name="form[name]">
<br>SKU: <input type="text" name="form[SKU1]">
<br>Quantity: <input type="text" name="form[quantity1]">
<br>Comment: <input type="text" name="form[comment1]">
</form>
Add item
<script>
var num = 2; //The first option to be added is number 2
function addOption() {
var theForm = document.getElementById("myForm");
var newOption = document.createElement("input");
newOption.name = "form[SKU"+num+"]"; // form[varX]
newOption.type = "text";
theForm.appendChild(newOption); //How can I add a newline here?
optionNumber++;
}
</script>
</body>
</html>
Currently I can only get it working where it will add a single form value. I would like to recreate the entire myForm except for the name field with a single click.
Your post is very old, so presumably you've found an answer by now. However, there are some things amiss with your code.
In the JavaScript code you have
var num = 2;
This is the number that is incremented to keep track of how many "line-items" you will have on the form. In the function addOption(), though, instead of incrementing num you have
optionNumber++;
You never use optionNumber anywhere else. Your code works once, when you add the first item, but since you increment the wrong variable, you are effectively always adding option 2.
Oh, and adding the newline: you need to append a <br> element.