1

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(){
        $('input[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>

1 Answer 1

2

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">"
});
Sign up to request clarification or add additional context in comments.

4 Comments

@user443095 - it depends on the browser as to exactly what's rendered, but think of it this way, HTML is what the browser uses to create the DOM, after that they're not as strongly (1:1) connected as many thing, the DOM can be manipulated in many ways you won't see in the html output.
ok so DOM and HTML isn't same. but I don't understand this, if I had used <input type="hidden"> this would have resulted with modified value attribute in html as well as dom. now why this works for hidden type but not text type ??
@Nikc, i see ok.. thanx a lot Nick, helped a lot
@user443095 - It just depends on the browser, some will show an updated value for both...this behavior isn't explicitly specified, so it's implementation (browser) dependent.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.