doutun1362 2017-12-27 00:26
浏览 78
已采纳

如何在html中使用几个按钮为我的网站设置值,然后使用一个提交所有数据的按钮?

I'm looking to have several buttons in my php website that set different values based on the button selected and then have the final button set a value and then submit all of these to the next php page. So here I have two sets of buttons that need to be set inside of a form:

<form id="formUploadFile"  action="<?php echo $uploadHandler ?>" enctype="multipart/form-data" method="post" > 
    <p> 
        <input type="hidden" name="MAX_FILE_SIZE" value="<?php echo $max_file_size ?>"> 
    </p> 

    <p align="left"> 
        <label for="file" >First, Choose your image!</label> 
        <input type="file" name="files[]"  /> 
    </p> 

    <p>
        <h5>Would you like to use colored pencils or paint?</h5>
        <div class="btn-group">
            <button class="btn btn-primary" name="ToolChoice" value="0">Colored Pencils</button>
            <button class="btn btn-primary" name="ToolChoice" value="1">Paint</button>
          </div>
    </p>
    <p class="text-center"> 
        <h5>Then, Choose your Difficulty!</h5>
            <div class="btn-group">
            <button type="submit" class="btn btn-success" name="DifficultyChoice" value="0" onclick="loadingCircle()">Kids</button>
            <button type="submit" class="btn btn-success" name="DifficultyChoice" value="1" onclick="loadingCircle()">Novice</button>
            <button type="submit" class="btn btn-success" name="DifficultyChoice" value="2" onclick="loadingCircle()">Intermediate</button>
            <button type="submit" class="btn btn-success" name="DifficultyChoice" value="3" onclick="loadingCircle()">Advanced</button>
          </div>

    </p> 

    </form>   

I want the user to first choose their "ToolChoice" and then choose their "DifficultyChoice" and to have both values posted to the $uploadHandler. However, as written, only the "DifficultyChoice is being sent. On the php end I'm just using

$difficulty=$_POST['DifficultyChoice'];
$toolChoice=$_POST['ToolChoice'];  

I understand this is because I'm not using submit for the toolchoice, but I do not want to run the php $uploadHandler for each of these values separately. Rather, I need both set and sent at the same time.

Any help is appreciated!

  • 写回答

