функция Добавить и удалить поля раскрывающегося списка ввода с javascript не работает должным образом - PullRequest
2 голосов
/ 04 августа 2020

сейчас делаю laravel проект. Я реализую Dynami c Добавляя и удаляя поля раскрывающегося списка ввода, используйте javascript. функция добавления и удаления может работать нормально. но проблема в выпадающих полях. внутри раскрывающегося списка я добавляю опцию «другое», поэтому при выборе «другое» будет отображаться текст типа ввода.

Я просто могу отображать текст типа ввода только в первой строке. но в другой строке неверно. вот мой код

<div id="AddItemOption">
            <div class="d-flex justify-content-center align-items-center">
                <table class="table table-striped table-condensed table-additems">
                    <thead>
                        <tr>
                            <th class="align-middle border-0">items</th>
                            <th class="align-middle border-0">Delete</th>
                        </tr>
                    </thead>
                    <tbody>
                        <tr id="row1">
                            <td>
                                <select  name="items[]" class="form-control sellitem">
                                    <option value="book">book</option>
                                    <option value="pencil">pencil</option>
                                    <option value="pen">pen</option>
                                    <option value="other">other</option>
                                </select>

                                 <input type="text" class='form-control inputother' style="display: none;" name="other[]"  >

                            </td>
                            <td class="action">
                                <button type="submit" class="btn btn-danger ">
                                    Delete
                                </button>
                            </td>
                        </tr>
                        <tr>
                            <td colspan="4">
                                <button type="button" class="btn btn-default btn-xs">+ Add New Item</button>
                            </td>
                        </tr>
                    </tbody>
                </table>
            </div>
        </div>

, а вот скрипт

<script>
        var i=1;
    $('#AddItemOption .btn-default').on('click', function(e) {
        i++;
        var el = $('.table-additems tbody tr:eq(0)').clone();
        $(el).find('option:selected').removeAttr('selected');
        $(el).find(':input').each(function(){
            $(this).removeAttr('value');
        });

        $(this).closest('tr').before('<tr id="row'+i+'" >'+$(el).html()+'</tr>');
    });
    $(document).on('click', '#AddItemOption .btn-danger', function(e) {
        if ($('.table-additems tbody tr').length == 2) {
            var el = $('.table-additems tbody tr:eq(0)');
            $(el).find('select:eq(0)').val($(el).find('select:eq(0) option:first').val());
            $(el).find('select:eq(1)').val($(el).find('select:eq(1) option:first').val());
            $(el).find('input:eq(0)').val('');
            e.preventDefault();
        }
        else {
            $(this).closest('tr').remove();
        }
    });

    $('.sellitem').change(function(){
        if ($(this).val() == 'other') {
            $('.inputother').css({'display':'block'});
        }else{
            $('.inputother').css({'display':'none'});
        }
    }); 

    </script>

и вот ссылка, которую я сделал для тестирования тестовая функция добавления и удаления, созданная мной просто нажмите кнопку «запустить», чтобы проверить код

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

пожалуйста, помогите

Ответы [ 2 ]

1 голос
/ 04 августа 2020

В событии click из #AddItemOption вы можете скрыть ввод, который клонирован по умолчанию, а при изменении поля выбора вы можете использовать $(this).closest("tr").find('.inputother'), чтобы показать или скрыть только тот ввод, который находится под окном выбора .

Код демонстрации :

var i = 1;
$('#AddItemOption .btn-default').on('click', function(e) {
  i++;
  var el = $('.table-additems tbody tr:eq(0)').clone();
  $(el).find('option:selected').removeAttr('selected');
  $(el).find(':input').each(function() {
    $(this).removeAttr('value');
  });
  //while cloning hide other input
  $(el).find('.inputother').css({
    'display': 'none'
  });

  $(this).closest('tr').before('<tr id="row' + i + '" >' + $(el).html() + '</tr>');
});
$(document).on('click', '#AddItemOption .btn-danger', function(e) {
  if ($('.table-additems tbody tr').length == 2) {
    var el = $('.table-additems tbody tr:eq(0)');
    $(el).find('select:eq(0)').val($(el).find('select:eq(0) option:first').val());
    $(el).find('select:eq(1)').val($(el).find('select:eq(1) option:first').val());
    $(el).find('input:eq(0)').val('');
    e.preventDefault();
  } else {
    $(this).closest('tr').remove();
  }
});
//use this because other slect-box are dynmically created
$(document).on('change', '.sellitem', function(e) {
  if ($(this).val() == 'other') {
  //find this ->closest trs-> get input box show
    $(this).closest("tr").find('.inputother').css({
      'display': 'block'
    });
  } else {
    $(this).closest("tr").find('.inputother').css({
      'display': 'none'
    });
  }
});
<!DOCTYPE html>
<html>

