简体   繁体   中英

submit form button trigger when secondary button clicked

I'm trying to get a check box to trigger the submit button in a form. Basically, this is a touch screen game that takes users emails using a touch keyboard. The Enter button on the touch keyboard is what switches into the game. When I add document.getElementById("").submit in the javascript just resets everything. What I've done to try and work around this is to put a button next to it that is like an "opt-in" type of deal. When you click the button it copies the email address into the form. But I still need the submit button on the form to click without resetting the site or not updating the data.txt where the form info goes.

<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);
}
?>

What I want to achieve is to click the check button, the form fills and auto-submits to data.txt. Website does not reload.

Drat - started this before the noticing an accepted answer but will post this anyway as it might help.

<?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>

You can try with something like this

As you can see I used Jquery for that. You can make a trigger on change .

Then to send ajax request to server.

 $('#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"> 

Simple 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> 

This one will give you error in alert, because there is not email.php file.

Here is code you need for that

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);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM