0

I'am trying to wrap every two elements with my custom div. Here is my code:

<div class="variation-radios">
    <input type="radio" name="attribute_pa" value="60-cm">
    <label for="60-cm">60 cm</label>
    <input type="radio" name="attribute_pa" value="70-cm">
    <label for="70-cm">70 cm</label>
    <input type="radio" name="attribute_pa" value="80-cm">
    <label for="80-cm">80 cm</label>
    <input type="radio" name="attribute_pa" value="90-cm">
    <label for="90-cm">90 cm</label>
</div>

And I want go get:

<div class="variation-radios">
    <div class="wrapper">
        <input type="radio" name="attribute_pa" value="60-cm">
        <label for="60-cm">60 cm</label>
    </div>

    <div class="wrapper">
        <input type="radio" name="attribute_pa" value="70-cm">
        <label for="70-cm">70 cm</label>
    </div>

    <div class="wrapper">
        <input type="radio" name="attribute_pa" value="80-cm">
        <label for="80-cm">80 cm</label>
    </div>

    <div class="wrapper">
        <input type="radio" name="attribute_pa" value="90-cm">
        <label for="90-cm">90 cm</label>
    </div>      
</div>

The problem is that tehre are two diferent elements label and input and I can't add there a class. If there would be only inputs I could use jQuery wrapAll. But I don't know how to wrap completly two different html elements with jQuery.

Mike
  • 159
  • 10
  • I should say that for="" in a label should match the id of the related input. Your inputs should have ids. The labels should say for="(relevant id)". THEN - Think of a single jquery selector that gets the pair together. –  Apr 12 '20 at 22:14
  • This is the reason why I trying to fix that with wrapper. Because it's woocommerce product page. I found the solution to convert option fields to radios from this topic: https://stackoverflow.com/questions/36219833/woocommerce-variations-as-radio-buttons but for is not generated correctly. Works only for first group of radios. – Mike Apr 12 '20 at 22:21

1 Answers1

2

This code works like a champ:

<head>
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
</head>
<div class="variation-radios">
    <input id="60-cm" type="radio" name="attribute_pa" value="60-cm">
    <label for="60-cm">60 cm</label>
    <input id="70-cm" type="radio" name="attribute_pa" value="70-cm">
    <label for="70-cm">70 cm</label>
    <input id="80-cm" type="radio" name="attribute_pa" value="80-cm">
    <label for="80-cm">80 cm</label>
    <input id="90-cm" type="radio" name="attribute_pa" value="90-cm">
    <label for="90-cm">90 cm</label>
</div>

<script>
$('input').each(function() {
  $(this).add($(this).next('label')).wrapAll('<div class="wrapper"></div>')
});
</script>

It uses the .each method to loop through every input element, then add the next element: label to it, and then call the .wrapAll to wrap them both together with the div element.

hiew1
  • 1,394
  • 2
  • 15
  • 23