HTML FORM + pureJS Auto multiply script - javascript

I have a simplified HTML form that I would like to multiply entered amount by 100 and send it with GET method to any endpoint.
Here is my form:
<body>
<form method="get" action="https://endpoint/purchase.php">
<input type="text" name="description" value="description">
<input type="text" name="amount">
<input type="submit" value="pay">
</form>
</body>
And my Js
var $output = $("#output-value");
$("#input-value").keyup(function() {
var value = parseFloat($(this).val());
$output.val(amount*100);
});
I'm stuck here, as I don't know how to connect them to send a proper value where I want?
Thank You. That helps a lot, I have another problem, where, in which the URL passed in GET is shortened / cut out?
So below is an original URL
https://sklep.przelewy24.pl/zakup.php?z24_id_sprzedawcy=88696&z24_kwota=10000&z24_currency=pln&z24_nazwa=test&z24_opis=test&z24_return_url=http%3A%2F%2Fwww.przelewy24.pl&z24_language=pl&k24_kraj=PL&z24_crc=ca056736&
I would like to be able to dynamiclly trnasfer z24_kwota (/z24_amount) so my form can transfer the amount as I want.
After tweaking the code above to my needs:
<html>
<head>
<meta charset="utf-8">
<title>Formularz uproszczony</title>
</head>
<body>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js">
</script>
<form id="testForm" method="get" action="https://sklep.przelewy24.pl/zakup.php?z24_id_sprzedawcy=88696&z24_currency=pln&z24_nazwa=test&z24_opis=test&z24_return_url=http%3A%2F%2Fwww.przelewy24.pl&z24_language=pl&k24_kraj=PL&z24_crc=ca056736&">
<input type="text" name="z24_kwota" value="Kwota">
<input type="submit" value="zapłać ">
<script>
$("#testForm").on('submit', function() {
var amount = $("#testForm input[name='z24_kwota']")
var value = parseFloat(amount.val());
value = value * 100 || 0; // set zero for non number
if (prompt("Kwota przekazywana do Przelewy24 to: ", value)) {
amount.val(value);
return true
}
else {
console.log('submission aborted, value not multiplied')
return false;
}
});</script>
</form>
</body>
</html>
I see that only first part is in the browser adress bar:
'''https://sklep.przelewy24.pl/zakup.php?z24_kwota=2000'''
Can someone tell me why that is, and how to fix it ?

