2

Есть скрипт.

Он добавляет текст из селектов в теги блока Special Price (span curr, span numb). При вводе цифр добавляется новый аналогичный блок. Необходимо добавить точно такой же блок, как и предыдущий. Но текст из тегов <span> (numb, curr) не добавляется.

Я так понимаю, что этот скрипт анализирует только исходную разметку HTML?

online ide

(function() {
  $(document).ready(function() {
    //Добавление текста в теги span. Работает верно
    $('.field.inline.specially > span.curr').text(
      $('#id_lot_currency > option:selected').eq(0).text()
    );
    $('.field.inline.specially > span.numb').text(
      $('#id_lot_type > option:selected').eq(0).text()
    );
    $(document).on('change','#id_lot_currency',function () {
      $('.field.inline.specially span').eq(3).text($('option:selected',this).text())
    })
    $(document).on('change','#id_lot_type',function () {
      $('.field.inline.specially span').eq(1).text($('option:selected',this).text())
    });
  })
  
  //Добавление аналогичных блоков. Почему-то не видит текст, добавленный предыдущим кодом.
  var copy = document.querySelector('.field.inline.specially').cloneNode(true);
  document.querySelector('html').addEventListener('input', function(e) {
    if (e.target.classList.contains('event') && e.target.tagName == 'INPUT') {
      var error = 0;
      for (var evt of document.querySelectorAll('.field.inline.specially input.event')) {
        evt.value = evt.value.replace(/[^\d]/, '');
        if (!evt.value || +evt.value < 1) error++;
      }
      if (!error) {
        var last = document.querySelectorAll('.field.inline.specially');
        last[last.length - 1].insertAdjacentHTML('afterEnd', copy.outerHTML);
      }
    }
  });
})();
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="field inline" id="lot_minimum">
  <label for="id_lot_minimum" class="subhead">Lot minimum:</label>
  <input type="number" name="lot_minimum" required id="id_lot_minimum" />
  <select name="lot_type" style="width: 100px" class="select2" id="id_lot_type">
    <option value="1">kg</option>
    <option value="2">foot</option>
  </select>
</div>
<div class="field inline" id='lot'>
  <label for="id_lot_cost" class="subhead">Cost:</label>
  <input type="number" name="lot_cost" step="0.01" required id="id_lot_cost" />
  <select name="lot_currency" style="width: 100px" class="select2" id="id_lot_currency">
    <option value="1">usd</option>
    <option value="3">blg</option>
    <option value="2">uah</option>
  </select>
</div>

<div class="field inline specially">
  <label for="specially" class="subhead">Special price</label>
  <span class="id_specially_price"><input type="text" name="adittional_specially_price" style="width: 165px" class="event" id="" /></span>
  <span class='numb'></span>
  <span class="id_specially_number"><input type="text" name="adittional_specially_number" style="width: 100px" class="event" id="" /></span>
  <span class='curr'></span>
</div>

То есть, в добавленных блоках нет текста со span curr, span numb (usd, kg, например)

1 ответ 1

1

Вы это имеете в виду?

(function() {
  $(document).ready(function() {
    //Добавление текста в теги span. Работает верно
    $('.field.inline.specially > span.curr').text(
      $('#id_lot_currency > option:selected').eq(0).text()
    );
    $('.field.inline.specially > span.numb').text(
      $('#id_lot_type > option:selected').eq(0).text()
    );
    $(document).on('change','#id_lot_currency',function () {
      $('.field.inline.specially span.curr').text($('option:selected',this).text())
    })
    $(document).on('change','#id_lot_type',function () {
      $('.field.inline.specially span.numb').text($('option:selected',this).text())
    });
  })
  
  //Добавление аналогичных блоков. Почему-то не видит текст, добавленный предыдущим кодом.

  document.querySelector('html').addEventListener('input', function(e) {
    var copy = document.querySelector('.field.inline.specially').cloneNode(true);
    if (e.target.classList.contains('event') && e.target.tagName == 'INPUT') {
      var error = 0;
      for (var evt of document.querySelectorAll('.field.inline.specially input.event')) {
        evt.value = evt.value.replace(/[^\d]/, '');
        if (!evt.value || +evt.value < 1) error++;
      }
      if (!error) {
        var last = document.querySelectorAll('.field.inline.specially');
        last[last.length - 1].insertAdjacentHTML('afterEnd', copy.outerHTML);
      }
    }
  });
})();
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="field inline" id="lot_minimum">
  <label for="id_lot_minimum" class="subhead">Lot minimum:</label>
  <input type="number" name="lot_minimum" required id="id_lot_minimum" />
  <select name="lot_type" style="width: 100px" class="select2" id="id_lot_type">
    <option value="1">kg</option>
    <option value="2">foot</option>
  </select>
</div>
<div class="field inline" id='lot'>
  <label for="id_lot_cost" class="subhead">Cost:</label>
  <input type="number" name="lot_cost" step="0.01" required id="id_lot_cost" />
  <select name="lot_currency" style="width: 100px" class="select2" id="id_lot_currency">
    <option value="1">usd</option>
    <option value="3">blg</option>
    <option value="2">uah</option>
  </select>
</div>

<div class="field inline specially">
  <label for="specially" class="subhead">Special price</label>
  <span class="id_specially_price"><input type="text" name="adittional_specially_price" style="width: 165px" class="event" id="" /></span>
  <span class='numb'></span>
  <span class="id_specially_number"><input type="text" name="adittional_specially_number" style="width: 100px" class="event" id="" /></span>
  <span class='curr'></span>
</div>

я переместил

var copy = document.querySelector('.field.inline.specially').cloneNode(true);

внутрь слушателя

document.querySelector('html').addEventListener('input', function(e) {

В вашем варианте получается так, что Вы клонировали элемент еще без текста внутри элементов...

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

8
  • Да, это оно. Спасибо. А как сделать, чтобы при изменении выбора в селекте текст изменялся не только в первом блоке, но и в остальных, склонированных?
    – pythoner
    27 апр 2019 в 21:05
  • @pythoner то есть во всех должно быть одинаковое значение всегда? 27 апр 2019 в 21:06
  • Да, и оно должно зависеть от выбора в соответствующем селекте.
    – pythoner
    27 апр 2019 в 21:07
  • @pythoner Сейчас подумаю, я не сильно вчитывался в начало скрипта... 27 апр 2019 в 21:08
  • 1
    было $('.field.inline.specially span').eq(3) стало $('.field.inline.specially span.curr') и ниже то же самое, в начале скрипта 27 апр 2019 в 21:19

Ваш ответ

Нажимая на кнопку «Отправить ответ», вы соглашаетесь с нашими пользовательским соглашением, политикой конфиденциальности и политикой о куки

Всё ещё ищете ответ? Посмотрите другие вопросы с метками или задайте свой вопрос.