Несколько кнопок отправки в форме HTML - PullRequest
245 голосов
/ 01 августа 2008

Допустим, вы создаете мастера в форме HTML. Одна кнопка возвращается назад, а другая - вперед. Поскольку кнопка back появляется первой в разметке, когда вы нажимаете Enter, она будет использовать эту кнопку для отправки формы.

Пример:

<form>
  <!-- put your cursor in this field and press Enter -->
  <input type="text" name="field1" />

  <!-- This is the button that will submit -->
  <input type="submit" name="prev" value="Previous Page" />

  <!-- But this is the button that I WANT to submit -->
  <input type="submit" name="next" value="Next Page" />
</form>

Я хотел бы решить, какая кнопка используется для отправки формы, когда пользователь нажимает Enter. Таким образом, когда вы нажимаете Enter, мастер переходит на следующую страницу, а не на предыдущую. Вы должны использовать tabindex, чтобы сделать это?

Ответы [ 23 ]

0 голосов
/ 09 января 2018

Я решил очень похожую проблему следующим образом:

  1. если javascript включено (в большинстве случаев в настоящее время), то все кнопки отправки " ухудшены " для кнопок при загрузке страницы через javascript (jquery). События нажатия на кнопках типа " ухудшено " обрабатываются также с помощью javascript.

  2. , если javascript не включен, то форма подается в браузер с несколькими кнопками отправки. В этом случае, нажав Enter на textfield в форме, вы отправите форму с первой кнопкой вместо по умолчанию , но, по крайней мере, форму можно использовать: вы можете отправить как пред и следующие кнопки.

рабочий пример:

<html>
    <head>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
    </head>
    <body>
    <form action="http://httpbin.org/post" method="post">
    If javascript is disabled, then you CAN submit the form with button1, button2 or button3.
    If you press enter on a text field, then the form is submitted with the first submit button.

    If javascript is enabled, then the submit typed buttons without the 'defaultSubmitButton'
    style are converted to button typed buttons.

    If you press enter on a text field, then the form is submitted with the only submit button
    (the one with class defaultSubmitButton)
    If you click on any other button in the form, then the form is submitted with that button's
    value.
    <br />
    <input type="text" name="text1" ></input>
    <button type="submit" name="action" value="button1" >button 1</button>
    <br />
    <input type="text" name="text2" ></input>
    <button type="submit" name="action" value="button2" >button 2</button>
    <br />
    <input type="text" name="text3" ></input>
    <button class="defaultSubmitButton" type="submit" name="action" value="button3" >default button</button>
    </form>
    <script>
    $(document).ready(function(){

    /* change submit typed buttons without the 'defaultSubmitButton' style to button typed buttons */
    $('form button[type=submit]').not('.defaultSubmitButton').each(function(){
        $(this).attr('type', 'button');
    });

    /* clicking on button typed buttons results in:
       1. setting the form's submit button's value to the clicked button's value,
       2. clicking on the form's submit button */
    $('form button[type=button]').click(function( event ){
        var form = event.target.closest('form');
        var submit = $("button[type='submit']",form).first();
        submit.val(event.target.value);
        submit.click();
    });

    });
    </script>
    </body>
    </html>
0 голосов
/ 29 сентября 2017

Попробуйте это ..!

<form>
  <input type="text" name="Name" />
  <!-- Enter the value -->

  <input type="button" name="prev" value="Previous Page" />
  <!-- This is the button that will submit -->
  <input type="submit" name="next" value="Next Page" />
  <!-- But this is the button that I WANT to submit -->
</form>
0 голосов
/ 05 августа 2008

Используя приведенный вами пример:

<form>
<input type="text" name="field1" /><!-- put your cursor in this field and press Enter -->
<input type="submit" name="prev" value="Previous Page" /> <!-- This is the button that will submit -->
<input type="submit" name="next" value="Next Page" /> <!-- But this is the button that I WANT to submit -->
</form>

Если вы нажмете «Предыдущая страница», будет отправлено только значение «предыдущая». Если вы нажмете «Следующая страница», будет отправлено только значение «Далее».

Если, однако, вы нажмете ввод где-нибудь в форме, ни "предыдущая", ни "следующая" не будут отправлены.

Таким образом, используя псевдокод, вы можете сделать следующее:

If "prev" submitted then
    Previous Page was click
Else If "next" submitted then
    Next Page was click
Else
    No button was click
...