0

I want to learn jQuery but I can't figure out why my page keeps refreshing right after the on-click event is done.

The goal with this code is to change the background of DivResult. This works for a split seconds before the page is refreshed. I tried it on different browsers and different computers so i think it's something with my code.

This is my jQuery code:

$(document).ready(function(){
    $('#button').on('click',function(){
        var kleur = "#" +$('#text').val();
        $('#DivResult').css({'background-color': kleur});
    });
});

and this is my html file:

<!DOCTYPE html>
<html>
<head lang="en">
    <meta charset="UTF-8">
    <script src="jQuery_JavaScript_Library_v1.11.3.js"></script>
    <script src="script.js"></script>

    <link href="style.css" rel="stylesheet">

    <title></title>
</head>
<body>
    <form>
        <input type="text" id="text">
        <button id="button">button</button>
    </form>
    <div id="DivResult">&nbsp;</div>
</body>
</html>

Many thanks in advance!

Rory McCrossan
  • 331,213
  • 40
  • 305
  • 339
  • 1
    this is the 1000000th duplicate of http://stackoverflow.com/q/18575623/1845408, still people post answer quickly just to get reputation points. – renakre May 15 '15 at 14:03
  • That question is regarding the click of an `a` element, not the submission of a `form` as in this case. – Rory McCrossan May 15 '15 at 14:09

2 Answers2

1

It's because the default value for the type attribute of button elements is "submit".

source : Can I make a <button> not submit a form?

Solution :

   <form>
        <input type="text" id="text">
        <button type="button" id="button">button</button>
    </form>
Community
  • 1
  • 1
fozzeuh
  • 41
  • 6
0

The issue is because the button click is submitting the form which makes the page appear to refresh. To solve this issue you should hook to the submit event of the form and use preventDefault() to stop the form submission. Try this:

$('form').on('submit', function(e) {
    e.preventDefault();
    var kleur = "#" + $('#text').val();
    $('#DivResult').css({ 'background-color': kleur });
});
Rory McCrossan
  • 331,213
  • 40
  • 305
  • 339