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.

6
  • 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
    Jan 25, 2016 at 22:20
  • 1
    @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.
    – Quentin
    Jan 25, 2016 at 22:21
  • You should use ajax in this case.
    – abeyaz
    Jan 25, 2016 at 22:44
  • 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
    Jan 25, 2016 at 22:50
  • @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.
    – Quentin
    Jan 25, 2016 at 22:51

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.