0

I have a variable containing a form with an input box, and I'd like to change the value attribute of said input box using jquery. So far, I'm able to change the value, but it doesn't get changed in the outer html. This' what I've got so far:

$("a").click(function(event) {
    var form_content = "<form><input id=\"name\" value=\"Test value\"/></form>";
    var test = $('<div />').html(form_content).find('#name').val('New test value').parent();
    alert(test.find('#name').val());
    alert(test.html());
    return false;
});

also available at jsfiddle. The first alert displays "New test value", yet the second alert doesn't reveal any hint of how this new value is stored - basically it returns the same value as the original variable form_content.

I've had a look here, but can't understand what I'm doing wrong.

Could anyone please help me connect the dots, and possibly give me a hint of how I can change the html stored in form_content? (There seems to be plenty of examples of how to do it in plain static html, but that's unfortunately not an option for me.) Thanks!

Community
  • 1
  • 1
conciliator
  • 6,078
  • 6
  • 41
  • 66
  • it is because the updated value is not copied to the value attribute.. it is maintained in the value property of the input element.. when you say html() it gets the inner html along with its attributes not the properties – Arun P Johny Feb 04 '14 at 09:05
  • The Attribute of an input does not change when you change the value property with .val() . The inputs value will change, but not the attr. Check this fiddle http://jsfiddle.net/tndn7/1/ – Anton Feb 04 '14 at 09:05
  • The `val` methods sets the value property, if you want to change the `value` attribute of your input tag, try `attr('val', 'new test value')`. See http://jsfiddle.net/tewathia/tndn7/3/ – tewathia Feb 04 '14 at 09:09
  • http://stackoverflow.com/questions/10346471/why-doesnt-the-value-attribute-of-the-input-change – Chirayu Chiripal Feb 04 '14 at 09:16
  • Thanks all for those helpful comments! :) – conciliator Feb 04 '14 at 10:45

3 Answers3

1
$("a").click(function(event) {
    var form_content = "<form><input id=\"name\" value=\"Test value\"/></form>";
    var test = $('<div />').html(form_content).find('#name').attr('value', 'New test value').parent();
    alert(test.find('#name').attr('value'));
    alert(test.html());
    return false;
});

Update your query, its working fine...

Sam1604
  • 1,459
  • 2
  • 16
  • 26
0

Don't use .val('new test value'), instead use .attr('value', 'new test value')

Sélim Achour
  • 718
  • 4
  • 7
0

Just put the type for you input element try

      <input type="hidden" id="name" value="Test value">
Sachin9
  • 135
  • 8