I have a single form input on my homepage userinput. The homepage also contains a JavaScript function that uses that userinput value to calculate a result.
<form action="/run.php" method="POST" target="_blank">
<input type="hidden" id="idg" value="<?php echo $rand ?>"> // gets random url, can be ignored
<input type="text" name="userinput" id="userinput">
<button type="submit" onclick="calcResult();">Go!</button>
</form>
<script>
function calcResult() {
var userinput = document.getElementById('userinput').value;
var result = userinput + 10; // want to POST result in a hidden input field w/ form
</script>
I'm trying to find a way in which a user can enter their input, submit the form, the JavaScript takes that userinput and calculates a result, then that result is POST'ed along with the userinput in the form.
The problem I can forsee with this method is that:
The JavaScript function needs the userinput before it can calculate the result. However, the only way to get the userinput is to submit the form, which means the form data will be POSTed before the JavaScript result is returned.
My attempted solution(s):
I've been attempting to use AJAX (Unable to access AJAX data [PHP]) and have been consistently running into issues with that.
I was wondering whether it's possible to use a button (type="button"), instead of a submit (type="submit") for the form. Then just use that button to call the JS function, then (somehow) submit the form (with the JS function result) after the JS function has completed? (either with plain JS or jQuery).
there are multiple approaches to do this,
i'm gonna use jquery here instead of pure javascript to simplify it
[without submission] you may check the event change
$('#userinput').change(function (e) {
// make some calculation
// then update the input value
});
[with form submission] you will disable the submission using the object preventDefault inside the submit event
$('#userinput').submit(function (e) {
e.preventDefault();
// make some calculation
// then update the input value
// your ajax goes here OR resubmission of your form
// to resubmit the form
$(this).submit();
});
What you will find useful in this scenario is event.preventDefault();
function calcResult(e) {
// Prevent the default action of the form
e.preventDefault();
var userinput = document.getElementById('userinput').value;
var result = userinput + 10;
// Do whatever else you need to do
// Submit the form with javascript
document.getElementById("myForm").submit();
}
I believe this is what you are looking for. A way of having the information computed over PHP, without a page request. This uses a form and then serializes the data, then transmits it to PHP and displays the result from run.php.
Note:
I did change your id to a name in the HTML so the code would serialize properly. I can change this per request.
index.php
$rand = rand(10,100);
?>
<form action="javascript:void(0);" id="targetForm">
<input type="hidden" name="idg" value="<?php echo $rand ?>">
<input type="text" value="12" name="userinput" id="userinput">
<button onclick="ready()">Go!</button>
</form>
<div id="result"></div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.0/jquery.min.js"></script>
<script>
function ready() {
$.post('run.php', $('#targetForm').serialize(), function (data) {
$("#result").html(data);
})
}
</script>
run.php
<?php
echo floatval($_POST['userinput']) * floatval($_POST['idg']);
?>
Nowhere in your question is there any indicator that your task requires AJAX. You're just trying to change an input value right when you submit. AJAX is not needed for that.
First, attach an onsubmit event handler to your form instead of using an onclick attribute on your button. Notice, we are not stopping the form from submitting with return false as we still want the form to submit.
For convenience, let's add an ID to your form and let's add a hidden input field to store the calculated value.
(Side-remark: you don't need to use document.getElementById(ID) if the ID is a string with no dashes i.e. document.getElementById('userinput') can be shortened to just userinput )
<form action="/run.php" method="POST" target="_blank" id="theform">
<input type="hidden" id="idg" value="<?php echo $rand ?>">
<input type="text" name="userinput" id="userinput">
<input type="hidden" name="hiddeninput" id="hiddeninput">
<button type="submit">Go!</button>
</form>
<script>
// this will be called right when you submit
theform.onsubmit = function calcResult() {
// it should update the value of your hidden field before moving to the next page
hiddeninput.value = parseInt(userinput.value, 10) + 10;
return true;
}
</script>
One way is by onSubmit
<form action="/run.php" method="POST" onSubmit="return calcResult()">
<input type="hidden" id="idg" value="<?php echo $rand ?>"> // gets random url, can be ignored
<input type="text" name="userinput" id="userinput">
<button type="submit" onclick="calcResult();">Go! </button>
</form>
And when you return true then only form will submit.
<script>
function calcResult() {
var userinput = document.getElementById('userinput').value;
var result = userinput + 10; // want to POST result in a hidden input field w/ form
return true;
}
</script>
Related
Due to the layout of my page I would like to place a custom element outside of a form.
Can I make something like <my-custom-element form="foo"> work?
Presuming you want the submit button to return the value of your element even though it is outside the form. This is one way, there are many more (including using the function here called addExtras() to dynamically append your external name/value pair(s) to the form).
<my-custom-element> <input name="custom" id="custom" value="foo"></my-custom-element>
<form id="myForm" onsubmit="return addExtras()" method="post">
<input type="hidden"" name="customItem" id="customItem" />
<input name="anotherField" value="india" />
<button type="submit">submit</button>
</form>
<script>
function addExtras() {
document.getElementById("customItem").value = document.getElementById("custom").value;
return true;
}
// ==========================================================
//Code to display the submitted items, and prevent submission for test purposes
//Not needed for production
document.getElementById("myForm").addEventListener('submit', function (e) {
//prevent the normal submission of the form
e.preventDefault();
for (var i = 0; i < document.getElementById("myForm").elements.length; i++) {
var e = document.getElementById("myForm").elements[i];
console.log(e.name, e.value)
}
});
</script>
I have a textbox the value load from PHP Here is the code
<input type="text" id="fName" value="<?php echo $row['fName']; ?>" disabled/>
<input type="button" value="Edit" onclick="changeValue('fName')" />
my Javascript
function changeValue(id){
var value = "test";
document.getElementById(id).value = value;
}
As soon as I click the function, the value change for a few second and go back to default one from database. Can anyone help me
After clicking on the button, the page will reload so that the value of the database will be restored.
Please change
<input type="button" value="Edit" onclick="changeValue('fName')" />
to
<input type="button" value="Edit" onclick="changeValue('fName'); return false;" />
to avoid submitting the form.
For more information, please have a look at this: What's the effect of adding 'return false' to a click event listener?
If you click on elements like links (a element) or buttons (input[type="button"] or button) page will be redirect. So at the end of onClick action you must write return false to force say to the browser I don't want to redirect this page after click!
For example:
function changeValue(id){
var value = "test";
document.getElementById(id).value = value;
return false;
}
How can i change the PHP value in textbox through Javascript
An alternative to using document.getElementById(id).value would be:
function changeValue(id){
var value = "test";
document.getElementById(id).setAttribute("value", value);
}
I am trying to continuously add to a js variable every time a user enters a value into a box.
So far if they enter '21' the alert will say 'your balance is £12' but then if I enter '15' I want it to say your balance is '27' but instead it says '15' or rather just the latest amount.
The code below:
<form action="" method="get">
<input type="number" value="" id="amountDropped">
<input type="submit" value="Deposit amount" onclick="depositedFunds()">
</form>
var firstAmount = 0;
function depositedFunds(){
var ad = document.getElementById("amountDropped");
firstAmount = +firstAmount + +ad.value;
alert ("Your balance is £" + firstAmount);
};
thanks
The function which makes the change is attached to a submit button.
When the user clicks the button:
The JS runs
The value is updated
The value is alerted
The form is submitted
A new page loads
The new page has var firstAmount = 0; in it
You should:
Set the default value dynamically with server side code. See Unobtrusive JavaScript and
Prevent the default behaviour of the submit button
Using an onclick attribute, you need to return false from the event handler function:
onclick="depositedFunds(); return false;"
Modern code would separate concerns and not tie things so tightly to a specific means of triggering the form submission.
var firstAmount = 0;
function depositedFunds(e) {
e.preventDefault();
var ad = document.getElementById("amountDropped");
firstAmount = +firstAmount + +ad.value;
alert("Your balance is £" + firstAmount);
};
document.querySelector('form').addEventListener('submit', depositedFunds);
<form method="get">
<input type="number" id="amountDropped">
<input type="submit" value="Deposit amount">
</form>
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();
}
I have a page that loads a random MP3 file on each refresh. The user has to guess a name based on the sound via text form input. I want to check their input against the stored string and refresh the page if it's correct. Otherwise, I wan't to give them an incorrect alert and stay on the same page so they can guess again:
<div class="ui-widget" align="center">
<form method="post" action="" class="answer_box" onsubmit="return submit();">
<p>Which hero is it? <input id="tags" name="guess" /></p>
<script>
var key = <?php echo json_encode($rand_key) ?>;
var info = document.getElementById("guess").value;
function submit() {
if (key==info){
alert('Correct!');
return true;
}
else {
alert('Incorrect!');
returnToPreviousPage();
return false;
}
}
</script>
</form>
</div>
Right now, it submits the information to a new page regardless of the input. The javascript alerts are also not showing (I suspect they do show, but the page then refreshes and they disappear). The key variable is the key from the randomly taken value of a PHP array, and info should be the text the user inputs.
Problems found:
you cant use submit as a function name a this is an HtmlForm object
document.getElementById("guess").value; is looking for an element with ID of "guess" and that does not exist.
I would rewrite your script like this:
<script>
var key = <?php echo json_encode($rand_key) ?>;
function my_submit(curr) {
var info = curr.guess.value;
if (key == info) {
alert('Correct!');
return true;
}
else {
alert('Incorrect!');
returnToPreviousPage();
return false;
}
}
</script>
<form onsubmit="return my_submit(this);">
<p>Which hero is it? <input id="tags" name="guess"/></p>
</form>
You have a problem here:
<input id="tags" name="guess" />
Your id is tags, not guess.
You should use document.getElementById("tags").value.
You are trying to retrieve the value of an element with id of "guess." Change this to "tags."
var info = document.getElementById("tags").value;
Also, as #CodeGodie mentioned, you need to change your function name to something other than submit.