views:

1727

answers:

4

Hey,

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.

+1  A: 

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
As long as the script is loaded after the textarea, it should be fine, though your point is probably valid anyway.
altCognito
I've had issues with IE, even if the script is loaded after the HTML elements.
Philippe Leybaert
A: 

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
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
A: 

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

Philippe Leybaert
no the program consists of just the code above.
themaddhatter
ok, but the code above works in IE6. Try http://jsbin.com/ivaso (as altCognito suggested)
Philippe Leybaert
A: 

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

sasa
when i use .html() it deletes everthing from the screen and adds the code to the newly blank page
themaddhatter
with a bit of tinkering this worked,thanks!
themaddhatter