-1

I have inputs created dynamically by jQuery, I set init value to it, and I want it keeps that value as default value (will show again after resetting form). I searched around, but cannot find the solution.

To make it clear, after someone rate down my question, the default value here is not the value stored in placeholder (will disappear when the input get focused), it's the true, editable text!

I found solution! when resetting form, web browser will take the text in "value" attribute of inputs and display it again as default text. So, if we create a new input element, we must give it "value" attribute. In jQuery, instead of using method val() which only temporary changes the viewable value of element but not overwrite value attribute of input, we should use method attr('value', newValue)

Hieu Vo
  • 3,105
  • 30
  • 31
  • my current solution is instead of resetting, I have to remove and create it again (with init value) and insert it to where it is – Hieu Vo Feb 06 '13 at 08:17
  • Refer this http://stackoverflow.com/questions/8937113/setting-an-html-text-input-boxs-default-value-the-value-it-reverts-to-when-c – Renjith JR Feb 06 '13 at 08:19
  • @RenjithJR: the answer in your link prefers placeholder attribute (not what I want), the other answer use javascript to store the value and set it again (meaningless to me) – Hieu Vo Feb 06 '13 at 08:22

1 Answers1

1

You could try setting the value in the element as it is created. JSFiddle: http://jsfiddle.net/turiyag/UG7uw/6/

$("form").append('<input type="text" value="456" />');
$(":button").click(function(){
    $("form").reset();
});

EDIT:

Seeing your code, I think you need to look closer at how to attach events to elements. This example illustrates how to run Javascript code that runs on the "click" event. Note how the Javascript for the page is in the Javascript box in JSFiddle. http://jsfiddle.net/turiyag/uUCGV/8/

Also, for "empty elements" they should be closed with a "/>" at the end of the tag. For example:

<input type="text" value="foo" />

I would avoid the use of clone on elements that have an "id" assigned to them. clone() will also copy the id attribute, and the initial value attribute. Creating new elements is much cleaner.

Further, the '$' symbol can usually be used in the place of 'jQuery' in your code. It makes for a lot less typing.

The code in the example will set the initial values to "Input #1", "Input #2", etc. The reset button will reset the form to these values.

event.preventDefault() prevents the default action of form submission from the element being clicked.

Does this answer things?

turiyag
  • 2,757
  • 2
  • 22
  • 21