1

I'm trying to get a textarea's value to update using jquery as outlined in the below code:

<button type="button" onclick="setLine();">Set</button>
<button type="button" onclick="showLine();">fire!</button><p></p>
    <textarea id="hello">

    </textarea>
    <script type="text/javascript">
            $('#hello').val("hi there");
        </script>
    <script type="text/javascript">
        function showLine()
        {
            alert($('#hello').val());
        }
        function setLine()
        {
            $('#hello').val('foo');
        }
    </script>

This code works fine in all major browsers except IE6.

In Ie6 the textarea will not update with the buttonclick and the alert gives a blank/null string. However in other browsers, clicking "set" changes it to "foo" which is then shown in the alert box.

Does anyone know why this is specific to this browser, or what may be wrong with the code? I have my suspicions about the .val()

Any help would be appreciated.

kyassuru
  • 163
  • 2
  • 11

4 Answers4

1

you should call val() inside the document.ready event:

$(document).ready(function() {

    $('#hello').val("hi there");

});

Just to make things clear: I'm only talking about the first (global) call to val(). The function declarations shouldn't be inside the document.ready function.

Philippe Leybaert
  • 168,566
  • 31
  • 210
  • 223
0

I don't know why you're code is not working in IE6 but its not proper jQuery. I can't test this right now but this should work with some changes:

<button type="button" id="setline">Set</button>
<button type="button" id="showline">fire!</button>

<textarea id="hello"></textarea>

<script type="text/javascript">
    $(document).ready(function(){
       $('#hello').val("hi there");

       $('#showline').click(function()
       {
           alert($('#hello').val());
       });

       $('#setline').click(function()
       {
           $('#hello').val('foo');
       });
   });

Buttons should not have onclick events in jQuery you should bind them like shown above. And always use document.ready!

MrHus
  • 32,888
  • 6
  • 31
  • 31
  • There's nothing wrong with having onclick attributes, even when using jQuery. Of course, it's better to use jQuery's event handling, but the "old" style isn't necessarily wrong. – Philippe Leybaert Jun 05 '09 at 13:05
0

Do you by any change have more than one element with id "hello" ?

Philippe Leybaert
  • 168,566
  • 31
  • 210
  • 223
0

I think that you must use .html() instead of .val() ... Try and say what is happened?

sasa
  • 2,443
  • 5
  • 23
  • 35
  • when i use .html() it deletes everthing from the screen and adds the code to the newly blank page – kyassuru Jun 08 '09 at 08:09
  • 4
    I wish that you would have explained in detail what you fiddled with to get it to work. I'm having a similar issue. –  Feb 23 '11 at 07:52