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!

5
  • 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 Commented Feb 4, 2014 at 9: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 jsfiddle.net/tndn7/1 Commented Feb 4, 2014 at 9: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 jsfiddle.net/tewathia/tndn7/3 Commented Feb 4, 2014 at 9:09
  • stackoverflow.com/questions/10346471/… Commented Feb 4, 2014 at 9:16
  • Thanks all for those helpful comments! :) Commented Feb 4, 2014 at 10:45

3 Answers 3

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...

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks @Sam1604 for the most complete solution.
0

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

Comments

0

Just put the type for you input element try

      <input type="hidden" id="name" value="Test value">

Comments

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.