2条回答 默认 最新

  • dongzai3917 2017-12-27 01:00
    关注

    Use javscript for the handling of the submit event. The storing of the program state can be done in various ways. In this example I used two hidden fields to store the values:

    <input type="hidden" name="DifficultyChoice" id="hiddDiff" value="-1" />
    <input type="hidden" name="toolChoice" id="hiddTool" value="-1" />
    

    I made two functions changeDifficulty and changeTools which are being passed an int and they set the values of the hidden fields as well.

    Hidden fields are used because they have a name which will be passed to the receiving PHP file. So you don't have to use names on each button. Instead let javascript do it for you with two functions and two hidden fields:

    EDIT: I replaced the original answer for a working example since the OP asked for the receiving server side as well.

    The program consists of two PHP files a_test.php and b_tesp.php, and one javascript file a_test.js. They should be all located in the same folder for this example to work.

    Program sequence: a_test.php will send POST data to b_test.php using a_test.js. b_test.php will receive the data and try to validate it. If everything is ok the image will be uploaded, otherwise you will see an error message.

    Here is the code:

    File a_test.php:

    <!DOCTYPE html>
    <html>
    <head>
    <title>Title of the document</title>
    <script src="a_test.js"></script>
    </head>
    
    <body>
    <form id="formUploadFile" name="formUploadFile" action="b_test.php" enctype="multipart/form-data" method="post" > 
    
        <input type="hidden" name="MAX_FILE_SIZE" value="<?php echo $max_file_size ?>">
    
        <p align="left"> 
        <label for="file" >First, Choose your image!</label> 
        <input type="file" name="img_1"  /> 
        </p> 
    
        <h5>Would you like to use colored pencils or paint?</h5>
        <div class="btn-group">
          <input type="button" class="btn btn-primary" value="Colored Pencils" onclick="changeTools(0)" />
          <input type="button" class="btn btn-primary" value="Paint" onclick="changeTools(1)" />
        </div>
    
        <h5>Then, Choose your Difficulty!</h5>
        <div class="btn-group">
          <input type="button" class="btn btn-success" value="Kids" onclick= "changeDifficulty(0)" />
          <input type="button" class="btn btn-success" value="Novice" onclick="changeDifficulty(1)" />
          <input type="button" class="btn btn-success" value="Intermediate" onclick="changeDifficulty(2)" />
          <input type="button" class="btn btn-success" value="Advanced" onclick="changeDifficulty(3)" />
       </div>
    
       <input type="hidden" name="difficultyChoice" id="hiddDiff" value="-1" />
       <input type="hidden" name="toolChoice" id="hiddTool" value="-1" />
    </form>
    </body>
    
    </html>
    

    File a_test.js:

    function changeDifficulty(number)
    {
       var toolChoice = parseInt(document.getElementById('hiddTool').value)
       var difficulty = document.getElementById('hiddDiff');
       var form = document.getElementById('formUploadFile');
       difficulty.value = number;
    
       // if the toolChoice is set
       if(toolChoice != -1)
       {
          // Show the values, for testing purposes
          console.log("Tools: " + toolChoice + " Difficulty: " + difficulty.value);
          form.submit();
       }
    }
    
    function changeTools(number)
    {
       var difficulty = parseInt(document.getElementById('hiddDiff').value)
       var toolChoice = document.getElementById('hiddTool');
       var form = document.getElementById('formUploadFile');
       toolChoice.value = number;
    
       // If the difficulty is set
       if(difficulty != -1)
       {
          console.log("Tools: " + toolChoice.value + " Difficulty: " + difficulty);
          form.submit();
       }
    }
    

    File b_test.php:

    <?php
    
    // make a function to check if `int` so you don't have to retype for each variable
    function checkIfInt($var)
    {
        // Here we use a fix to let `0` also be validated as `int`
        if (filter_var($var, FILTER_VALIDATE_INT) || filter_var($var, FILTER_VALIDATE_INT) === 0)
        {
             return true;
        }
        else
        {
            return false;
        }
    }
    
    
    function checkImageValidityAndUpload()
    {
        // Check if file was uploaded without errors
        if($_FILES["img_1"]["error"] == 0)
        {
           // allowed image types
           $allowed = array("jpg" => "image/jpg", "jpeg" => "image/jpeg", "gif" => "image/gif", "png" => "image/png");
           // some (incoming) file properties
           $filename = $_FILES["img_1"]["name"];
           $filetype = $_FILES["img_1"]["type"];
           $filesize = $_FILES["img_1"]["size"];
    
           // Verify file extension (here we are comparing the file extension to the keys of $allowed array)
           $ext = pathinfo($filename, PATHINFO_EXTENSION);
           if(!array_key_exists($ext, $allowed))
           {
              echo "Error: Please select a valid file format.<br/>";
              return false;
           }
    
           // Verify file size - 5MB maximum (5MB is example, you can set anything)
           $maxsize = 5 * 1024 * 1024;
           if($filesize > $maxsize) 
           {
              echo "Error: File size is larger than the allowed limit.<br/>";
              return false;
           }
    
           // Verify MYME type of the file (here we are comparing the file MYME type to the $allowed array values)
           if(in_array($filetype, $allowed))
           {
              // Check whether file exists before uploading it (upload/ is example folder, change to your image folder)
              if(file_exists("upload/" . $_FILES["img_1"]["name"]))
              {
                  echo $_FILES["img_1"]["name"] . " already exists.<br/>";
                  return false;
              }
              else
              {
                  move_uploaded_file($_FILES["img_1"]["tmp_name"], "upload/" . $_FILES["img_1"]["name"]);
                  return true;
              } 
          }
          else
          {
              echo "Error: There was a problem uploading your file. Please try again.<br/>";
              return false;
          }
       }
       else
       {
          echo "Error: " . $_FILES["img_1"]["error"]."<br/>";
          return false;
       }
    }
    
    
    
    // MAIN program starts here - Check if the form was submitted
    if($_SERVER["REQUEST_METHOD"] == "POST")
    {
       $tools = array("Colored Pencils", "Paint");
       $difficulties = array("Kids", "Novice", "Intermediate", "Advanced");
    
       // check if all needed variables are set and valid, and if the image is valid and uploaded successfully
       if(isset($_POST['difficultyChoice']) && isset($_POST['toolChoice']) && isset($_FILES['img_1']) && 
          checkIfInt($_POST['difficultyChoice']) && checkIfInt($_POST['toolChoice']) && 
          checkImageValidityAndUpload())
       {
          $diff = intval($_POST['difficultyChoice']);
          $tool = intval($_POST['toolChoice']);
          echo 'Tools choice: '.$tools[$tool].' Difficulty choice: '.$difficulties[$diff].'<br/>';
          echo 'image has been uploaded successfully';
          // do something
      }
      else
      {
          echo 'Something went wrong. Program will not continue';
          die();
      }
    }
    else
    {
       echo 'There was no POST request.';
       die();
    }
    ?>
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 不小心不正规的开发公司导致不给我们y码,
  • ¥15 我的代码无法在vc++中运行呀,错误很多
  • ¥50 求一个win系统下运行的可自动抓取arm64架构deb安装包和其依赖包的软件。
  • ¥60 fail to initialize keyboard hotkeys through kernel.0000000000
  • ¥30 ppOCRLabel导出识别结果失败
  • ¥15 Centos7 / PETGEM
  • ¥15 csmar数据进行spss描述性统计分析
  • ¥15 各位请问平行检验趋势图这样要怎么调整?说标准差差异太大了
  • ¥15 delphi webbrowser组件网页下拉菜单自动选择问题
  • ¥15 wpf界面一直接收PLC给过来的信号,导致UI界面操作起来会卡顿