开发者

jquery attribute manipulation(DOM manipulation) for input type text not working?

in javascript below, variable temp would hold html string like this,

<input type="text" value="initial text" name="msg" />

why this code

$('input[name=msg]').val('hello world');

won't change html string to

<input type="text" value="hello world" name="msg" />    

here is the code,

<html>
<head>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js"></script>
</head>
<body>
<form><input type="text" value="initial text" name="msg" /></form>

<script type="text/javascript">
    $().ready(function(){
        $('i开发者_如何学运维nput[name=msg]').val('hello world');

        var temp = $('form').html();

        console.debug(temp);        
    });
</script>
</body>
</html>

updated

<form>
    <input type="hidden" value="foo" name="msg1" />
    <input type="text" value="bar" name="msg2" />
</form>

<script type="text/javascript">
    $(function(){
        $('input[name=msg1]').val('hello world 1'); // this manipulates dom at html level
        $('input[name=msg2]').val('hello world 2'); // this does not! why?

        $('form').html();
    });
</script>


An element's HTML isn't the same as what its DOM properties are, that's just how it is. Though your .ready() style is deprecated, it's not the issue. If you do this, you'll see the correct value:

console.debug($('input[name=msg]').val()); //"hello world"
console.debug($('form').serialize()); //"msg=hello+world"

You can test it here:

$(function() {
  $('input[name=msg]').val('hello world');
  var temp = $('form').html();

  console.debug($('input[name=msg]').val()); //"hello world"
  console.debug($('form').serialize());      //"msg=hello+world"
  console.debug(temp);                       //"<input type="text" value="initial text" name="msg">"
});
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