How to add JavaScript variables to a form action - javascript

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>

Related

HTML FORM + pureJS Auto multiply script

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>

How do I trigger a JavaScript function when a button is pressed in HTML code

I am trying to create a calculator that solves the Pythagoras theorem. I have created a function inside a tag in my code which takes two arguments (one for each leg length of the right-angled triangle) The function works if I just do a console.log with two numbers as arguments and the function executes properly if it is inside the script tag. But I just want to know how to take the two arguments in the text boxes and then when I press the button make the result appear on the screen.
<html>
<main>
<head>
<!--Textboxes to input lengths of legs-->
<input type = "text" required placeholder= "1st legnth">
<br> <br>
<input type = "text" required placeholder= "2nd legnth">
<br> <br>
<button type = "submit">Give me the answer.
</head>
</main>
</html>
<script>
function solveforHyp (a, b)
{
var c = a*a + b*b;
return Math.sqrt(c);
}
var final = (solveforHyp(3, 4));
console.log(final);
</script>
add a span after the button to contain the final result:
<span id="final-result"></span>
add an onclick event to your button, it might look like this:
<button type="button" onclick="onButtonSubmit()"></button>
you might also give some relevant ID's to the input like this:
<input type = "text" id="first-length" required placeholder= "1st legnth">
<input type = "text" id="second-length" required placeholder= "2nd legnth">
and finally, write the onButtonSubmit function to access the inputs and call the solveforHyp function :
function onButtonSubmit(){
const firstValue = document.getElementById('first-length').value;
const secondValue = document.getElementById('second-length').value;
document.getElementById('final-result').innerText = solveforHyp(firstValue,secondValue); // finally, put the returned value in the created span.
}
First of all your document structure is entirely wrong, a lot of tags are not closed script is after the HTML tag, and content is written inside head tag and head is inside main, NO doctype declaration is done, and most importantly if you wanna submit something you should have a form at least with preventing its default behavior. Learn HTML before JavaScript Brother, and also its a good practice to use input type Number when you already know the input will be always a Number.
and here is the code what you are trying to make
<!DOCTYPE html>
<html>
<head>
<title>Example</title>
</head>
<body>
<form id="formOne">
<input type="number" required placeholder="1st legnth" id="first">
<br> <br>
<input type="number" required placeholder="2nd legnth" id="second">
<br> <br>
<button type="submit">Give me the answer</button>
</form>
</body>
<script>
let form = document.querySelector("#formOne");
let inputOne = document.querySelector("#first");
let inputTwo = document.querySelector("#second");
form.addEventListener("submit", function(e){
e.preventDefault();
console.log(Math.sqrt(Math.pow(inputOne.value,2) + Math.pow(inputTwo.value,2)));
})
</script>
</html>
Js file function to be called
function tryMe(arg) {
document.write(arg);
}
HTML FILE
<!DOCTYPE html>
<html>
<head>
<script type="text/javascript" src='object.js'> </script>
<title>abc</title><meta charset="utf-8"/>
</head>
<body>
<script>
tryMe('This is me vishal bhasin signing in');
</script>
</body>
</html>
You can try like this:
<!DOCTYPE html>
<html>
<head>
<title>Parcel Sandbox</title>
<meta charset="UTF-8" />
</head>
<body>
<form id="form">
<input type="text" id="first_length" name="first_length" />
<input type="text" id="second_length" name="second_length" />
<input type="submit" value="Submit" />
</form>
<script>
function logSubmit(event) {
event.preventDefault();
var first_length = document.getElementById("first_length").value;
var second_length = document.getElementById("second_length").value;
var final = solveforHyp(first_length, second_length);
console.log(final);
}
const form = document.getElementById("form");
form.addEventListener("submit", logSubmit);
function solveforHyp(a, b) {
var c = a * a + b * b;
return Math.sqrt(c);
}
</script>
</body>
</html>

onsubmit function used for form is coming up undefined