<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width">
  <title>repl.it</title>
  <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.0/css/bootstrap.min.css" integrity="sha384-9aIt2nRpC12Uk9gS9baDl411NQApFmC26EwAOH8WgZl5MYYxFfc+NcPb1dKGj7Sk" crossorigin="anonymous">
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
  <link href="style.css" rel="stylesheet" type="text/css" />
</head>

<body>
  <div class="ajaxModalBody">
    <div class="container-fluid">
      <div id="AddItemOption">
        <div class="d-flex justify-content-center align-items-center">
          <table class="table table-striped table-condensed table-additems">
            <thead>
              <tr>
                <th class="align-middle border-0">items</th>
                <th class="align-middle border-0">Delete</th>
              </tr>
            </thead>
            <tbody>
              <tr id="row1">
                <td>
                  <select name="items[]" class="form-control sellitem">
                    <option value="book">book</option>
                    <option value="pencil">pencil</option>
                    <option value="pen">pen</option>
                    <option value="other">other</option>
                  </select>

                  <input type="text" class='form-control inputother' style="display: none;" name="other[]">

                </td>
                <td class="action">
                  <button type="submit" class="btn btn-danger ">
                                    Delete
                                </button>
                </td>
              </tr>
              <tr>
                <td colspan="4">
                  <button type="button" class="btn btn-default btn-xs">+ Add New Item</button>
                </td>
              </tr>
            </tbody>
          </table>
        </div>
      </div>
    </div>
  </div>
  <script src="script.js"></script>
</body>

</html>
0 голосов
/ 04 августа 2020
var i=1;
    $('#AddItemOption .btn-default').on('click', function(e) {
        i++;
        var el = $('.table-additems tbody tr:eq(0)').clone();
        $(el).find('.inputother').attr('count', i);
        $(el).find('.inputother').addClass('inputothercount' + i);
        $(el).find('.inputother').removeClass('firstinput');

        $(el).find('.sellitem').attr('count', i);
      //  $(el).find('.sellitem').class('count' + i);
        $(el).find('option:selected').removeAttr('selected');
        $(el).find(':input').each(function(){
            $(this).removeAttr('value');
        });

        $(this).closest('tr').before('<tr id="row'+i+'" >'+$(el).html()+'</tr>');
        listen();
    });

    $(document).on('click', '#AddItemOption .btn-danger', function(e) {
        if ($('.table-additems tbody tr').length == 2) {
            var el = $('.table-additems tbody tr:eq(0)');
            $(el).find('select:eq(0)').val($(el).find('select:eq(0) option:first').val());
            $(el).find('select:eq(1)').val($(el).find('select:eq(1) option:first').val());
            $(el).find('input:eq(0)').val('');
            e.preventDefault();
        }
        else {
            $(this).closest('tr').remove();
        }
    });


function listen() {
    $('.sellitem').change(function(){
        var count = $(this).attr('count') || 1;
        if (count == 1) {
           if ($(this).val() == 'other') {
            $('.firstinput').css({'display':'block'});
        }else{  
            $('.firstinput').css({'display':'none'});
        };
          return;
        } else {

        if ($(this).val() == 'other') {
            $('.inputothercount' + count).css({'display':'block'});
        }else{
            $('.inputothercount' + count).css({'display':'none'});
        }
        }
    });
}
listen();

Вы можете поиграть с ним здесь https://repl.it/repls/DefiniteMintyScandisk#index. html и вам нужно будет добавить firstinput класс в <input type="text" class='form-control inputother' style="display: none;" name="other[]" > также

  1. Когда вы добавляете и удаляете отображение через класс .inputother, вы делаете это для всех элементов, размещенных в представлении. Вы должны добавить к нему класс inputothercontent${count}, чтобы вы могли найти указанный c элемент по счетчику и скрыть отображение соответствующего div.

  2. Добавьте firstinput класс по умолчанию в html и удалите его при добавлении других элементов.

  3. Вам нужно будет снова разбудить слушателя, чтобы прослушать .sellitem щелчок после добавления элемента в dom. Он не обновляет автоматически sh для динамически добавляемых элементов.

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

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