Matthew
Matthew

Reputation: 3956

Input value from different form

I have two forms on my page...

<form method="post" action="">
    <input type="text" name="name" id="name"/>
    <input type="submit" name="form1_submit_pushed"/>
</form>

<form method="post" action="">
    <input type="submit" name="form2_submit_pushed/>
</form>

On my php side I want to be able to know the value of the text input "name" when I push the submit button of the second form. Kind of like....

if(isset($_POST['form2_submit_pushed']))
{
    echo $_POST['name']; //or something else?
}

The reason behind is that first form has a bunch of data that I don't want in the second form submission.

Upvotes: 2

Views: 575

Answers (2)

Matt Browne
Matt Browne

Reputation: 12429

You could do something like this...this code uses jQuery:

<form id="form1" method="post" action="">
    <input type="text" name="name" id="name"/>
    <input type="submit" name="form1_submit_pushed"/>
    <input type="hidden" name="form2_submit_pushed" id="form2_submit_pushed">
</form>

<form id="form2" method="post" action="">
    <input type="submit" name="form2_submit_pushed"/>
</form>

<script>

$('#form2').submit(function(event) {
    //prevent form2 from submitting and submit form1 instead...

    event.preventDefault();

    //before submitting, indicate that the "form2_submit_pushed" button was pushed
    $('#form2_submit_pushed').val(true);
    //submit form1
    $('#form1').submit();
});

</script>

...but why you would want to I don't know. Why not make all the controls part of the same form? HTML is designed to send info from only one form (at a time) to the server...

UPDATE: Sorry, I didn't notice your line where you explain your reason for wanting to do this. If you want more explicit control over what gets sent to the server I recommend using AJAX to submit the form. Look at https://api.jquery.com/serializeArray/ and https://api.jquery.com/jQuery.ajax/

Upvotes: 1

attila
attila

Reputation: 2229

Correct me if I am wrong here, but I beleive normal HTML will only post the inputs from the form you are posting from. One option would be to have a hidden input on the second form which gets updated via javascript during the input's change event.

So, you could do something like this (I don't recommend inline javascript but it should get you in the right direction):

<form method="post" action="">
    <input type="text" name="name" id="name" onchange="document.getElementById('hiddenname').value=this.value"/>
    <input type="submit" name="form1_submit_pushed"/>
</form>

<form method="post" action="">
    <input type="hidden" name="hiddenname" id="hiddenname"/>
    <input type="submit" name="form2_submit_pushed/>
</form>

Then you just need to get it using $_POST['hiddenname'];

Upvotes: 0

Related Questions