Search code examples
htmlcssradio-buttonselector

Custom radio selector not functioning


I've created this custom radio selector for my site and the first radio selector is working but the 2nd field isn't selecting. Is there another class that I need to create or have each input named a different ID so they don't conflict with one another? I'm trying to create multiple options for a customer to select an option.

input[type=radio] {
  position: absolute;
  visibility: hidden;
  display: none;
}

label {
  display: inline-block;
  cursor: pointer;
  font-weight: bold;
  padding: 5px 20px;
}

input[type=radio]:checked+label {
  color: #fff;
  background: #444;
  border-radius: 5px;
}

label+input[type=radio]+label {
  border-left: solid 3px #444;
}

.radio-group {
  display: inline-block;
  overflow: hidden;
}
<div class="radio-group">
  <input type="radio" id="lessthan6months" name="timeline"><label for="lessthan6months">6 mo</label>
  <input type="radio" id="6to12months" name="timeline"><label for="6to12months">6-12 mo</label>
  <input type="radio" id="12to24months" name="timeline"><label for="12to24months">12-24 mo</label>
  <div class="line"></div>
</div>

<div class="radio-group">
  <input type="radio" id="tradein_y" name="tradein" value="Yes"><label for="trade in yes">Yes</label>
  <input type="radio" id="tradein_n" name="tradein" value="No"><label for="trade in no">No</label>
  <div class="line"></div>
</div>


Solution

  • The for of the label content has to match the id of the input.

    This will work, like this:

    input[type=radio] {
      position: absolute;
      visibility: hidden;
      display: none;
    }
    
    label {
      display: inline-block;
      cursor: pointer;
      font-weight: bold;
      padding: 5px 20px;
    }
    
    input[type=radio]:checked+label {
      color: #fff;
      background: #444;
      border-radius: 5px;
    }
    
    label+input[type=radio]+label {
      border-left: solid 3px #444;
    }
    
    .radio-group {
      display: inline-block;
      overflow: hidden;
    }
    <div class="radio-group">
      <input type="radio" id="lessthan6months" name="timeline"><label for="lessthan6months">6 mo</label>
      <input type="radio" id="6to12months" name="timeline"><label for="6to12months">6-12 mo</label>
      <input type="radio" id="12to24months" name="timeline"><label for="12to24months">12-24 mo</label>
      <div class="line"></div>
    </div>
    
    <div class="radio-group">
      <input type="radio" id="tradein_y" name="tradein" value="Yes"><label for="tradein_y">Yes</label>
      <input type="radio" id="tradein_n" name="tradein" value="No"><label for="tradein_n">No</label>
      <div class="line"></div>
    </div>