Search code examples
javascriptjqueryclone

Clone and Change on new radio check


Firstly I don't want to edit the html but use JavaScript/jQuery to achieve this.

One input is selected(checked) by default and in this example 'Express Shipping'. Then all of the html is cloned / copied from within the parent which is < li > that is holding the input. I don't need the < li > copied just the input within it.

This is then placed inside the #dumpinfohere < div >.

I can manage up to this point, however I want it so when I then toggle between both radio buttons, or if I add additional radio buttons then the complete html of that checked input plus it's < li > replaced the #dumpinfohere section.

This is the code I've done to try and achieve this:

JSFiddle. You can view what I've done here.

HTML

<ul id="shipping_method">
  <li>
    <input type="radio" name="shipping_method[0]" data-index="0" id="shipping_method_0_betrs_shipping_12-1" value="betrs_shipping_12-1" class="shipping_method "> Free Shipping 
  </li>
  <li>
    <input type="radio" name="shipping_method[0]" data-index="0" id="shipping_method_0_betrs_shipping_12-2" value="betrs_shipping_12-2" class="shipping_method" checked="checked"> Express Shipping
  </li>
</ul>

Javascript

jQuery(document).ready(function($){
  var changeShip = function() {
    $('#shipping_method input:checked')
        .parent()
      .clone()
      .appendTo(".woocommerce-billing-fields #dumpinfohere");
  };

  $('#shipping_method input').change(changeShip);

  changeShip();
});

CSS

#shipping_method { 
  float: left; width: 100%;
  list-style: none; 
  padding: 0px;
}
#shipping_method li {
  /* display: none; */
  float: left; width: 100%;
  background: #ccc;
  padding: 5px 10px;
}
#shipping_method .red { background: red; }

.woocommerce-billing-fields { 
  background: #000; color: #fff;
  width: 100%; height: 300px;
  padding: 5px 10px;
  float: left;
}

.woocommerce-billing-fields li { padding: 10px 0px; color: #e024a7; list-style: none; }
.woocommerce-billing-fields li input { display: none; }

However you can see if you toggle between the two radio buttons it doesn't change/replace the text but rather just adds to it?


Solution

  • You just need to add

    $("#dumpinfohere").html('');
    

    after

    var changeShip = function() {
    

    So your final code would be:

    jQuery(document).ready(function($){
      var changeShip = function() {
        $("#dumpinfohere").html('');
        $('#shipping_method input:checked')
            .parent()
          .clone()
          .appendTo(".woocommerce-billing-fields #dumpinfohere");
      };
    
      $('#shipping_method input').change(changeShip);
    
      changeShip();
    });
    

    Basically, you need to empty the container before appending any new text in it.