Bug Tracker

Opened 10 years ago

Closed 10 years ago

#14110 closed bug (notabug)

Setting values of elements created on the fly

Reported by: [email protected] Owned by:
Priority: undecided Milestone: None
Component: unfiled Version: 1.10.1
Keywords: Cc:
Blocked by: Blocking:

Description

When HTML objects are created on the fly, the html() function does not work properly for values which are set by the val() function.

The following code demonstrates this problem.

var result = $('<div><input type="hidden" /></div>');
$(result).find('input').val('test');
console.log($(result).html());
// Expected output: <input value="test" type="hidden">
// Output: <input value="test" type="hidden">
// THIS ONE IS CORRECT


var output = $('<div><textarea>Error</textarea></div>');
$(output).find('textarea').val('test');
console.log($(output).html());
// Expected output: <textarea>test</textarea>
// Output: <textarea>Error</textarea>

var result = $('<div><textarea></textarea></div>');
$(result).find('textarea').attr('value', 'test');
console.log($(result).html());
// Expected output: <textarea>test</textarea>
// Output: <textarea value="test"></textarea>

var result = $('<div><input type="text" /></div>');
$(result).find('input').val('test');
console.log($(result).html());
// Expected output: <input value="test" type="text">
// Output: <input type="text">

As you see, setting the value only works properly for hidden input fields. Whe you log the jQuery object itself, the correct value is set. It just does not show in the html() function.

http://jsfiddle.net/fDLsc/

Change History (1)

comment:1 Changed 10 years ago by dmethvin

Resolution: notabug
Status: newclosed

Think of it this way, generally the property represents the dynamic value of the DOM data structure in memory, and not the value as it was serialized in HTML.

Whe you log the jQuery object itself, the correct value is set. It just does not show in the html() function.

Yes, the property is the value in memory. Each browser is responsible for taking the in-memory representation of DOM objects and turning it into an HTML string. In general it uses the original attribute value although there are some exceptions. Do the same with bare DOM operations and you will get the same result, jQuery is not changing the outcome here.

Note: See TracTickets for help on using tickets.