ntzz
ntzz

Reputation: 183

Dynamically validate all radio inputs are checked

I've got many inputs in a table. I want to validate each time i get in the page that if all the radioOpciones* have one option checked. If it's true, I will show() something.

<table>
  <tr>
    <th>
      title
    </th>
    <td class="radioGroup">
      <input id="radioOpciones1" value="1" name="radioOpciones1" checked="checked" type="radio">
    </td>
    <td class="radioGroup">
      <input id="radioOpciones2" value="2" name="radioOpciones1" type="radio">
    </td>
    <td class="radioGroup">
      <input id="radioOpciones3" value="3" name="radioOpciones1" type="radio">
    </td>
    <td class="radioGroup">
      <input id="radioOpciones4" value="4" name="radioOpciones1" type="radio">
    </td>
    <td class="radioGroup">
      <input id="radioOpciones5" value="5" name="radioOpciones1" type="radio">
    </td>
  </tr>
  <tr>
    <th>
      title2
    </th>
    <td class="radioGroup">
      <input id="radioOpciones6" value="1" name="radioOpciones2" checked="checked" type="radio">
    </td>
    <td class="radioGroup">
      <input id="radioOpciones7" value="2" name="radioOpciones2" type="radio">
    </td>
    <td class="radioGroup">
      <input id="radioOpciones8" value="3" name="radioOpciones2" type="radio">
    </td>
    <td class="radioGroup">
      <input id="radioOpciones9" value="4" name="radioOpciones2" type="radio">
    </td>
    <td class="radioGroup">
      <input id="radioOpciones10" value="5" name="radioOpciones2" type="radio">
    </td>
  </tr>
</table>

I was trying to get the length by

$('.radioGroup').length

and then compare with checked options

$('.radioGroup:has(input:checked)').length

I want to get when i click in each radio that if it's the last radio option checked possible to send a continue button.

Upvotes: 0

Views: 90

Answers (4)

connexo
connexo

Reputation: 56823

This is how I'd address this using a <radio-group> webcomponent. The element represents the missing radio-group element which you can simply ask for the value. null means none of the radio buttons is :checked. Otherwise, the radio-group element reports the value of the :checked radiobutton:

class RadioGroup extends HTMLElement {
  constructor(...args) {
    const self = super(...args)
    self.type = 'radio-group'
    self.radioButtons = null
    return self
  }

  get value() {
    const checked = this.querySelector(':checked')
    return checked ? checked.value : null
  }

  set value(val) {
    const radios = this.radioButtons.filter(i => i.value === val)
    if (radios.length) {
      radios[0].checked = true
    } else {
      for (const radioButton of this.radioButtons) {
        radioButton.checked = false
      }
    }

    let change = createNewEvent('change', true, true)
    this.dispatchEvent(change)
  }

  connectedCallback() {
    if (this.nextSibling) { // children parsed?
      this.radioButtons = [...this.querySelectorAll('input[type=radio]')]
    } else { // if not, populate radioButtons only on next animation frame
      window.requestAnimationFrame(() => {
        this.radioButtons = [...this.querySelectorAll('input[type=radio]')]
      })
    }
  }
}

window.customElements.define('radio-group', RadioGroup)

let radioGroups = Array.from(document.querySelectorAll('radio-group'))

check.addEventListener('click', (e) => {
  console.log(radioGroups.every(radioGroup => radioGroup.value))
})
<radio-group id="sex">
  <fieldset>
    <legend>Sex</legend>
    <input type="radio" value="female" id="female" name="sex" />
    <label for="female">female</label>
    <input type="radio" value="male" id="male" name="sex" />
    <label for="male">male</label>
    <input type="radio" value="diverse" id="diverse" name="sex" />
    <label for="diverse">diverse</label>
  </fieldset>
</radio-group>
<radio-group id="color">
  <fieldset>
    <legend>Color</legend>
    <input type="radio" value="blue" id="blue" name="color" />
    <label for="blue">blue</label>
    <input type="radio" value="red" id="red" name="color" />
    <label for="red">red</label>
    <input type="radio" value="green" id="green" name="color" />
    <label for="green">green</label>
  </fieldset>
</radio-group>
<button id="check" type="button">Check if each radiogroup has a checked radiobutton</button>

Upvotes: 1

kapantzak
kapantzak

Reputation: 11750

UPDATED

Search for distinct radio input names, pass them to checkRadioGroups() function and get results.

You can use this function each time you want to check the checked state of the radio inputs.

NOTE

You can use this approach in any possible HTML structure.

function checkRadioGroups(collection) {
  var obj = {};
  for (var i in collection) {
    var nameAttr = collection[i];
    var isChecked = $('input[name="' + nameAttr + '"]:checked').length > 0;
    obj[nameAttr] = isChecked;
  }
  return obj;
}

function getDistinctGroupNames() {
    var names = [];
    $('input[type="radio"]').each(function(index, elem) {
        var name = $(elem).attr('name');
        if (names.indexOf(name) === -1) {
            names.push(name);
        }
    });
    return names;
}

var check = checkRadioGroups(getDistinctGroupNames());
console.log(check);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table>
      <tr>
        <th>
          title
        </th>
        <td class="radioGroup">
          <input id="radioOpciones1" value="1" name="radioOpciones1" checked="checked" type="radio">
        </td>
        <td class="radioGroup">
          <input id="radioOpciones1" value="2" name="radioOpciones1" type="radio">
        </td>
        <td class="radioGroup">
          <input id="radioOpciones1" value="3" name="radioOpciones1" type="radio">
        </td>
        <td class="radioGroup">
          <input id="radioOpciones1" value="4" name="radioOpciones1" type="radio">
        </td>
        <td class="radioGroup">
          <input id="radioOpciones1" value="5" name="radioOpciones1" type="radio">
        </td>
      </tr>
      <tr>
        <th>
          title2
        </th>
        <td class="radioGroup">
          <input id="radioOpciones2" value="1" name="radioOpciones2" type="radio">
        </td>
        <td class="radioGroup">
          <input id="radioOpciones2" value="2" name="radioOpciones2" type="radio">
        </td>
        <td class="radioGroup">
          <input id="radioOpciones2" value="3" name="radioOpciones2" type="radio">
        </td>
        <td class="radioGroup">
          <input id="radioOpciones2" value="4" name="radioOpciones2" type="radio">
        </td>
        <td class="radioGroup">
          <input id="radioOpciones2" value="5" name="radioOpciones2" type="radio">
        </td>
      </tr>
    </table>

Upvotes: 1

Kiranramchandran
Kiranramchandran

Reputation: 2094

try this code

$(function() {

    var radios = $('input[type=radio][name*=radioOpciones]').filter(function() {
        return $(this).is(':checked')
    });
    alert(radios.length);

});

hope this helps

Upvotes: 1

atesbaris
atesbaris

Reputation: 31

Firstly, you need to give different id's to your inputs in same page cause of HTML rules. Because id specifies a unique id for the element. Here

And your elegant solution is here :

if($('input.classname').not(':checked').length > 0) {
  ...
}

OR

 if($('input[name="inputname"]').not(':checked').length > 0) {
  ...
}

Upvotes: -1

Related Questions