Josh
Josh

Reputation: 13818

Append text into a div with Jquery

I've tried the following code in my sample page and it doesn't work.All I'm trying to do is just append some text into a div on the page when the button is clicked.

<asp:Content ID="BodyContent" runat="server" ContentPlaceHolderID="MainContent">
    <script type="text/jscript">
        $(document).ready(function () {
            $('#Button1').click(function () {
                $('#testdiv').append("Hello World!!");
            });

        });

    </script>
    <input id="Button1" type="button" value="button" />
    <div id="testdiv"> 
    adiv
    </div>
</asp:Content>

Please guide me on how to get this simple thing to work in jquery...

Thanks

Edit:I updated my code as you suggested...still doesn't work...please help me...Thanks

Upvotes: 1

Views: 3949

Answers (4)

user538315
user538315

Reputation: 11

Ok from my tests I have found out that adding straight text to a div does not work.

for example: I will use appendTo() but it should be the same result.

My UI looks like this:

<body>
  <form>
      <div>

        <input id="Button1" value="Click Me!" type="button" onclick="OnBtnClick()" /> <br />
        <div id="showMeTheMoneyText"></div>
    </div>
   </form>
<body>

Inside my script:

function OnBtnClick() {

    $('Hello World!').appendTo('#showMeTheMoneyText');

    return false;
};

This does absolutely nothing in the UI. Why? Because you will need to wrap your text inside some HTML tag that contains the text you wish to display (i.e.

, etc)

Look at my updated example:

function OnBtnClick() {

    $('<span>Hello World!</span>').appendTo('#showMeTheMoneyText');

    return false;
};

Works like a charm!

Upvotes: 1

Corey Ballou
Corey Ballou

Reputation: 43467

Try fixing your script declaration from

<script type="text/jscript">

to

<script type="text/javascript">

as some browsers are finicky.

Upvotes: 3

Andrea Zilio
Andrea Zilio

Reputation: 4534

You must use $('#Button1').click and not $('#Button1').ready

Upvotes: 0

SLaks
SLaks

Reputation: 887449

You're adding a handler to the button's ready event inside of the document's ready event. Since the button is already ready by the time you add the handler, nothing happens.

You need to add a handler to the button's click event, like this:

$('#Button1').click(function () {
    $('#testdiv').append("Hello World!!");
});

Upvotes: 1

Related Questions