Using result of javascript query as input for HTML form - javascript

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();
}

Related

Changing global variable javascript

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
}

Dynamically assign onsubmit validator

In my form I have the following
<script>
function validate(form)
{
if(form.xyz.value=='') return false;
return true;
}
</script>
<form onsubmit="return validate(this)">
<input name="xyz">
<input type="submit" value="submit">
</form>
For some reason I have to assign my onsubmit listener dynamically.
I cound define
document.forms[0].addEventListener('submit',validate);
But how to dynamically achieve return validate(this)
(I need pure JavaScript, not jQuery)
The first argument passed to the event handler function is the Event object. If you want to pass a different value, then create a new function and pass it explicitly.
function validateEventHandler(event) {
return validate(this);
}
document.forms[0].addEventListener('submit',validateEventHandler);
… but I'd rewrite validate so that it just used this and not the form argument.
According to answer on this post JavaScript code to stop form submission I implemented event.preventDeafault() command to prevent submission if the field is empty.
<form>
<input name="xyz">
<input type="submit" value="submit">
</form>
<script>
function validate(event)
{
if(document.forms[0].xyz.value=='')
{
alert('Mandatory field!');
event.preventDefault();
}
}
document.forms[0].addEventListener('submit',validate);
</script>

Using hidden inputs to POST JavaScript function result

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>

How can i change the PHP value in textbox through Javascript

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);
}

javascript form access

<form name = "myForm" onsubmit="foo()">
<p class = "form-text">Name</p>
<input type = "text" name="name" />
<input type = "submit" />
</form>
//javascript (external file)
function foo(){
alert(document.forms["myForm"].name.value)
}
Is there anything wrong with this code? When I press submit, it goes to a white page and nothing happens.
The desired result: alert box with value of the name field
You never specified what your desired results are, so I can only assume that you would like to see the value alerted with the form submission prevented.
If you must use inline javascript, you'll need to use return false; to prevent the form submission, although I'm sure you'd like that dependent on the result of foo(), so instead of return false you can use return foo(); which will allow you to choose whether or not to prevent the event from happening:
onsubmit="return foo()"
///JS
function foo() {
alert(...);
return false;
}
The problem with code like this is that it directly relies on the HTML calling the JS, which breaks the wonderful MVC structure of HTML CSS and JavaScript. Instead, add the event callback in the JS code:
//make sure you add an `[id]` to your form
var form = document.getElementsById('formid');
form.onsubmit = foo;
function foo() {
//do stuff
return false;
}
try this:
<form name = "myForm" onsubmit="foo();return false;">
<p class = "form-text">Name</p>
<input type = "text" name="name" />
<input type = "submit" />
</form>
//javascript
function foo(){
alert(document.forms["myForm"].name.value)
}
The problem is that you don't prevent the submission of the form. Rewrite your function to return either true or false depending on your intention (true for "send it" and false for "don't send it"). Then use onsubmit="return foo();", which will then directly influence the submission of the form depending on the return value of foo().

Categories

Resources