help with javascript and text area
Hey my text from textarea is not showing in my div area within my contentplaceholder.
Could any one advice whats going wrong with my javascript?
<asp:Content ID="Content1" ContentPlaceH开发者_JS百科olderID="head" Runat="Server">
<link href="css/Style.css" rel="stylesheet" type="text/css" />
</asp:Content>
<asp:Content ID="Content2" ContentPlaceHolderID="ContentPlaceHolder2" Runat="Server">
<script src="http://ajax.aspnetcdn.com/ajax/jQuery/jquery-1.5.1.min.js" type="text/javascript"></script>
<script type="text/javascript">
$('button').click(function () {
var x = $('textarea').val();
$('div').html(x);
});
</script>
<textarea style="border: 0" cols="77" rows="5"></textarea>
<button>Post Message</button>
<div></div>
</asp:Content>
The button isn't in the DOM yet when your script runs.
<script type="text/javascript">
$(function() {
$('button').click(function () {
var x = $('textarea').val();
$('div').html(x);
});
});
</script>
That'll tell jQuery to hold on to that initialization function until the DOM is ready. When that's the case, your function will be called.
Optionally, you could move your script block to the end of the <body>
, but that'd be somewhat déclassé.
The story is that scripts are run as soon as the browser has seen the whole <script>
element. When you put the script at the top like that, there aren't any <button>
elements yet because the browser hasn't made it that far through the document.
To elaborate on Pointy's answer, move your script beneath the
</div>
or wrap your code in an init() function that you call from the body tag via an onload as in...
<script>
function whateverIwantToHappenWhenTheDomLoads(){
//put your code here
}
</script>
<body onload="whateverIwantToHappenWhenTheDomLoads()">
...
精彩评论