简体   繁体   中英

jquery-problem using val() in IE6

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.

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.

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!

通过任何更改,您是否具有一个ID为“ hello”的元素?

我认为您必须使用.html()而不是.val()...试着说发生了什么?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM