Как установить атрибут имени переключаемого поля ввода при изменении события - PullRequest
0 голосов
/ 14 апреля 2020

Я пытаюсь изменить значение атрибута name="" поля ввода, которое переключается после установки флажка и отображения и заполнения переключенного ввода.

Пользователь устанавливает флажок, после того как флажок установлен, поле ввода показывает, где был заголовок. Я получил эту часть покрыты.

Как только поле ввода показывает, я хочу изменить атрибут имени в этом поле ввода значением, которое пользователь вводит все до отправки формы.

Вот код, который я пробовал ...

document.getElementById('custom-check-box').addEventListener('click', function() {
  if (this.checked) {
    document.getElementById('custom-span').innerHTML = '<input type="text" id="customInputName" name="customInputName" placeholder="Name the custom attribute">';
  } else {
    document.getElementById('custom-span').innerHTML = 'Custom: ';
  }
});
// this bit of code is not working as intended. I want to get the input 
// value after the user changes or focus out of the input and then have that
// value input into the name attribute for the same input.  
document.getElementById('customInputName').addEventListener('change', function() {
  if (this.onChange) {
    let value = document.getElementById('customInputName').value;
    this.setAttribute("name", value);
  }
});
<div title="'.$title.'" class="input-info">
  <span id="custom-span">Custom:</span> Yes: <input id="custom-check-box" type="checkbox" class="input-check" name="custom" value="yes">
</div>

Ошибка: Cannot read property 'addEventListener' of null

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

Любая помощь будет принята с благодарностью, так как я немного новичок с JavaScript.

Заранее спасибо!

СМ. ПРИНЯТЫЙ ОТВЕТ НА ОБНОВЛЕНИЕ РАБОЧЕГО КОДА. -> Во второй фрагмент добавлено редактирование кода @CertainPerformance, которое лучше подходит для моего использования.

1 Ответ

1 голос
/ 14 апреля 2020

Я бы создал <input> вне любого из обработчиков и дал бы ему слушателя, который присваивает его значение его имени. Когда флажок установлен, добавьте ввод к контейнеру, в противном случае очистите контейнер:

const input = document.createElement('input');
input.name = 'customInputName';
input.placeholder = 'Name the custom attribute';
const customSpan = document.getElementById('custom-span');
document.getElementById('custom-check-box').addEventListener('click', function() {
  if (this.checked) {
    customSpan.textContent = '';
    customSpan.appendChild(input);
  } else {
    customSpan.textContent = 'Custom: ';
  }
});
input.addEventListener('change', function() {
  input.name = input.value;
});
<div title="'.$title.'" class="input-info">
  <span id="custom-span">Custom:</span> Yes: <input id="custom-check-box" type="checkbox" class="input-check" name="custom" value="yes">
</div>
...