0

I have a page on which a list of properties is displayed (i.e houses). This list is made up using CSS. So I've built a second CSS class, which makes the properties/houses align properly in 2 columns. Until now I did this by pressing a button, posting back, and outputting different html (basicly the same, but with other Css class references).

Now I found this question on SO and I implemented a basic scenario. A div with the class "yellow" is written to the html page, and a button changes this class to "red". This happens, but the div immediately changes back to class "yellow".

I'm a very very beginner in JS but not a beginning programmer. This would be a great addition to my site, but I can't find a proper answer. I apologize if this question is redundant.

<script type="text/javascript">
    function changeView() {
        document.getElementById("box").className = " red";
    }

Grtz, thanks in advance, Christophe,

Community
  • 1
  • 1
Christophe De Troyer
  • 2,852
  • 3
  • 30
  • 47

2 Answers2

3

By default a button element is of type 'submit' - which will cause your browser to post back to the server.

Try changing the type to button instead.

<input type="button" ....

More info on the difference here... Difference between <input type='button' /> and <input type='submit' />

Community
  • 1
  • 1
isNaN1247
  • 17,793
  • 12
  • 71
  • 118
1

If your button causes a postback (possibly a server control with an asp: tag), the javascript changes you made will be lost as by default an asp button submits a page to the server as a result of which your page reloads.

If all you need to change the class of a div make it a simple html button like

<input type="button" onclick="changeView()" value="Change" />
mshsayem
  • 17,557
  • 11
  • 61
  • 69