克隆无线电标签并在单击标签时更改输入'已检查'属性

时间:2017-06-25 17:06:11

标签: jquery

我有一个包含多个input[type='radio']元素的表单。当点击其中一个时,我正在克隆该特定元素的标签并将其标签放入元素中。我无法弄清楚的是如何做到以下几点:

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');
  }
});

1 个答案:

答案 0 :(得分: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
  }
});