0
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
<script src="http://ajax.googleapis.com/ajax/lib…
</script>
<script type="text/javascript">
$(document).ready(function () {


    $("button").click(function () {


$("p").css("background-color", "yellow");
});
});
</script>
</head>
<body>
<form id="form1" runat="server">

<h2>This is a heading</h2>
<p style="background-color:#ff0000">This is a paragraph.</p>
<p style="background-color:#00ff00">This is a paragraph.</p>
<p style="background-color:#0000ff">This is a paragraph.</p>
<button>Return background-color of p</button>
</form>
</body>
</html>

** I wrote this code to change color of <p> elements to yellow by jQuery. This code runs fine when I remove the form tag. But with form tag(this code) <p> element change color to yellow and instantly change back to the previous color. What's the reason for that.?

2
Contributors
2
Replies
10
Views
3 Years
Discussion Span
Last Post by kazp
0

This is because your button is within the form and it is causing a postback. When the page reloads the element returns back to its color. Your server side code has no knowledge that you changed the color because that happened client side.

If you don't want the postback you can change your code to this....

 $("button").click(function (event) {
      event.preventDefault();
      $("p").css("background-color", "yellow");
 });

Edited by JorgeM

This question has already been answered. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.