Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jquery html disappears on click event

Tags:

jquery

Please see the following code:

<body>
<form id="form1" runat="server">
<div>

    <button id="helloButton">
        Search</button>
    <div id="hello">


    </div>
    <script type="text/javascript">
        $(document).ready(
        function () {

            $('#helloButton').click(function () {


                $('#hello').html('<div>hello world</div>');

            });

        });
    </script>
</div>
</form>

When I use this script, all it does is flash "hello world", it doesn't keep it on the page. Does this has something to do with the click event? I'm trying to click the button and then leave the object on the page.

like image 365
locoboy Avatar asked Jan 18 '11 05:01

locoboy


2 Answers

in order to prevent the form from posting, so that you can see your changes, you need to call preventDefault()

$('#helloButton').click(function (e) {
    e.preventDefault();
    $('#hello').html('<div>hello world</div>');
});
like image 65
Omer Bokhari Avatar answered Nov 15 '22 08:11

Omer Bokhari


Otherwise you can simply do a return false which will do both preventDefault and stop propagation

$('#helloButton').click(function (e) {

    $('#hello').html('<div>hello world</div>');
    return false;
});
like image 26
kobe Avatar answered Nov 15 '22 08:11

kobe