Подтвердить что ты не робот

Twitter Bootstrap 2 модальные формы диалогов

У меня есть следующий диалог:

<div class='modal' id='myModal'>
  <div class='modal-header'>
    <a class='close' data-dismiss='modal'>×</a>
    <h3>Add Tags</h3>
  </div>

  <div class='modal-body'>
    <form accept-charset="UTF-8" action="/tagging" data-remote="true" method="post"><div style="margin:0;padding:0;display:inline"><input name="utf8" type="hidden" value="&#x2713;" /><input name="authenticity_token" type="hidden" value="mCNvbvoPFWhD7SoJm9FPDh+BcRvCG3d16P+oOFACPuc=" /></div>
        <input id="tags_string" name="tags_string" type="text" value="luca" />
        <input id="id" name="id" type="hidden" value="4f1c95fd1d41c80ff200067f" />
    </form>
  </div>

  <div class='modal-footer'>
    <div class='btn btn-primary'><input name="commit" type="submit" value="Add tag" /></div>
  </div>
</div>

и его JS:

<script>
  //<![CDATA[
    $(function() {
      // wire up the buttons to dismiss the modal when shown
      $("#myModal").bind("show", function() {
        $("#myModal a.btn").click(function(e) {
          // do something based on which button was clicked
          // we just log the contents of the link element for demo purposes
          console.log("button pressed: "+$(this).html());
          // hide the dialog box
          $("#myModal").modal('hide');
        });
      });
      // remove the event listeners when the dialog is hidden
      $("#myModal").bind("hide", function() {
          // remove event listeners on the buttons
          $("#myModal a.btn").unbind();
      });
      // finally, wire up the actual modal functionality and show the dialog
      $("#myModal").modal({
        "backdrop" : "static",
        "keyboard" : true,
        "show" : true // this parameter ensures the modal is shown immediately
      });
    });
  //]]>
</script>

Когда я нажимаю x, который равен <a class='close' data-dismiss='modal'>×</a>, форма закрывается, оставляя меня на текущей странице, в то время как я хотел бы перейти на страницу hamepage.

Также "Добавить тег" botton, который <div class='btn btn-primary'><input name="commit" type="submit" value="Add tag" /></div> ничего не делает, нажав jaust ENTER на клавиатуре, выполните задание, и я бы хотел нажать "Добавить тег", сделав то же самое.

Я не очень разбираюсь в JS и front-end prog, поэтому любая помощь приветствуется.

4b9b3361

Ответ 1

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

Используйте javascript для подключения к форме.

<div class='modal-body'>
    <form id="modal-form" accept-charset="UTF-8" action="/tagging" data-remote="true" method="post">
        <input name="something" value="Some value" />
    </form>
  </div>

<div class='modal-footer'>
    <a id="modal-form-submit" class='btn btn-primary' href="#">Submit</a>
</div>

<script>
  $('#modal-form-submit').on('click', function(e){
    // We don't want this to act as a link so cancel the link action
    e.preventDefault();

    // Find form and submit it
    $('#modal-form').submit();
  });
</script>

Что касается <a class='close' data-dismiss='modal'>×</a>, который должен ссылаться на главную страницу, почему бы просто не удалить data-dismiss='modal' и заставить его действовать как обычная ссылка, используя стандартный href='home.html'.

Вот еще один код, указывающий вам в правильном направлении использования AJAX для отправки формы:

// Since we want both pressing 'Enter' and clicking the button to work
// We'll subscribe to the submit event, which is triggered by both

$('#modal-form').on('submit', function(){

  //Serialize the form and post it to the server
  $.post("/yourReceivingPage", $(this).serialize(), function(){

    // When this executes, we know the form was submitted

    // To give some time for the animation, 
    // let add a delay of 200 ms before the redirect
    var delay = 200;
    setTimeout(function(){
      window.location.href = 'successUrl.html';
    }, delay);

    // Hide the modal
    $("#my-modal").modal('hide');

  });

  // Stop the normal form submission
  return false;
});

Ответ 2

Чтобы получить команду отправить, поместите ее в форму.

<div class="modal">
    <form id="modal-form" action="/tagging" data-remote="true" method="post">
        <div class="modal-header">
            <a class="close" data-dismiss="modal">×</a>
            <h3>A Modal Form</h3>
        </div>
        <div class="modal-body">
            <input name="something" value="Some value" />
        </div>
        <div class="modal-footer">
            <a href="#" class="btn" data-dismiss="modal">Cancel</a>
            <input type="submit" value="Save" class="btn btn-primary" />
        </div>
    </form>
</div>

Однако это добавляет неожиданный запас в нижней части модального. Bootstrap 2.0.2 представил класс modal-form, чтобы исправить это, или вы можете исправить его самостоятельно с помощью определения стиля, например:

.modal > form {
    margin-bottom: 0;
}

Для ссылки на другую страницу при закрытии модального я иду вместе с TheShellfishMeme

Что касается ×, который должен связываться с главной страницей, почему бы просто не удалить data-reject = 'modal' и заставить его действовать как обычная ссылка, используя стандартный href= 'home.html'.

Ответ 3

С HTML5 вы можете иметь что-то вроде этого:

<div class="modal" id="myModal">
  <div class="modal-header">
    <a class="close" data-dismiss="modal">×</a>
    <h3>Add Tags</h3>
  </div>

  <div class="modal-body">
    <form id="my_form" accept-charset="UTF-8" action="/tagging" data-remote="true" method="post">
        <div style="margin:0;padding:0;display:inline">
          <input name="utf8" type="hidden" value="&#x2713;" />
          <input name="authenticity_token" type="hidden" value="mCNvbvoPFWhD7SoJm9FPDh+BcRvCG3d16P+oOFACPuc=" />
        </div>
        <input id="tags_string" name="tags_string" type="text" value="luca" />
        <input id="id" name="id" type="hidden" value="4f1c95fd1d41c80ff200067f" />
    </form>
  </div>

  <div class="modal-footer">
    <div class="btn btn-primary"><input name="commit" type="submit" value="Add tag" form="my_form" /></div>
  </div>
</div>

Это называется HTML5 связанным с формой элементом, если вам нужно поддерживать все браузеры + старые, тогда вам нужно пойти с JavaScript, но вы можете использовать JavaScript как резерв:)

Ответ 4

Проблема отправки формы лежит в собственной загрузочной библиотеке JS-модема (bootstrap-modal.js). Базисное событие отправки предотвращается из-за строки # 204: ev.preventDefault (почему?).

Моим решением было добавить:

if(!$(e.target).parents('form'))
   e.preventDefault();

Однако я не знаю, какие проблемы возникнет.

Ответ 5

FYI Вы можете сделать следующее (написанное в нефрите):

.modal.hide.fadel
  form.modal-form
    .modal-header
        button.close type='button' data-dismiss="modal" x
        h3= t 'translation'
    .modal-body
        p hello
    .modal-footer
        button.btn data-dismiss="modal" href="#" = t 'close'
        a.btn.btn-primary data-dismiss="modal" data-remote="true" href="#"= t 'form.submit'