andy
andy

Reputation: 97

i want to change button color and text onclick and it should not change when page is refreshed

i want to change button colour and text on on click and it should not change when page is refreshed.Here when set status is clicked it changes the text to confirmed and colour changes to green,when i again click on it,it changes the colour to red and text changes to pending.Now when i again click on it,it should change the colour to green and text should change to confirmed,here neither the color changes nor the text is changed.And this should stay when page is refreshed. here is the code:

<input type="submit" id="<?php echo $orderQuery['id'];?>" value="set status" onclick="setColor('<?php echo $orderQuery['id'];?>')"; />
<script>

var count = 1;

function setColor(btn) {
var property = document.getElementById(btn);

if (count == 0) {property.style.backgroundColor = "#ff0000"
 if (property.value=="confirmed") property.value = "pending";
 }
 else {property.style.backgroundColor = "#7FFF00"
 count = 0;
if (property.value=="set status") property.value = "confirmed";
}

    }
</script>

Upvotes: 0

Views: 896

Answers (1)

siddhesh
siddhesh

Reputation: 598

HTTP is Stateless Protocol we cannot maintain the state between HTTP Calls for more info look at this answer

So you have to save the data that you need next time (In your case button color) by other mechanism like Query Strings,Cookies or Sessions

QUERY STRINGS

you can use query string to carry the information that you want to preserve like

www.example.com?btnColor=blue

and ofcourse at the page loading you can set the color with php something like this.

//pseudo code
if(isset($_GET['btnColor']) // for query string
 echo  '<button style="background:'.$_GET['btnColor'].'">'
if(isset($_COOKIE['btnColor']) // for cookie
 echo  '<button style="background:'.$_COOKIE['btnColor'].'">'
if(isset($_SESSION['btnColor']) // for Session based storage
 echo  '<button style="background:'.$_SESSION['btnColor'].'">'

COOKIES & SESSIONS

you can also use the cookies to save your btn color

setcookie("color", "red", time() + (86400 * 30), "/"); // 86400 = 1 day
// and you can retrieve the cookie value from


 echo $_COOKIE['color'] // prints red

The sessions can be used in following way

//to set the session
$_SESSION['color'] = "red";
// to retrive the data
echo $_SESSION['color'];

The major advantage of cookie and sessions are they save the information over a period For more information and detailed information please look at php.net documentation.

Upvotes: 1

Related Questions