Пользовательский тумблер перестает работать после трех переключателей - PullRequest
0 голосов
/ 18 декабря 2018

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

Вот код.

$('input[name="switch"]').change(function() {
      if (this.checked) {
        $('input[name="tin"], label[for="tin"]').prop('disabled', true);
        $('input[name="switch"]').prop('name', "tin");
        $('#tinSwitchText').hide().html("(This will attract an added cost)").fadeIn(1500);
      } else {
        $('input[name="tin"], label[for="tin"]').prop('disabled', false);
        $('input[name="switch"]').prop('name', "switch");
        $('#tinSwitchText').html('')
      }
  });
<!-- Include jQuery. -->
<script src="https://code.jquery.com/jquery-3.3.1.min.js"></script>

<div class="form-group d-flex " >
  <span class="w-15 d-flex justify-content-end">
    <input value="Get TIN" type="checkbox" id="id-name--1" name="switch" class="switch-input">
    <label for="id-name--1" class="switch-label"></label>
  </span>
  <span class="w-85 d-flex justify-content-start">
    <label for="" >I dont have a TIN, I want to get one <br>
      <small><i id="tinSwitchText"></i></small> 
    </label>
  </span>
 </div>

Ответы [ 2 ]

0 голосов
/ 19 декабря 2018

Виновная строка $('input[name="switch"]').prop('name', "tin");, делая так, вы отключаете сам флажок после того, как он был переименован.Это подробный процесс:

  1. this.checked - true, input name="switch" переименовывается name="tin"
  2. this.checked - false, input name="switch" не найден
  3. this.checked - true, вход, который был переименован name="tin" отключается

Вам также фактически не нужно переименовывать вход, чтобы обнаружить изменение в данных вашего сервера.Благодаря тому, как работают флажки, ваше поле будет присутствовать во входных данных, если отмечено, и будет отсутствовать, если не отмечено.Этого должно быть достаточно, чтобы определить ваше значение.

просто удалите строки $('input[name="switch"]').prop('name', "tin"); и $('input[name="switch"]').prop('name', "switch");, а затем адаптируйте свою сторону обнаружения на сервере.

0 голосов
/ 18 декабря 2018

Прочитав комментарии и еще много чего, я сделал предположение, что это что-то вроде того, что вы хотели бы иметь?

Должен сказать, что вам немного непонятноВы пытаетесь достичь этого, то есть, почему вы устанавливаете внутреннее значение HTML элемента с идентификатором tinSwitchText на ничего, только для его сброса?Конечно, было бы эффективнее просто показать / скрыть это.

// Some function that will run when the input is checked.
const whenChecked = (input) => {
  $('input[name="tin"], label[for="tin"]').prop('disabled', input.checked);
  $(input).prop('name', "tin");
  $('#tinSwitchText').fadeIn(1500);
};


// Some function that will run when the input is unchecked.
const whenUchecked = (input) => {
  $('input[name="tin"], label[for="tin"]').prop('disabled', input.checked);
  $(input).prop('name', "switch");
  $('#tinSwitchText').hide();
};


// Some function to handle the input state change.
const onChangeHandler = (input) => input.checked ? whenChecked(input) : whenUchecked(input);


// Wait for the DOM to load.
$(document).ready(() => {
  const input = document.querySelector("input[name=switch]");
  input.onchange = () => onChangeHandler(input);
});
<!-- Include jQuery. -->
<script src="https://code.jquery.com/jquery-3.3.1.min.js"></script>

<div class="form-group d-flex " >
  <span class="w-15 d-flex justify-content-end">
    <input value="Get TIN" type="checkbox" id="id-name--1" name="switch" class="switch-input">
    <label for="id-name--1" class="switch-label"></label>
  </span>
  
  <!-- 
     - I've set the content of $('#tinSwitchText') to the default value below, 
     - the reason being because in the example code you provided, there wasn't much
     - going on? It would either be hidden, or visible, and essentially in this 
     - solution, it maintains the same functionality, but by all means, feel free to 
     - change it as you like.
    -->
  <span class="w-85 d-flex justify-content-start">
    <label for="">I dont have a TIN, I want to get one <br>
      <small><i style="display:none" id="tinSwitchText">(This will attract an added cost)</i></small> 
    </label>
  </span>
  
 </div>
...