Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to change the select option text permanently using javascript

I am having a following select option code

<select id="test" onchange="changeContent()">
<option>1</option>
<option>2</option>
<option>3</option>
</select>

The javascript code is

function changeContent()
{
    document.getElementById('test').options[0].text = 'ONE';
}

Now it changing my option value when am i refresh the page it again came back to older one how can i change the option value permanently like.

<select id="test" onchange="changeContent()">
<option>ONE</option>
<option>2</option>
<option>3</option>
</select>
like image 588
Aravin Avatar asked Dec 02 '25 09:12

Aravin


2 Answers

I supose from your comments you are using a php file where the <select> is. Lets call it file.php

In the file.php you can have something like this: (I did not test this but I think it's a good start for what you need)

<?php
session_start();
$value1 = 1; $value2 = 2; $value3 = 3;
$_SESSION["value1"] = 1;$_SESSION["value2"] = 2;$_SESSION["value3"] = 3;
if ($_POST['value'] == 1) {$_SESSION["value1"] = 'One';}
if ($_POST['value'] == 2) {$_SESSION["value2"] = 'Two';}
if ($_POST['value'] == 3) {$_SESSION["value3"] = 'Three';}
?>


<select id="test" onchange="changeContent()">
<option value="1"><?php echo $_SESSION["value1"]; ?></option>
<option value="2"><?php echo $_SESSION["value2"]; ?></option>
<option value="3"><?php echo $_SESSION["value3"]; ?></option>
</select>


<script type="text/javascript">
window.onload = function() {
function changeContent(){
var e = document.getElementById("test");
var newval = e.options[e.selectedIndex].value;
xmlhttp.open("POST","file.php",true);
xmlhttp.send("value="+newval);
}
};
</script>

This will just make it available after a refresh, if you want to store it to a database, it's a bit different. Then we need more info/code from what you have.

like image 179
Sergio Avatar answered Dec 04 '25 00:12

Sergio


you CANNOT change the value using javascript and expect it to be permanent. You may want to send a ajax request on change and render next time with the changed value


Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!