I want to use global variable number = 2, but when in input form something is put I want to change value of global variable because I'm going to use it in another function so at the beginning I want number = 2 but when other value is put in input form I want number to take that value.
<form onsubmit="return timed('commands')">
<input type="number" name="a" id="commands"><br>
</form>
var number= 2;
function timed(id)
{
number=getElementById(id).value;
return false;
}
You can add the event onchange to handle this:
<form onsubmit="return timed('commands')">
<input type="number" name="a" id="commands" onchange="changeNumber(this.value)"/><br>
</form>
And add the function in the area:
function changeNumber(value){
number=value
}
Related
Apologies if this is already covered... I'm trying to pass information from a basic text input form and then parse that information using another couple functions. I'm not able to figure out how to return the information from the function in the onClick property to pass it into another function.
function getBulletAction(element) {
return element[0].value;
}
// why can't i store this in a variable outside of the function???
let valueFrmForm = getBulletAction(document.getElementById("frmForm"));
document.getElementById("log").innerHTML = valueFrmForm;
//I want to pass the value returned from getBulletAction() to getAction() which will change the user input to lowercase characters.
function getAction(OutOfTheFunction){
let action = userInput.toLocaleLowerCase('en-US');
return action;
}
<form name="bulletForm" id="frmForm">
Write the action of your bullet:<br>
<input type="text" name="bulletAction" value="" style="width: 30%;"/>
<input type="button" name="submitType" value="Submit" onClick="getBulletAction(this.parentElement)" />
</form>
<h3>This is where the data is supposed to appear from getBulletAction()</h3>
<p id="log"></p>
You are storing value in global variable when script loads(at the time when was empty)
Create one global variable at the start of script
Change value of global variable when user clicks submit button
Use the global variable in another function
var text = "";
function getBulletAction(form) {
text = form[0].value; //first input element
return form[0].value;
}
function myFunc(form){
var inputText = getBulletAction(form);
document.getElementById("log").innerHTML = getAction();
}
function getAction(){ //let's use global variable
let action = text.toLocaleLowerCase('en-US');
return action;
}
function alertMyGlobalVar(){
alert(text);
}
<form name="bulletForm" id="frmForm">
Write the action of your bullet:<br>
<input type="text" name="bulletAction" value="" style="width: 30%;"/>
<input type="button" name="submitType" value="Submit" onClick="myFunc(this.parentElement)" />
</form>
<button onclick="alertMyGlobalVar()">Current value of global variable</button><br>
<h id="log">This is where the data is supposed to appear from getBulletAction()</h3>
The first keyup event will change the value of one input but on the change of one input gn() in not calling.
This is my code
function fn() {
document.getElementById("one").value = "abc"
}
function gn() {
document.getElementById("two").value = "def"
}
<input type="number" onkeyup="fn()">
<input type="number" id="one" onchange="gn()">
<input type="number" id="two">
The first assignment wasn't working because you were trying to set a "number" input to a non-numeric value.
The second assignment wasn't working because the onchange event isn't triggered when the value of a field is modified by script; you have to create and dispatch the event manually:
function fn() {
// This will work because the #one input is now type="text"
document.getElementById("one").value = "abc";
// now create and dispatch a change event on the field you modified:
var evt = new Event('change');
document.getElementById("one").dispatchEvent(evt)
// (Or, of course, just call gn() directly here.)
}
function gn() {
document.getElementById("two").value = "def"
}
<input type="text" onkeyup="fn()">
<input type="text" id="one" onchange="gn()">
<input type="text" id="two">
You're trying to set the value of a number input to a string, and not even one that can be cast to a number.
Replace your functions with:
document.getElementById("one").value = "123";
or
document.getElementById("one").value = 123;
and that will work.
If you want the input to be set to abc, you should switch the input type from number to text
<input type="text" id="one" onchange="gn()">
EDIT
I copied my proposed solution of changing inputs into text into an HTML file. Below is the entirety of that file:
1 <html>
2
3 <input type="text" onkeyup="fn()">
4 <input type="text" id="one" onchange="gn()">
5 <input type="text" id="two">
6
7 <script>
8 function fn(){ document.getElementById("one").value = "abc"}
9 function gn(){ document.getElementById("two").value = "def"}
10 </script>
11 </html>
With this, a keyup event in the first box will change the 2nd input to abc. Changing the value (as in, entering in a value and clicking out of) the 2nd box will make the 3rd box have a value of def.
Is it possible to directly use the result of a Javascript function as an input value for an HTML form?
<form class="my-form" action="fileUpload.php" method="POST" enctype="multipart/form-data">
<input type="hidden" name="User_id" value="getValue();">
<input type="submit" value="Submit"/>
</form>
This is clearly not correct, but I hope it communicates what I am trying to do. I would like the returned result of JS function getValue(); to act as the input value.
In that implementation, no it is not possible to equate the value attribute inside the input tag to a JavaScript function.
According to w3.org, the value attribute can only equal
String without line breaks
Any string that contains no line feed
(U+000A, “LF”) or carriage return (U+000D, “CR”) characters.
I am not sure what is inside the getValue() function, but you can call a click event handler when the submit button is clicked and run that getValue() function.
Ex.
<form class="my-form" action="fileUpload.php" method="POST" enctype="multipart/form-data">
<input type="hidden" name="User_id">
<input type="submit" value="Submit" onclick="getValue();"/>
</form>
I hope it guides you well.
While it is technically possible to do something like this:
<script>
function getValue(){ return "foo"; }
document.write("<input type='hidden' name='User_id' value='" + getValue() + "' />");
</script>
That is typically frowned upon as there are scoping issues and page rendering implications. The more accepted way would be to do something more like this..
function getValue(){ return "bar"; }
window.addEventListener("load", function(event){
document.querySelector("input[name='User_id']").value = getValue();
});
or potentially at form submit or submit button click with something like:
function getValue(){ return "bar"; }
document.querySelector("input[type='submit']").addEventListener("click", function(){
document.querySelector("input[name='User_id']").value = getValue();
});
Though I am not keen on it myself, it would be possible to do the same as above with:
<input type="submit" value="Submit" onclick="setUserId();"/>
Then later in say a end of body script block do:
function getValue(){ return "bar"; }
function setUserId(){
document.querySelector("input[name='User_id']").value = getValue();
}
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).
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();