Reputation: 460
What I'm trying to achieve is to display the inputted name in text.The user is allowed to edit it by clicking the edit button. A form will replace the text and the form must have the default value of the name.
My code is able to perform the process stated. The problem is when I click the save button, the displayed text is still the old value. It doesn't update.
function edit(firstname){
document.getElementById("firstname-div").innerHTML='First Name:<input type="text" name="firstname" value="'+firstname+'">';
}
function save(firstname){
document.getElementById("firstname-div").innerHTML= 'First Name:'+firstname;
}
<div id="firstname-div">
<?php echo "First Name: $firstname<br>"; ?>
</div>
<button type="button" onclick="edit('<?php echo $firstname ?>')">edit</button><br>
<button type="button" onclick="save('<?php echo $_POST['firstname']?>')">save</button><br>
I know it has something to do with <button type="button" onclick="save('<?php echo $_POST['firstname']?>')">save</button>
. The $_POST['firstname']
value is still the same.
Any idea on how to solve this? Or other implementation in pure javascript?
Upvotes: 0
Views: 285
Reputation: 355
As you are new to web development, better try more tutorials about javascript and php to understand how do they work in client side and the server side.
Why this doesn't work?
In order to access $_POST
you must submit a http post request to the server from client side.
Answer for your question.
(Please remember here i will only display the user inputs in client side and, this will not change your database or any server side variable.)
<button type="button" onclick="save()">save</button><br>
function edit(firstname){
var firstname_old = document.getElementById("firstname-div")
//Set id="FirstName" to your input field
firstname_old.innerHTML= 'First Name:<input type="text" id="FirstName" name="firstname" value="'+ firstname +'">';
}
function save(){
var firstname_new = document.getElementById("FirstName").value
document.getElementById("firstname-div").innerHTML = firstname_new
}
Hope this will helpful to fix it without reloading your page.
Upvotes: 1