Multiple Submit Buttons On Form [duplicate]

2019-07-16 23:52发布

Possible Duplicate:
Multiple submit buttons in an HTML form

I wonder whether someone may be able to help me please.

I've put together this form which, as you can see at the bottom of the page, allows a user to add and delete image files associated with the main record.

The problem that I have is that there are multiple buttons that have a 'Submit' action behind them, namely: 'Upload this File', 'Delete Selected Image', 'View Selected Image', and 'Submit' and because of this, immaterial of the button I use, the only action performed is a complete record submission.

Could someone perhaps tell me please how I can make sure that the 'Submit' action behind each button works independently of each other.

Many thanks and kind regards

4条回答
Melony?
2楼-- · 2019-07-17 00:13

If you put every button in a separate <form></form> it should be fine. Is that possible in your current setup?

Assuming you can not do the above:

Form:

<form name='myForm'>
<input type='hidden' id='hiddenSubmit' name='hiddenSubmit' value=''/>
//lots of fields here
<input type='button' name='action1' onclick='changeHiddenSubmit(this.name)'/>
//some more fields
<input type='button' name='action2' onclick='changeHiddenSubmit(this.name)'/>

//etc...
</form>

JS:

<script>
   function changeHiddenSubmit(name){
       document.getElementById('hiddenSubmit').value = name;
       document.myForm.submit();

    }
</script>

PHP:

<?php
  switch($_POST['hiddenSubmit'){
    case 'action1':

    break;
     case 'action2':

    break;
 }

?>
查看更多
Juvenile、少年°
3楼-- · 2019-07-17 00:17

If you give your submit buttons a unique name, you can tell on the server side which one of them was clicked (resulting in the submission of the form).

Try this example:

<?php
    if (isset($_POST['b1'])) {
        echo 'Button 1 was pressed.';
    }
    if (isset($_POST['b2'])) {
        echo 'Button 2 was pressed.';
    }
    if (isset($_POST['b3'])) {
        echo 'Button 3 was pressed.';
    }
?>
<form action="" method="post">
<input type="submit" name="b1" />
<input type="submit" name="b2" />
<input type="submit" name="b3" />
</form>
查看更多
爷、活的狠高调
4楼-- · 2019-07-17 00:27
叼着烟拽天下
5楼-- · 2019-07-17 00:37

You don't need to use separate form for each button. You can just use different value in the "name" of submit button's. Then on the server you can examine the value of 'form_action'

example :

<input name="form_action[delete]" type="submit" value="Delete">
<input name="form_action[update]" type="submit" value="Update">

Put as manu of these buttons as you want. On the server examine the value of $_POST['form_action']

查看更多
登录 后发表回答