jquery-problem using val() in IE6

风格不统一 提交于 2019-12-11 09:29:27

问题


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:


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




回答2:


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.




回答3:


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!




回答4:


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



来源:https://stackoverflow.com/questions/955630/jquery-problem-using-val-in-ie6

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!