tags:

views:

509

answers:

2

I didn't expect it but the following test fails on the cloned value check:

test("clone should retain values of select", function() {
    var select = $("<select>").append($("<option>")
                              .val("1"))
                              .append($("<option>")
                              .val("2"));
    $(select).val("2");
    equals($(select).find("option:selected").val(), "2", "expect 2");
    var clone = $(select).clone();
    equals($(clone).find("option:selected").val(), "2", "expect 2");
});

Is this right?

A: 

Yes. This is because the 'selected' property of a 'select' DOM node differs from the 'selected' attribute of the options. jQuery does not modify the options' attributes in any way.

Try this instead:

$('option', select).get(1).setAttribute('selected', 'selected');
//    starting from 0   ^

If you're really interested in how the val function works, you may want to examine

alert($.fn.val)
Pumbaa80
If I use the val() on the select object the test fails as well: test("clone should retain values of select", function() { var select = $("<select>").append($("<option>").val("1")).append($("<option>").val("2")); $(select).val("2"); equals($(select).val(), "2", "expect 2"); var cl
chief7
That's pretty weird, cause this works for me in IE 6/7, Firefox 3 and Opera 9. Maybe something wrong with your 'equals' function?alert(eval(' select = $("<select>").append($("<option>").val("1")).append($("<option>").val("2"));$(select).val("2"); $(select).val() '));
Pumbaa80
+3  A: 

After further research I found this ticket in the JQuery bug tracker system which explains the bug and provides a work around. Apparently, it is too expensive to clone the select values so they won't fix it.

http://dev.jquery.com/ticket/1294

My use of the clone method was in a generic method where anything might be cloned so I'm not sure when or if there will be a select to set the value on. So I added the following:

 var selects = $(cloneSourceId).find("select");
 $(selects).each(function(i) {
  var select = this;
  $(clone).find("select").eq(i).val($(select).val());
 });
chief7