0

I want to make a few simple buttons that toggle color each time they are pressed. With a button press also some unique string needs to be passed to the server. Therefore on every button press I run two functions. My problem is that when I run this script, button changes color to red only for the period after the alert message Msg1 is displayed. When I answer OK to the Msg2, the color of the button reverts back to green. What am I doing wrong here?

<style>
.button { background-color: green; }
.buttonOn { background-color: red; }
</style>

<button id="r1" class="button" onclick="mF1(id)">Relay 1</button>

<script>

function mF1(btn) {
var property = document.getElementById(btn);
alert('Msg1: This is ' + property.className);
if (property.className == 'button')     
    { property.className = 'buttonOn' }
else 
    { property.className = 'button';  }
alert('Msg2: This is ' + property.className);
mF2(btn);            
}

function mF2(id) { window.location.href='?HVAC-' + id; }

</script>

1 Answer 1

2

You are using JavaScript to change the DOM.

Then you are setting location.href to a new value.

This causes a new page to load.

The new page does not have the modifications you made to the DOM.


You would need to write code that examines the query string when the page loads and sets the appropriate classes.

Sign up to request clarification or add additional context in comments.

6 Comments

I only need to pass a parameter "HVAC.." to the server. No need to load any page. I thought "?" in the href string denotes that this is an HTTP query string, not a new page to load?
@ggv — A query string is part of a URL. Changing the query string changes the URL. Setting location.href to a different URL (unless you are only modifying the fragment identifier … which is never sent to the server) loads a new page.
You should use ajax in this case.
Quentin - Maybe this is stupid question, but I am trying to understand - do you mean that I have to send a query string to the server and the server then paints my button red if appropriate string is received? I can not do it in javascript on the client's machine?
@ggv — You can set it to red on the current screen. You've proven that. You can see it change colour. If you then replace the page with a new one then you've replaced the page that you turned the button red on. See also Ajax.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.