I want to validate my form, and have created a formValidation function with onsubmit, that calls a function from a js.js file. When I click submit, however, I get this error:
Here is the necessary form code:
<form action="send-email.php" id="callback" class="popup-form" method="post" onsubmit="return validateForm()">
// Form content
</form>
Here is the function code:
function validateForm() {
console.log("hellloooooo this is working");
// var captcha_response = grecaptcha.getResponse();
// if(captcha_response.length === 0)
// {
// // Captcha is not Passed
// console.log("not working");
// return false;
// }
// else
// {
// // Captcha is Passed
// console.log("working");
// return true;
// }
}
The script tag is within the body tag, so it should work.. where am I going wrong??
Please use input type='submit' in form. It will work in java script as well.
Add submit input in the form as below
<form action="send-email.php" id="callback" class="popup-form" method="post" onsubmit="return validateForm()"><input type="submit">
</form>
And in java script write your validation function as below
<script type="text/javascript">
function validateForm(){
console.log('ddd');
return false;
}
</script>
You should be sure that your script tag above your form tag
This seems to be working. Don't see any issue here
<head>
<meta charset="utf-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<title>Page Title</title>
</head>
<body>
<script>
function validateForm() {
console.log("hellloooooo this is working");
}
</script>
<form id="callback" class="popup-form" method="post" onsubmit="return validateForm()">
// Form content
<input type="Submit">
</form>
</body>
</html>

Is more than one method call possible at the onclick of a button?

I was wondering if i can call two functions at the onclick of a button? Basically what i have is a form which submit button calls a function which saves the field values into localstorage. What i want to do is when the user clicks the save button, the data will be INSERTED into a MSYQL database. How can i do that? As with that button i am calling save() function which saves them at the localstorage. Can more than one function be called on one button onclick? Below is my code -
<!DOCTYPE HTML>
<html>
<head>
<title>Localstorage Test</title>
<script type="text/javascript">
function save(){
var fieldvalue = document.getElementById('textfield1').value;
var fieldvalue1 = document.getElementById('textfield2').value;
var fieldvalue2 = document.getElementById('textfield3').value;
localStorage.setItem('text',fieldvalue);
localStorage.setItem('text1',fieldvalue1);
localStorage.setItem('text2',fieldvalue2);
}
function load(){
var storedValue = localStorage.getItem('text');
var storedValue1 = localStorage.getItem('text1');
var storedValue2 = localStorage.getItem('text2');
if(storedValue){
document.getElementById('textfield1').value = storedValue;
}
if(storedValue1){
document.getElementById('textfield2').value = storedValue1;
}
if(storedValue2){
document.getElementById('textfield3').value = storedValue2;
}
}
</script>
</head>
<body onload="load()">
<input type="text" id="textfield1" />
<input type="text" id="textfield2" />
<input type="text" id="textfield3" />
<input type="submit" value="Save" onclick="save()">
</body>
</html>
It is possible to call more than one function in onclick event:
<input type="submit" value="Save" onclick="save(); alert('hello!');">

Form textbox content with javascript

I would like to know if there is better way to this exercice.
Here it is : Create a form that contain a textbox ;after the user enter the text ,all the letters will be converted to lowercase as soon as he or she clicks elsewhere in the form( hint: use change onChange event handler).
I have written this code :
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Event</title>
</head>
<body>
<form>
Username : <input type="text" id="username"><br>
<input type="submit" value="button">
</form>
<script type="text/javascript">
var username = document.getElementById("username");
username.onchange = function(){
username.value = username.value.toLowerCase();
};
</script>
</body>
</html>
Basically i'm replacing the content of the textbox by the formatted
Might be too easy, but setting the text over a style to lowercase transform doesn't allow uppercase :)
function toLower(element) {
if (element && element.value) {
element.value = element.value.toLowerCase();
var target = document.getElementById('realvalue');
target.innerHTML = element.value;
}
}
<input type="text" onblur="toLower(this)" />
<div id="realvalue"></div>
But, if all the letters will be converted to lowercase as soon as he or she clicks elsewhere in the form, your code work correctly...
http://jsfiddle.net/b6xwde62/
<form>
Username : <input type="text" id="username"><br>
<input type="submit" value="button">
</form>
<script type="text/javascript">
var username = document.getElementById("username");
username.onchange = function(){
username.value = username.value.toLowerCase();
};
</script>

Categories