单击辅助按钮时提交表单按钮触发器

时间:2019-08-06 01:05:32

标签: javascript php html forms

我正在尝试获取一个复选框,以触发表单中的提交按钮。基本上,这是一个触摸屏游戏,它使用触摸键盘接收用户的电子邮件。触摸键盘上的Enter按钮可以切换到游戏中。当我在JavaScript中添加document.getElementById("").submit时,将重置所有内容。我尝试解决此问题的方法是在其旁边放置一个按钮,就像“选择加入”类型的交易一样。当您单击按钮时,它将电子邮件地址复制到表单中。但是我仍然需要在表单上单击“提交”按钮,而无需重置站点或不更新表单信息所在的data.txt。

<body>
  <script>
    function myFunction() {
      var x = document.getElementById("name").innerHTML;
      document.getElementById("demo").innerHTML = x;
    }
  </script>
  <span id="name">
<!-- Displaying name input from touch keyboard here -->
  </span>
  <form method="post" class="emailForm" id="demo" name="myForm">
    <input type="text" name="subscriptions" id="formName"><br>
    <input type="submit" name="mySubmit" id="submitBtn">
  </form>

  <div class="roundedB">
    <input onclick="myFunction()" type="checkbox" value="None" id="roundedB" name="Submit" />
    <label for="roundedB"></label>
  </div>
</body>

<?php

if(isset($_POST['subscriptions']))
{
    $data=$_POST['subscriptions'];
    $fp = fopen('data.txt', 'a');
    fwrite($fp, $data);
    fclose($fp);
}
?>

我想要实现的是单击复选按钮,该表格将填写并自动提交到data.txt。网站无法重新加载。

2 个答案:

答案 0 :(得分:1)

Drat-在注意到已接受的答案之前就开始了此操作,但仍会发布,因为它可能会有所帮助。

<?php

    error_reporting( E_ALL );
    ini_set( 'display_errors', 1 );



    if( $_SERVER['REQUEST_METHOD']=='POST' ){
        ob_clean();

        /* This is where you would process the POST request somehow...  */
        $_POST['response']=date( DATE_ATOM );
        $_POST['ip']=$_SERVER['REMOTE_ADDR'];

        /* prepare data for saving */
        $json=json_encode( $_POST );

        /* write to file */
        $file=__DIR__ . '/subscriptions-data.txt';
        file_put_contents( $file, $json . PHP_EOL, FILE_APPEND );

        /* send back a response of some sort to the ajax callback function */
        exit( $json );
    }
?>
<!DOCTYPE html>
<html lang='en'>
    <head>
        <meta charset='utf-8' />
        <title>submit form button trigger when secondary button clicked</title>
        <script>
            document.addEventListener( 'DOMContentLoaded', function(){

                const xhr_callback=function(r){
                    console.info( r );
                };

                const ajax=function(url,payload,callback){
                    let xhr=new XMLHttpRequest();
                        xhr.onreadystatechange=function(){
                            if( this.status==200 && this.readyState==4 )callback( this.response );
                        }
                        xhr.open( 'POST', url, true );
                        xhr.send( payload );                    
                };

                const clickhandler=function(e){
                    if( this.checked ){
                        let payload=new FormData( document.forms.myForm );
                        ajax.call( this, location.href, payload, xhr_callback );
                    }
                };

                document.querySelector('input[type="checkbox"][name="submit"]').addEventListener( 'click', clickhandler );
            });
        </script>       
    </head>
    <body>
        <span id='name'>
            <!-- Displaying name input from touch keyboard here -->
        </span>

        <form method='post' class='emailForm' name='myForm'>
            <input type='text' name='subscriptions' value='geronimo@hotmail.com' />
            <br />
            <input type='submit' />
        </form>

        <div class='roundedB'>
            <input type='checkbox' value='None' name='submit' />
            <label for='roundedB'></label>
        </div>
    </body>
</html>

答案 1 :(得分:0)

您可以尝试使用类似的方法

如您所见,我为此使用了Jquery。您可以触发on change

然后将ajax请求发送到服务器。

$('#myCheck').on('change',function() {
	// ajax request
	alert('Do your action');

});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

Check me <input type="checkbox" id="myCheck">

简单的ajax

$('#myCheck').on('change', function() {
      var data = JSON.stringify({
         email: $('input#email').val()
       });
    $.ajax({
      type: "POST",
      url: "email.php",
      data: data,
      success: function(){
          alert('success');
      },
      error: function(){
          alert('error');
       }
     });
 });
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form id="form1">
  Email: <input type="text" id="email" value="someone@email.com">
</form>

<form id="form2">
  Check me <input type="checkbox" id="myCheck">
</form>

  

由于没有 email.php 文件,因此这会给您错误警报。

     

这是您需要的代码

index.php

$('#roundedB').on('change', function() {
        var email = $('input#subscriptions').val();
        $.ajax({
            type: "POST",
            data: {
                'subscriptions': email
            },
            url: 'send.php',
            success: function (data) {
                alert(data);
            },
            error: function (data) {
                alert(data);
            }
        });
    });
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<body>
<span id="name">
<!-- Displaying name input from touch keyboard here -->
  </span>
<form method="post" class="emailForm" id="demo" name="myForm">
    <label for="subscriptions">Email address</label>
    <input type="text" name="subscriptions" id="subscriptions"><br>
</form>

<div class="roundedB">
    <input type="checkbox" id="roundedB" name="Submit" />
    <label for="roundedB"></label>
</div>
</body>

send.php

<?php
if(isset($_POST['subscriptions']))
{
    $data=$_POST['subscriptions']."\n";
    $fp = fopen('data.txt', 'a');

   if(fwrite($fp, $data)){
        print 'successful';
   }else{
        print 'error';
   }
    fclose($fp);
}