Как добавить фокус на входные данные, содержащиеся в div, из которого класс был удален, используя jQuery - PullRequest
0 голосов
/ 07 января 2020

Код, приведенный ниже, является функцией jQuery, которая загружает модальный bootstrap, вызванный событием onclick. Этот модал имеет опцию Добавить категорию , которая при щелчке показывает поле ввода, которое ранее было скрыто. Проблема в том, что я хочу сфокусировать ввод, который появляется после щелчка.

// code to show through on click
window.getModalForm_3=function(context){
  $('#ajaxModal').remove();
  var defaults = {
    title: 'Edit',
    action: '',
    helpText:'',
    icon: '',
    placeholder: '',
    name:'', name2:'', name3:'', name4:'', name5:'', name6:'', name7:'',
    value: '', value2: '', value3: '', value4: '', value5: '', value6: '', value7: '',
  };
  var context = $.extend(defaults, context);

  var modal = '<div class="modal fade" id="ajaxModal" tabindex="-1" role="dialog" aria-labelledby="ajaxModalLabel">';
      modal += '<div class="modal-dialog" role="document">';
      modal += '<div class="modal-content">';
      modal += '<div class="modal-header">';
      modal += '<button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">&times;</span></button>';
      modal += '<h4 class="modal-title color-dark">'+ context.title +'</h4>';
      modal += '</div>';
      modal += '<form class="form-horizontal clearfix" action="'+ context.action +'" method="post">';
      modal += '<input type="hidden" name="_method" value="PUT">';
      modal += '<div class="modal-body">';
      modal += '<div class="col-full p-l-20 p-t-5 p-r-20 p-b-20">';
      modal += '<div class="col-full p-b-10">'+ context.helpText +'</div>';

      modal += '<div class="p-t-20 strong">Primary category</div>';

      modal += '<div class="col-full">';
      modal += '<div class="form-group form-group-mat m-l-0 m-r-0 m-t-0 m-b-20 box-60-plus pull-left">';
      modal += '<input id="category_id" name="category_id" value="'+ context.id +'" type="hidden"/>';
      modal += '<input id="category" type="text" class="form-control" name="category" value="'+ context.value +'" required autocomplete="off" spellcheck="false" maxlength="255">';
      modal += '<label for="category" class="control-label"><i class="fa fa-'+ context.icon +' m-r-5"></i>'+ context.placeholder +'</label><i class="bar"></i>';
      modal += '<div id="error_category" class=""></div>';
      modal += '</div>';
      modal += '<div id="categoryList"></div>';
      modal += '</div>';

      modal += '<div class="p-t-20 strong">Additional categories</div>';


      modal += '<div class="col-full '+ (context.name2 == "" ? "hidden" : "") +'">';
      modal += '<div class="form-group form-group-mat m-l-0 m-r-0 m-t-0 m-b-20 box-60-plus pull-left">';
      modal += '<input id="'+ context.name2 +'" type="text" class="form-control" name="'+ context.name2 +'" value="'+ context.value2 +'" required autocomplete="off" spellcheck="false" maxlength="255">';
      modal += '<label for="'+ context.name2 +'" class="control-label"><i class="fa fa-'+ context.icon +' m-r-5"></i>'+ context.placeholder +'</label><i class="bar"></i>';
      modal += '<div id="error_'+ context.name2 +'" class=""></div>';
      modal += '</div>';
      modal += '<div class="pull-left m-t-5 m-l-15 l-h-1 hideCategoryInputInModal" style="font-size: 30px;"><a href="#" style="text-decoration: none;">&times;</a></div>';
      modal += '</div>';

      modal += '<div class="col-full '+ (context.name3 == "" ? "hidden" : "") +'">';
      modal += '<div class="form-group form-group-mat m-l-0 m-r-0 m-t-0 m-b-20 box-60-plus pull-left">';
      modal += '<input id="'+ context.name3 +'" type="text" class="form-control" name="'+ context.name3 +'" value="'+ context.value3 +'" required autocomplete="off" spellcheck="false" maxlength="255">';
      modal += '<label for="'+ context.name3 +'" class="control-label"><i class="fa fa-'+ context.icon +' m-r-5"></i>'+ context.placeholder +'</label><i class="bar"></i>';
      modal += '<div id="error_'+ context.name3 +'" class=""></div>';
      modal += '</div>';
      modal += '<div class="pull-left m-t-5 m-l-15 l-h-1 hideCategoryInputInModal" style="font-size: 30px;"><a href="#" style="text-decoration: none;">&times;</a></div>';
      modal += '</div>';

      modal += '<div class="col-full '+ (context.name4 == "" ? "hidden" : "") +'">';
      modal += '<div class="form-group form-group-mat m-l-0 m-r-0 m-t-0 m-b-20 box-60-plus pull-left">';
      modal += '<input id="'+ context.name4 +'" type="text" class="form-control" name="'+ context.name4 +'" value="'+ context.value4 +'" required autocomplete="off" spellcheck="false" maxlength="255">';
      modal += '<label for="'+ context.name4 +'" class="control-label"><i class="fa fa-'+ context.icon +' m-r-5"></i>'+ context.placeholder +'</label><i class="bar"></i>';
      modal += '<div id="error_'+ context.name4 +'" class=""></div>';
      modal += '</div>';
      modal += '<div class="pull-left m-t-5 m-l-15 l-h-1 hideCategoryInputInModal" style="font-size: 30px;"><a href="#" style="text-decoration: none;">&times;</a></div>';
      modal += '</div>';

      modal += '<div class="col-full '+ (context.name5 == "" ? "hidden" : "") +'">';
      modal += '<div class="form-group form-group-mat m-l-0 m-r-0 m-t-0 m-b-20 box-60-plus pull-left">';
      modal += '<input id="'+ context.name5 +'" type="text" class="form-control" name="'+ context.name5 +'" value="'+ context.value5 +'" required autocomplete="off" spellcheck="false" maxlength="255">';
      modal += '<label for="'+ context.name5 +'" class="control-label"><i class="fa fa-'+ context.icon +' m-r-5"></i>'+ context.placeholder +'</label><i class="bar"></i>';
      modal += '<div id="error_'+ context.name5 +'" class=""></div>';
      modal += '</div>';
      modal += '<div class="pull-left m-t-5 m-l-15 l-h-1 hideCategoryInputInModal" style="font-size: 30px;"><a href="#" style="text-decoration: none;">&times;</a></div>';
      modal += '</div>';

      modal += '<div id="showNextCategoryInModal" class="col-full '+ (context.name5 != "" ? "hidden" : "") +'">';
      modal += '<div class="form-group form-group-mat m-l-0 m-r-0 m-t-20 m-b-10 strong"><a href="#" style="text-decoration: none;">Add another category</a></div>';
      modal += '</div>';


      modal += '</div>';
      modal += '</div>';
      modal += '<div class="modal-footer">';
      modal += '<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>';
      modal += '<button type="button" class="btn btn-primary">Save changes</button>';
      modal += '</div>';
      modal += '</form>';
      modal += '</div>';
      modal += '</div>';
      modal += '</div>';
      $("body").append(modal);
      $('#ajaxModal')
        .on("shown.bs.modal", function() { $(this).find(".form-control:first").focusCursorAtEnd(); })
        .modal({ backdrop: 'static', keyboard: false });
      $("#showNextCategoryInModal").on('click', function(e) {
        e.preventDefault();

        ($( ".col-full.hidden" ).first()).find("input.form-control").focus(); // This is the line where I am facing problem

        $( ".col-full.hidden" ).first().removeClass("hidden");
        if (!($(".col-full.hidden")[0])) {
          $("#showNextCategoryInModal").addClass( "hidden" );
        }
      });
      $(".hideCategoryInputInModal").on("click", function (e) {
        e.preventDefault();
        $(this).closest('div.col-full').addClass( "hidden" );
        $(this).closest('div.col-full').find("input").attr("value", "");
        if (($(".col-full.hidden")[0])) {
          $("#showNextCategoryInModal").removeClass( "hidden" );
        }
      });
};