This is common problem, please see browser console (F12) and check for error, you don't have element with ID #input-value, #output-value and variable amount
if you want to change input name amount before submit use submit event
$("#testForm").on('submit', function() {
var amount = $("#testForm input[name='amount']")
var value = parseFloat(amount.val());
value = value * 100 || 0; // set zero for non number
if (prompt("amount value now: ", value)) {
amount.val(value);
return true
}
else {
console.log('submission aborted, value not multiplied')
return false;
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form id="testForm" method="get" action="https://endpoint/purchase.php">
<input type="text" name="description" value="description">
<input type="text" name="amount">
<input type="submit" value="zapłać z przelewy24.pl">
</form>

Related

How to run a function in input tags value attribute

I have an html page that i send to a client as response when he wants to transfer money
response.end(
`
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>The Good Server</title>
</head>
<body>
<p>Transfer money to other users with the super safe form which uses the latest HTTP GET method!</p>
<form action="/money_transfer" method="get">
<div class="container">
<label for="from"><b>Tranfer from</b></label>
<input type="text" value="good_user" name="from" required readonly>
<label for="to"><b>Transfer to</b></label>
<input type="text" placeholder="User you want to send money to" name="to" required>
<label for="sum"><b>Sum to transfer (in full Euros)</b></label>
<input type="number" placeholder="Enter a sum" name="sum" required>
<input name="csrf_token" type="hidden" value="setCSRFtoken()">
<button type="submit">Transfer money</button>
</div>
</form>
</body>
</html>
`
);
I try to get the an randomly generated token and set it as a value for the input tag as is shown before the button: Transfer money. My setCSRFtoken function also stores the token into an array.
const setCSRFtoken = () => {
var result = '';
var characters = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
var charactersLength = characters.length;
for ( var i = 0; i < 10; i++ ) {
result += characters.charAt(Math.floor(Math.random() * charactersLength));
}
console.log(result)
csrfTokens.push(result);
return result;
The value that returns from the setCSRFtoken function must be placed in to the input's(name=crsf_token) value.
The problem is that at the moment i cant get the function to run in the page and return the randomly generated value. i also thought about adding the value as parameter to the page but dont know how add it to the response.
<input name="csrf_token" type="hidden" onload="this.value=setCSRF()">
Saw the code above as an fix but it didn't work for me

Issue with onsubmit not allowing action to send

I have an html form that runs a script to check if the inputs are empty, and if so, it will not submit and it will send an alert. But when the inputs are correct, I want it to go to my contact.php action. It's running the script correctly but its not activating or sending the data to my contact.php. It's running the script correctly but only the script.
index.html
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
</head>
<body>
<script src="form.js"></script>
<form name="Form" onsubmit="return formValidate(event)" action="contact.php" method="post">
<label>Name:<span id="label_name"></span></label>
<input type="text" id="name" name="name"><br/>
<label >Email:<span id="label_email"></span></label>
<input type="text" id="email" name="email"><br/>
<label >Subject:<span id="label_subject"></span></label>
<input type="text" id="subject" name="subject"><br/>
<label >Email:<span id="label_message"></span></label>
<input type="text" id="message" name="message"><br/>
<button type="submit" name="submit">Submit</button>
</form>
</body>
</html>
form.js
function formValidate(event) {
event.preventDefault();
var name = document.forms["Form"]["name"].value;
var email = document.forms["Form"]["email"].value;
var subject = document.forms["Form"]["subject"].value;
var message = document.forms["Form"]["message"].value;
if (name == "" || email == "" || subject == "" || message == "") {
output = "*";
alert('Fill out all required inputs');
return false;
} else {
alert('Thanks for contacting me!')
}
return true;
document.getElementById("label_name").innerHTML = output;
document.getElementById("label_email").innerHTML = output;
document.getElementById("label_subject").innerHTML = output;
document.getElementById("label_message").innerHTML = output;
}
Rather than return true/false, use your conditions to decide whether to call event.preventDefault. I don't think it actually matters what you return.
Normally, people write that as the first line because they're going to submit the data in a different way, like AJAX. If you're doing a normal full-page submit, then you don't want to prevent the normal behavior of submitting.

Limit number of words user enters into a text box without button click action

I want to limit number of words that user input to a text box . I tried one code it was successfull for only single text box when i ammend it to multiple text box this code did not work, An advice will be really appreciated.
<html>
<head>
<script type="text/javascript">
function validate(){
x=document.myForm
input=x.myInput.value
if (input.length>5){
alert("The field cannot contain more than 5 characters!")
return false
}else {
return true
}
}
</script>
</head>
<body>
<form name="myForm" action="http://www.java2s.com" onsubmit="return validate()">
Enter some text (less than 5 characters):
<input type="text" name="myInput" size="20">
<input type="submit" value="Submit">
</form>
</body>
</html>
There are two methods to go about it:
Method 1:
Using the maxlength="5" attribute
<input type="text" maxlength="5" name="somename"/>
Method 2:
Using Javascript:
<script language="javascript" type="text/javascript">
function limitInput(field, max) {
if (field.value.length > max) {
field.value = field.value.substring(0, max);
}
}
</script>
<input type="text" name="somename" onKeyDown="limitInput(this,5);" onKeyUp="limitInput(this,5);"" />
UPDATE
With a message:
<script language="javascript" type="text/javascript">
var errHolder = document.getElementById('err');
function limitInput(field, max) {
if (field.value.length > max) {
err.style.display = 'inline-block';
}
else
{
err.style.display = 'none';
}
}
</script>
<span>
<input type="text" name="somename" onKeyDown="limitInput(this,5);" onKeyUp="limitInput(this,5);" />
</span>
<span id="err" style="display:none;background-color:red;">Please enter less than 5 characters</span>
You can either set the maxlength attribute or trim the string everytime the user enters into it. Using maxlength is a better way of doing it
var input = document.getElementById("limit5");
var LIMIT = 5;
input.onkeyup=function(){
if(input.value.length > LIMIT){
input.value = input.value.substr(0,LIMIT);
//alert("Please limit your input to 5 characters")
}
}
<input id="autolimit5" maxlength="5" type="text"/>
<input id="limit5" type="text"/>
There are many ways to to prevent user from entering data in form elements. What you are trying is to validate all data in one go when user clicks on the Submit button. It would be better to validate at the time when the user is typing. Basically there are 4 related events whenever the user presses anything on the keyboard.
onKeyPress
onKeyDown
onKeyUp
onInput
You can use a combination of these events to achieve anything that you want. For the use case in the question we can just use keypress event.
<html>
<head>
<script type="text/javascript">
function validate(){
x=document.myForm
input=x.myInput.value
if (input.length>5){
alert("The field cannot contain more than 5 characters!")
return false
}else {
return true
}
}
// function which runs on every keypress of input element to which this
// function is attached
function validateTextField(e){
if(event.currentTarget.value.length >= 5){
return false;
}
}
</script>
</head>
<body>
<form name="myForm" action="http://nothing.com" onsubmit="return validate()">
Enter some text (less than 5 characters):
<input type="text" name="myInput" size="20" onkeypress="return validateTextField(event)">
<input type="text" name="anotherInput" size="20" onkeypress="return validateTextField(event)">
<input type="submit" value="Submit">
</form>
</body>
</html>enter code here
If you want, you can customize the size for the validation by changing some of the parameters
Update the html input definition with below
<input type="text" name="myInput" size="20" onkeypress="return validateTextField(event, 5)">
<input type="text" name="anotherInput" size="20" onkeypress="return validateTextField(event, 8)">
Update the function definition to use the second parameter
function validateTextField(e, size){
console.log(e);
if(event.currentTarget.value.length >= size){
return false;
}
}

How to add JavaScript variables to a form action

I need to the add a JavaScript variable to a link in action form. Is that possible?
JavaScript function:
<script>
function parameter()
{
function getUrlVars() {
var vars = {};
var parts = window.location.href.replace(/[?&]+([^=&]+)=([^&]*)/gi, function (m, key, value) {
vars[key] = value;
});
return vars;
}
var vpid = getUrlVars()["pid"];
}
//var link = "second_02.html" + pid.toString();
</script>
And in my form I need to add the variable 'link' to a form action, as follows:
<form action='second_02.html + ?pid=vpid&' id="sky-form" class="sky-form">
You'll need to do that programmatically via JavaScript.
After this line...
var vpid = getUrlVars()["pid"];
Add this one...
document.getElementById('sky-form').action = 'second_02.html?pid=' + vpid;
Given the nature of the content of vpid, then you could implements this in the load event of your window.
ALTERNATE METHOD 1
Here's an alternate method of doing what you appear to require, but it requires you to set the new location with the calculated parameter. You can amend the lines that try to get the text from the textbox, with whatever you need to append to your URL.
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<script>
function validateForm() {
//alert('Validating form...');
var text = document.getElementById('txtValue').value;
text = escape(text);
location.href = 'test.html?param=' + text;
return false;
}
</script>
</head>
<body>
<form id="frmTest" method="get" action="" onsubmit="return validateForm();">
<input id="txtValue" type="text" value="foobar">
<input id="btnSubmit" type="submit" value="Submit">
</form>
</body>
</html>
ALTERNATE METHOD 2
This method allows you to continue to use your form, even with its GET method, but you set the value of a hidden field, that will then be appended to the URL in the querystring during submission.
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<script>
function validateForm() {
//alert('Validating form...');
document.getElementById('hidTest').value = 'some calculated value';
return true;
}
</script>
</head>
<body>
<form id="frmTest" method="get" action="" onsubmit="return validateForm();">
<input id="txtValue" type="text" value="foobar">
<input id="btnSubmit" type="submit" value="Submit">
<input name="hidTest" id="hidTest" type="hidden" value="testIt">
</form>
</body>
</html>

Updating form values and stop submitting it

I have an HTML code:
<form action="?" id="form1" method="POST" onsubmit="return g.submitForm();">
<input type="text" name="posX" id="formPosX" />
<input type="text" name="posY" id="formPosY" />
<input type="submit" value="Send" />
</form>
and JS code:
var g = {
submitForm: function () {
var form = document.forms.form1;
if ( form.posX.value > 100 )
{
form.posX.value = 100;
}
return false;
}
}
and this form is always sending after updating values. My goal is to update wrong values and stop submitting form (I'd like to do it via AJAX). When I remove the IF statement then code works fine, but I need to update some values (and also show an error, if is).
Hope you'll understand my very bad English :)
You're assuming the value in the form input is an integer, when in reality it will be treated as a string data type. Try converting the value to a number before applying the comparison.
if ( parseInt(form.posX.value) > 100 )
{
form.posX.value = "100";
}
I've adapted your code see below (You will need to include the Jquery library):
JS Fiddle
http://jsfiddle.net/boggey79/kN49d/
Form request stopped, because onSubmit return false. You need return true.
Check input value on keypress event:
<script>
function checkPosX(this) {
if ( parseInt(this.value) > 100 ) {
this.value = "100";
}
}
</script>
<form action="?" id="form1" method="POST">
<input type="text" name="posX" id="formPosX" onkeypress="checkPosX(this)" />
<input type="text" name="posY" id="formPosY" />
<input type="submit" value="Send" />
</form>
Then work fine.

Categories