TransWikia.com

Posting values of input fields outside form tag containing submit button

Stack Overflow Asked by Kuwir Singh on August 11, 2020

I have 3 input fields which are not inside a form tag. I cannot add them inside the form because the three input fields are at different locations on the same page.

I want to post input values outside form tag as well when i press submit button. How can i do that?

<input input type="text" id="elecr"  value="2" name="electricity"></input>
<input input type="text" id="3wheel"  value="3" name="threewheel"></input>
<input input type="text" id="4wheel"  value="2" name="fourwheel"></input>

<form action="/savedata" method="post">
2Wheeler: <input type="text" id="2wheeler"  value="0" name="twowheeler"/><br><br>
<input type="submit" />
</form>

2 Answers

Just store the values of all the input fields through jquery and submit your form through ajax on the click of your submit button.

$('form').submit(function(event) {

    // get the form data
    // there are many ways to get this data using jQuery (you can use the class or id also)
    var formData = {
        'electricity'  : $('input[name=electricity]').val(),
        'threewheel'   : $('input[name=threewheel]').val(),
        'fourwheel'    : $('input[name=fourwheel]').val(),
        'twowheeler'   : $('input[name=twowheeler]').val(),
    };

    // process the form
    $.ajax({
        type        : 'POST', // define the type of HTTP verb we want to use (POST for our form)
        url         : 'savedata.php', // the url where we want to POST
        data        : formData, // our data object
        dataType    : 'json', // what type of data do we expect back from the server
        encode      : true
    })

you are able to log and also able to error handling in your jquery.

Answered by Emraan Khalid on August 11, 2020

  1. Write javascript to handle submit event
  2. On submit event append your input with form data
  3. Submit

For reference please refer Adding POST parameters before submit

$( 'form' ).submit(function ( e ) {
    var data;

    data = new FormData();
    data.append( 'electricity', $('#elecr').val());
    data.append( 'threewheel', $('#3wheel').val());
    data.append( 'fourwheel', $('#4wheel').val());

    $.ajax({
        url: 'savedata.php',
        data: data,
        processData: false,
        type: 'POST',
        success: function ( data ) {
            alert( data );
        }
    });

    e.preventDefault();
});

Answered by Ketan Vekariya on August 11, 2020

Add your own answers!

Ask a Question

Get help from others!

© 2024 TransWikia.com. All rights reserved. Sites we Love: PCI Database, UKBizDB, Menu Kuliner, Sharing RPP