user1961525 user1961525 - 6 months ago 12
Javascript Question

javascript jquery carrying html form POST data

SO I have a form that look similar to

<form action="test.php" id="checksub" method="post">
<div>
<select name="mydropdown">
<option value="buy">buy</option>
<option value="sell">sell</option>
</select>
</div>

autocomplete text input that triggers "checksub"

<input type="submit" id="checksub" name="checksub" style="visibility:hidden">
<input type="submit" id="newsbutton" name="newsbutton">
</form>

<script type="text/javascript">
$('#newbutton').click(function() {
var newaction = "cantfinditems.php";
$("#checksub").prop("action", newaction);
$('#checksub').submit();
});
</script>


Now the submit button is hidden because the autocomplete triggers it anyway, but if the user cant find what they are looking for I want a button that says "cant find what your'e looking for?"
I want this button to have a different action to the form action, ie window.location = cantfinditems.php
but I also want to carry the POST data from the form ie "mydropdown".
Thank you

Answer

Ok, so you need a second button, which calls a JavaScript function. In this function, you do a number of things:

Set the action attribute of the form to your alternate action (e.g. cantfinditems.php)

var newaction = "cantfinditems.php";
$("#form_id").prop("action", newaction);

Submit the form

$('#form_id').submit();

So a full example would be:

<script type="text/javascript">
$('#yourbuttonid').click(function() {
  var newaction = "cantfinditems.php";
  $("#form_id").prop("action", newaction);
  $('#form_id').submit();
});
</script>
Comments