2017-06-25 14 views
0

私はinput[type='radio']要素のフォームを持っています。これらのうちの1つがクリックされると、その特定の要素のラベルを複製し、ラベルを要素に配置します。ラベルがクリックされたときにラジオ・ラベルをクローンして入力 'checked'プロパティを変更しました

1)クローンラベルが削除された(クリックされた)場合、ラジオ入力はデフォルトで<input id="default" type="radio"/>になり、このデフォルト入力の関連ラベルが出力されるはずですヘッダーに

2)ラジオボタンをクリックすると、ヘッダーに出力されたクローンラベルが削除され、新しいクローンに置き換えられます。

次のようなペンが表示されます。つまり、チェックされた状態は意図したとおりに変化しておらず、クローンのラベル自体がクローンされています。

Click me

マークアップ

<header> 
</header> 
<aside> 
    <form action=""> 
    <input name="form" id="default" type="radio" /> 
    <label for="default">Default</label> 
    <input name="form" id="one" type="radio" /> 
    <label for="one">One</label> 
    <input name="form" id="two" type="radio" /> 
    <label for="two">Two</label> 
    </form> 
</aside> 

jQueryの1.7

// Set active state on default radio input 
$("#default").prop("checked", true); 

// Clone and add/remove associated radio labels on click 
$("input").click(function() { 

    var self = $(this); 
    $('header label.radio-clone').remove(); 
    // if checked clone the radio input's label amd add to header 
    if (self.prop('checked', true)) { 
    self 
     .next("label") 
     .clone() 
     .addClass("radio-clone") 
     .appendTo("header"); 
    // add a class to associated original label (i.e. the non-cloned one) 
    self.next("label").addClass("is-checked"); 
    } else { 
    // if label in header is clicked remove from header 
    $('header label[for="' + self.attr('id') + '"]').remove(); 
    // remove class on the original label 
    self.next("label").removeClass("is-checked"); 
    // revert checked property to false on all radio inputs 
    self.prop("checked", false).addClass('test1'); 
    // then add checked true to the default radio input 
    $("#default").prop("checked", true).addClass('test2'); 
    } 
}); 

答えて

0

私は種類のソリューションを持っています。ラジオ入力のために常に値が表示されることを前提に、私は単にラベルを複製し、クローン上のイベントを避けるだけです。私はまだ私の最初の目標を達成する方法を知っている(私はおそらくifをドロップし、元の入力と別のクローンのラベル上の別のクリックイベントと一緒に行く必要があると思う)誰もが解決策を持っている場合火を消す。

ここでは、克服されたバックソリューションです。

Click me

// On page load set active state on default radio input and clone label to header 
$("#default").prop("checked", true); 
$("#default") 
    .next("label") 
    .clone(true, true) 
    .prepend("Blah: ") 
    .addClass("radio-clone") 
    .appendTo("header"); 

// On click clone and add/remove associated radio labels on click 
$("input").click(function() { 
    var self = $(this); 
    $("header label.radio-clone").remove(); 
    // if checked clone the radio input's label amd add to header 
    if (self.prop("checked", true)) { 
    self 
     .next("label") 
     .clone(true, true) 
     .prepend("Blah: ") 
     .addClass("radio-clone") 
     .appendTo("header"); 
    // add a class to associated original label (i.e. the non-cloned one) 
    $("input").next("label").removeClass("is-checked"); // remove 
    self.next("label").addClass("is-checked"); // then add 
    } 
});