Я пробовал find (), next (), prev () и многое другое, но не смог достичь желаемого результата .

Образ модальности: enter image description here

Ответы [ 4 ]

1 голос
/ 07 января 2020

У вас есть несколько входов с селектором input.form-control, вы должны найти уникальный и сфокусироваться на нем. Если предположить, что вы покажете самую последнюю версию:

($( ".col-full:not(.hidden)" ).first()).find("input.form-control").last().focus();
0 голосов
/ 07 января 2020

После многих усилий этот код работал для меня.

Изменено это

($( ".col-full.hidden" ).first()).find("input.form-control").focus();

до это

$( ".col-full.hidden > div > input" ).first().addClass("focused");
$( ".col-full.hidden" ).first().removeClass("hidden");
$("input.form-control.focused").last().focus();
0 голосов
/ 07 января 2020

я думаю, что вы должны сначала удалить скрытый класс

$ (".col-full.hidden") .first (). RemoveClass ("hidden");

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

$ (".col-full") .last (). Find ("input.form- контроль "). фокус ()

0 голосов
/ 07 января 2020

Было бы полезно, если бы я мог видеть html коды. (HTML исходный код в режиме разработчика)

Попробуйте выполнить фокусировку после его отображения.

$("#showNextCategoryInModal").on('click', function(e) {
    e.preventDefault();

    $( ".col-full.hidden" ).first().removeClass("hidden");
    if (!($(".col-full.hidden")[0])) {
      $("#showNextCategoryInModal").addClass( "hidden" );
    }

    $( ".col-full" ).last().find("input.form-control").focus(); 
});
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...