2

I have this js code to add (clone) and delete an element.

$('#btnAdd1').click(function (event) {
    var num = $('.linguas').length;
    var newNum = new Number(num + 1);

    var newElem = $('#input_' + num).clone(false).prop('id', 'input_' + newNum);

    newElem.children(':text').val('');

    $('#input_' + num).after(newElem).find('#input_' + num +'> option:selected').removeAttr("selected");
    $('#btnDel1').prop('disabled', '');
    if (newNum == 4) $('#btnAdd1').prop('disabled', 'disabled');
});

However, i want to remove the select="select" attribute, cloned from previous element.

I am trying something like this, but didn't work:

 $('#input_' + num).after(newElem).find('#input_' + num +'> option:selected').removeAttr("selected");

demo here

thanks

Daniel
  • 578
  • 1
  • 8
  • 22

1 Answers1

5

Try this alone:

$('option:selected', newElem).prop("selected", false);

Your code:

$('#input_' + num).after(newElem).find('#input_' + num +'> option:selected').removeAttr("selected");

put the cloned select after the original, but then you searched for selected options using find on your original select. find searches children. The cloned select is now a sibling of the original not a child.

Adam Rackis
  • 81,646
  • 52
  • 262
  • 388
  • 1
    @Daniel Use `.removeProp()` instead of `.removeAttr()` if you're using a version of jQuery >= 1.6. – JesseBuesking Dec 20 '11 at 16:29
  • 2
    @JesseB - are you sure? This is from the removeProp docs `Note: Do not use this method to remove native properties such as checked, disabled, or selected. This will remove the property completely and, once removed, cannot be added again to element. Use .prop() to set these properties to false instead.` – Adam Rackis Dec 20 '11 at 16:32
  • 1
    @JesseB: You definitely won't want to do that. [See the docs](http://api.jquery.com/removeProp/) for the reason why. Instead you should do `.prop('selected',false)`. ...er, like Adam said above. :) –  Dec 20 '11 at 16:32
  • @ЖΞЖΞЖΞЖΞЖΞЖΞЖΞЖΞЖΞЖΞЖΞЖΞЖΞЖΞЖ - thanks for that comment - +1 - I definitely learned something there, and updated my answer :) – Adam Rackis Dec 20 '11 at 16:37
  • @AdamRackis Whoops my bad. You guys are right ;p – JesseBuesking Dec 20 '11 at 17:12