Динамически проверить все радиовходы проверены - PullRequest
0 голосов
/ 17 октября 2018

У меня много входных данных в таблице.Каждый раз, когда я попадаю на страницу, я хочу подтверждать, что, если у всех radioOpciones* установлен один вариант.Если это правда, я буду show() что-то.

<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>

Я пытался получить длину на

$('.radioGroup').length

, а затем сравнить с проверенными параметрами

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

Я хочуполучить, когда я нажимаю в каждом радио, если это последний выбранный вариант радио, можно отправить кнопку продолжения.

Ответы [ 4 ]

0 голосов
/ 17 октября 2018

Вот как я бы решил эту проблему, используя <radio-group> веб-компонент.Элемент представляет отсутствующий элемент радиогруппы, который вы можете просто запросить для значения.null означает, что ни одна из переключателей не является :checked.В противном случае элемент радиогруппы сообщает значение радиокнопки :checked:

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>
0 голосов
/ 17 октября 2018

ОБНОВЛЕНО

Поиск различных имен радиовходов, передача их в функцию checkRadioGroups() и получение результатов.

Вы можете использовать эту функцию каждый раз, когда хотитепроверьте состояние checked радиовходов.

ПРИМЕЧАНИЕ

Вы можете использовать этот подход в любой возможной структуре HTML.

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>
0 голосов
/ 17 октября 2018

попробуйте этот код

$(function() {

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

});

надеюсь, это поможет

0 голосов
/ 17 октября 2018

Во-первых, вам нужно дать разные идентификаторы для ваших входных данных на одной странице из-за HTML-правил.Потому что идентификатор определяет уникальный идентификатор для элемента. Здесь

И ваше элегантное решение здесь:

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

ИЛИ

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