Javascript-форум (https://javascript.ru/forum/)
-   Элементы интерфейса (https://javascript.ru/forum/dom-window/)
-   -   Установка radio:checked в зависимости от значения Span (https://javascript.ru/forum/dom-window/72602-ustanovka-radio-checked-v-zavisimosti-ot-znacheniya-span.html)

gdvorc 11.02.2018 19:29

Установка radio:checked в зависимости от значения Span
 
Вроде простая задача. А бьюсь над ней уже 3 час. У меня есть таблица. Количество строк в ней может быть любое.
<tr id="" class="cart-item-pr">
    <td class="weight">
        <input type="radio"  class="rchecking" id="c2" name="price-hours" value="100" /><label for="c2"></label>
        <input type="radio"  class="rchecking" id="c3" name="price-hours" value="200" /><label for="c3"></label>
        <input type="radio"  class="rchecking" id="c4" name="price-hours" value="300" /><label for="c4"></label>
        <input type="radio"  class="rchecking" id="c5" name="price-hours" value="400" /><label for="c5"></label>
    </td>
    <td class="price">
        <span id="price">200</span>
    </td>
</tr>


Задача. При загрузки страницы сравнивать значение #price c val #c2, #c3, #c4, #c5 и ставить checked на нужный radio. И чтобы это все происходило для каждой tr.cart-item-pr(строки таблицы). Они могут быть одна, две три и много. Я понимаю что нужно что то мутить через $(this).Но пока не как

j0hnik 11.02.2018 19:37

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>Document</title>
</head>
<body>
  <tr id="" class="cart-item-pr">
    <td class="weight">
      <input type="radio"  class="rchecking" id="c2" name="price-hours" value="100" /><label for="c2"></label>
      <input type="radio"  class="rchecking" id="c3" name="price-hours" value="200" /><label for="c3"></label>
      <input type="radio"  class="rchecking" id="c4" name="price-hours" value="300" /><label for="c4"></label>
      <input type="radio"  class="rchecking" id="c5" name="price-hours" value="400" /><label for="c5"></label>
    </td>
    <td class="price">
      <span id="price">200</span>
    </td>
    </tr>
  <script>
document.querySelector('.rchecking[value="'+document.querySelector("#price").textContent+'"]').checked = true;
  </script>
</body>
</html>

gdvorc 11.02.2018 19:42

К сожаленю ваш вариант, так же как и множество решений что сегодня перепробовал работает только с первым <tr id="" class="cart-item-pr">
, а их в таблице будет неизвестное количество.

j0hnik 11.02.2018 19:50

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>Document</title>
</head>
<body>
  <tr id="" class="cart-item-pr">
    <td class="weight">
      <input type="radio"  class="rchecking" id="c2" name="price-hours" value="100" /><label for="c2"></label>
      <input type="radio"  class="rchecking" id="c3" name="price-hours" value="200" /><label for="c3"></label>
      <input type="radio"  class="rchecking" id="c4" name="price-hours" value="300" /><label for="c4"></label>
      <input type="radio"  class="rchecking" id="c5" name="price-hours" value="400" /><label for="c5"></label>
    </td>
    <td class="price">
      <span id="price">200</span>
    </td>
    </tr>
      <tr id="" class="cart-item-pr">
    <td class="weight">
      <input type="radio"  class="rchecking" id="c2" name="price-hours-2" value="100" /><label for="c2"></label>
      <input type="radio"  class="rchecking" id="c3" name="price-hours-2" value="200" /><label for="c3"></label>
      <input type="radio"  class="rchecking" id="c4" name="price-hours-2" value="300" /><label for="c4"></label>
      <input type="radio"  class="rchecking" id="c5" name="price-hours-2" value="400" /><label for="c5"></label>
    </td>
    </tr>
  <script>
document.querySelectorAll('.rchecking[value="'+document.querySelector("#price").textContent+'"]').forEach(el=>el.checked = true);
  </script>
</body>
</html>

Manyasha 11.02.2018 19:51

gdvorc,
может так?
<script src="https://code.jquery.com/jquery-1.9.0.min.js"></script>
<script>
$(function(){
	$(".cart-item-pr").each(function(){
  	var price = $(this).find("td.price span").text();
    $(this).find("input.rchecking").filter(function(i, e){return $(e).val() == price;}).prop("checked", true);
  });
})
</script>
<table>
<tr id="" class="cart-item-pr">
  <td class="weight">
    <input type="radio"  class="rchecking" id="c2" name="price-hours1" value="100" /><label for="c2"></label>
    <input type="radio"  class="rchecking" id="c3" name="price-hours1" value="200" /><label for="c3"></label>
    <input type="radio"  class="rchecking" id="c4" name="price-hours1" value="300" /><label for="c4"></label>
    <input type="radio"  class="rchecking" id="c5" name="price-hours1" value="400" /><label for="c5"></label>
  </td>
  <td class="price">
    <span id="price">200</span>
  </td>
</tr>
<tr id="" class="cart-item-pr">
  <td class="weight">
    <input type="radio"  class="rchecking" id="c2" name="price-hours2" value="100" /><label for="c2"></label>
    <input type="radio"  class="rchecking" id="c3" name="price-hours2" value="200" /><label for="c3"></label>
    <input type="radio"  class="rchecking" id="c4" name="price-hours2" value="300" /><label for="c4"></label>
    <input type="radio"  class="rchecking" id="c5" name="price-hours2" value="400" /><label for="c5"></label>
  </td>
  <td class="price">
  <span id="price">400</span>
  </td>
</tr>
</table>


айдишки намеренно не использовала. т.к. они наверняка разные будут.

j0hnik 11.02.2018 19:51

#price один для всех будет?

j0hnik 11.02.2018 19:52

атрибут id должен быть уникальным! тут уже миллион раз обсуждалось

gdvorc 11.02.2018 19:59

Примерно так. Но name менять тоже не могу. т.к. это корзина и товары грузит туда cms. А стандартным функционалом цен воспользоваться не получается. У начальника слишком извращенное представления.
В обратную сторону все работает идеально. То есть уже после загрузки тыкаю радио ставит именно в нужное место цену. а вот на оборот...

gdvorc 11.02.2018 20:00

Натолкнули меня на мысль. Сейчас попробую сделать по другому

j0hnik 11.02.2018 20:02

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


Часовой пояс GMT +3, время: 15:53.