How can i change the PHP value in textbox through Javascript - 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);
}

Related

Use changed values in other page

I have a textfield:
Voornaam: <h3 class="title1">Kevin</h3>
<input type="text" id="myTextField1" />
<input type="submit" id="byBtn" value="Change" onclick="change1()"/><br/>
I can set a value of this using this function:
function change1(){
var myNewTitle = document.getElementById('myTextField1').value;
if( myNewTitle.length==0 ){
alert('Write Some real Text please.');
return;
}
var titles = document.getElementsByClassName('title1');
Array.prototype.forEach.call(titles,title => {
title.innerHTML = myNewTitle;
});
}
Now in my other page, I want to use the value. I know I can for example pass a value from one page to another like this:
<a href='convert.php?var=data'>converteren.</a>
And then for example show it by doing this in the other page:
echo $_GET['var'];
But I cant really seem to figure out how to use the value which I've set using my textfield.
So my goal for now is to display the value I've set using my textfield in the other page using the method I just described.
Basically all I want to happen is for my textfield to change the value inside here aswell:
<a href='convert.php?var=data'>converteren.</a>
So where data is the value, I want it to become what I've put in the textfield.
Could anybody provide me with an example?
I've altered a bit your javascript code to make the link as you want.
To explain the answer, i've added document.getElementById("myLink").href="convert.php?var=" + myNewTitle ; which updates your a href while your function runs and is not empty.
function change1(){
var myNewTitle = document.getElementById('myTextField1').value;
if( myNewTitle.length==0 ){
alert('Write Some real Text please.');
return;
}
document.getElementById("myLink").href="convert.php?var=" + myNewTitle ;
var titles = document.getElementsByClassName('title1');
Array.prototype.forEach.call(titles,title => {
title.innerHTML = myNewTitle;
});
}
<a id="myLink" href='#'>converteren.</a>
Wrap your inputs inside a form element.
In the action attribute, specify the destination url.
In the method attribute, choose between GET and POST.
For example:
<form method="GET" action="convert.php">
<input type="text" id="myTextField1" />
<input type="submit" id="byBtn" value="Change" onclick="change1()"/>
</form>
Clicking the submit button will call "convert.php?myTextField1={value}".

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>

Using result of javascript query as input for HTML 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();
}

HTML text input conditional submit

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.

onsubmit Javascript popup to use value from submitted form syntax

I'm trying to make a little JScript popup that displays information from the form for confirmation. Here is what it looks like right now:
<input type="submit" value="Accept" onclick="return confirm('Press OK to confirm your purchase of' document.form.field.value)" />
The idea is to return a more useful confirmation than just 'Click OK to confirm' by showing values of the submitted form in the popup. Can anyone help me with the syntax?'
You can use the following:
<input type="submit" value="Accept" onclick="return confirm('Press OK to confirm your purchase of ' + document.getElementById('FIELDID').value)" />
Or you could modify the above to loop through each product and build a dynamic string with each product on a new line like this:
<input type="submit" value="Accept" onclick="return ConfirmOrder(); />
function ConfirmOrder()
{
var msg = 'Click OK to confirm your order of\n';
var prds = '';
var prdElements = <GET PRODUCT ELEMENTS HERE>
for (i=0; i<numPrds; i++)
{
prds = prdElements[i].value + '\n';
}
return confirm(msg + prds);
}
Also I think the onclick event should be in the onsubmit event of the form.

Categories

Resources