복붙노트

[JQUERY] 클론 선택 값을 복제하지 않습니다

JQUERY

클론 선택 값을 복제하지 않습니다

해결법


  1. 1.추가 연구 후에 나는 버그를 설명하고 작업 주위를 제공하는 JQuery와 버그 추적 시스템에서이 티켓을 발견했다. 분명히, 그들이 그것을 해결하지 않도록 선택 값을 복제 너무 비싸다.

    추가 연구 후에 나는 버그를 설명하고 작업 주위를 제공하는 JQuery와 버그 추적 시스템에서이 티켓을 발견했다. 분명히, 그들이 그것을 해결하지 않도록 선택 값을 복제 너무 비싸다.

    https://bugs.jquery.com/ticket/1294

    clone 메소드의 내 사용은 아무것도가 확실 할 때 나에 값을 설정하는 선택이 될 것입니다 경우 모르겠어요 때문에 복제 할 수있는 일반적인 방법이었다. 그래서 나는 다음을 추가 :

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

  2. 2.여기에 jQuery를위한 복제 방법의 고정 된 버전입니다 :

    여기에 jQuery를위한 복제 방법의 고정 된 버전입니다 :

    https://github.com/spencertipping/jquery.fix.clone

    // Textarea and select clone() bug workaround | Spencer Tipping
    // Licensed under the terms of the MIT source code license
    
    // Motivation.
    // jQuery's clone() method works in most cases, but it fails to copy the value of textareas and select elements. This patch replaces jQuery's clone() method with a wrapper that fills in the
    // values after the fact.
    
    // An interesting error case submitted by Piotr Przybył: If two <select> options had the same value, the clone() method would select the wrong one in the cloned box. The fix, suggested by Piotr
    // and implemented here, is to use the selectedIndex property on the <select> box itself rather than relying on jQuery's value-based val().
    
    (function (original) {
      jQuery.fn.clone = function () {
        var result           = original.apply(this, arguments),
            my_textareas     = this.find('textarea').add(this.filter('textarea')),
            result_textareas = result.find('textarea').add(result.filter('textarea')),
            my_selects       = this.find('select').add(this.filter('select')),
            result_selects   = result.find('select').add(result.filter('select'));
    
        for (var i = 0, l = my_textareas.length; i < l; ++i) $(result_textareas[i]).val($(my_textareas[i]).val());
        for (var i = 0, l = my_selects.length;   i < l; ++i) result_selects[i].selectedIndex = my_selects[i].selectedIndex;
    
        return result;
      };
    }) (jQuery.fn.clone);
    

  3. 3.chief7의 대답 밖으로 플러그인 제작 :

    chief7의 대답 밖으로 플러그인 제작 :

    (function($,undefined) {
        $.fn.cloneSelects = function(withDataAndEvents, deepWithDataAndEvents) {
            var $clone = this.clone(withDataAndEvents, deepWithDataAndEvents);
            var $origSelects = $('select', this);
            var $clonedSelects = $('select', $clone);
            $origSelects.each(function(i) {
                $clonedSelects.eq(i).val($(this).val());
            });
            return $clone;
        }
    })(jQuery);
    

    만 간단히 테스트,하지만 작동하는 것 같다.


  4. 4.나의 접근 방식은 약간의 다릅니다.

    나의 접근 방식은 약간의 다릅니다.

    대신 복제 중 선택을 수정하는 값이된다, 그래서 내가 선택한 <옵션>에 필요한 선택 속성을 추가 <옵션이 선택 = "선택"> 변경되면, 난 그냥, 다음 모든 변화 이벤트 페이지에서 선택 시청하고 있어요. 선택은 이제 <옵션>에 표시된대로 ()를 .clone거야 때의 마크 업, 그것은 전달됩니다.

    유일한 코드이 필요합니다

    //when ANY select on page changes its value
    $(document).on("change", "select", function(){
        var val = $(this).val(); //get new value
        //find selected option
        $("option", this).removeAttr("selected").filter(function(){
            return $(this).attr("value") == val;
        }).first().attr("selected", "selected"); //add selected attribute to selected option
    });
    

    그리고 지금, 당신은 당신이 원하는 방식을 선택하여 복사 할 수 있으며 그것의 값이 너무 복사해야합니다.

    $("#my-select").clone(); //will have selected value copied
    

    나는이 솔루션은 나중에 뭔가를 수정하는 것입니다 경우 코드가 침입 할 경우 걱정할 필요가 없습니다 덜 정의라고 생각합니다.

    이 페이지에서 선택은 모든에 적용하지 않으려면, 당신은 같은 첫 번째 줄에 선택을 변경할 수 있습니다 :

    $(document).on("change", "select.select-to-watch", function(){
    

  5. 5.chief7의 대답의 단순화 :

    chief7의 대답의 단순화 :

    var cloned_form = original_form.clone()
    original_form.find('select').each(function(i) {
        cloned_form.find('select').eq(i).val($(this).val())
    })
    

    다시 말하지만, 여기에 jQuery를 표는 다음과 같습니다 http://bugs.jquery.com/ticket/1294


  6. 6.예. 이 때문에 옵션의 '선택'속성에서 '선택'DOM 노드 다릅니다의 '선택'속성. jQuery를 어떤 방법으로 옵션 '속성을 수정하지 않습니다.

    예. 이 때문에 옵션의 '선택'속성에서 '선택'DOM 노드 다릅니다의 '선택'속성. jQuery를 어떤 방법으로 옵션 '속성을 수정하지 않습니다.

    대신이 시도 :

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

    당신이 어떻게 발 기능의 작동에 정말 관심이 있다면, 당신은 검사 할 수 있습니다

    alert($.fn.val)
    

  7. 7.A는 <선택> 복제 <옵션>에 값 = 속성을 복사하지 않습니다에요. 마크 플러그인은 모든 경우에 작동하지 않습니다 그래서.

    A는 <선택> 복제 <옵션>에 값 = 속성을 복사하지 않습니다에요. 마크 플러그인은 모든 경우에 작동하지 않습니다 그래서.

    해결하려면 <선택> 값을 복제하기 전에이 작업을 수행 :

    var $origOpts = $('option', this);
    var $clonedOpts = $('option', $clone);
    $origOpts.each(function(i) {
       $clonedOpts.eq(i).val($(this).val());
    });
    

    <선택> 복제에 대한 다른 방법이 옵션은 jQuery를 1.6.1 +에서, 선택 ...

    // instead of:
    $clonedSelects.eq(i).val($(this).val());
    
    // use this:
    $clonedSelects.eq(i).prop('selectedIndex', $(this).prop('selectedIndex'));
    

    후자는 selectedIndex의를 설정 한 후 <옵션> 값을 설정할 수 있습니다.


  8. 8.

    $(document).on("change", "select", function(){
        original = $("#original");
        clone = $(original.clone());
        clone.find("select").val(original.find("select").val());
    
    });
    

  9. 9.당신은 단지 선택의 값이 필요한 경우, 형태 또는 같은, 나를 위해이 작품을 직렬화 :

    당신은 단지 선택의 값이 필요한 경우, 형태 또는 같은, 나를 위해이 작품을 직렬화 :

    $clonedForm.find('theselect').val($origForm.find('theselect').val());
    

  10. 10.작동하지 않았다 다른 솔루션을 시도 1 시간 후, 나는이 간단한 해결책을 창조 하셨 는가

    작동하지 않았다 다른 솔루션을 시도 1 시간 후, 나는이 간단한 해결책을 창조 하셨 는가

    $clonedItem.find('select option').removeAttr('selected');
    $clonedItem.find('select option[value="' + $originaItem.find('select').val() + '"]').attr('selected', 'true');
    

  11. 11.@ pie6k 좋은 아이디어를 보여줍니다.

    @ pie6k 좋은 아이디어를 보여줍니다.

    그것은 내 문제를 해결했다. 나는 그것을 조금 작은을 변경 :

    $(document).on("change", "select", function(){
        var val = $(this).val();
        $(this).find("option[value=" + val + "]").attr("selected",true);
    });
    

  12. 12.그냥보고. 일부 경건한 알 수없는 이유를 들어,이 내가 첫 번째 테스트 일이었다하더라도, 나는 지금, 무엇이든지 내 코드를 변경하지 않은

    그냥보고. 일부 경건한 알 수없는 이유를 들어,이 내가 첫 번째 테스트 일이었다하더라도, 나는 지금, 무엇이든지 내 코드를 변경하지 않은

    $("#selectTipoIntervencion1").val($("#selectTipoIntervencion0").val());
    

    접근 방법은 노력하고 있습니다. 나는 내가 변화 일뿐 곧 다시 작동이 중지됩니다 이유 또는 경우 아무 생각이 없다,하지만 난 지금이 ​​갈거야. 도움을 주셔서 감사합니다 여러분!

  13. from https://stackoverflow.com/questions/742810/clone-isnt-cloning-select-values by cc-by-sa and MIT license