1

I have a simple dropdown menu and I would like to reload the page in order to submit a value via PHP $_POST WITHOUT clicking a submit button. Could I do this with javascript? if so, how?

lucasnadalutti
  • 5,818
  • 1
  • 28
  • 48
user2799603
  • 873
  • 3
  • 13
  • 19

4 Answers4

4

AJAX is the answer. If you have jQuery in your page, use something like:

$("#mySelectBox").change(function() {
    var selected = $(this).val(); //here you have the value of the selected option

    $.ajax({
        type: "post",
        url: "myscript.php",
        data: { value : selected } //this value will be accessible in your script via $_POST["value"]
    });
});

EDIT

If you REALLY want to reload the page, although this seems a bit ugly since it might be uncomfortable for the user to select something in a dropdown list and having the page reloaded, jQuery can also make it very easy to do:

$("#mySelectBox").change(function() {
    $("#myForm").submit();
}
lucasnadalutti
  • 5,818
  • 1
  • 28
  • 48
  • OP says "I would like to reload the page". While what you have is certainly more of the "modern" way to do it (and what I would suggest if starting from scratch), the OP may have a reason for wanting the reload. – Patrick Q Feb 21 '14 at 20:11
  • Actually I'm going to try to use this instead. I'm not very familiar with javascript. Where do i place this jquery script in my webpage? – user2799603 Feb 21 '14 at 21:05
  • I usually open a – lucasnadalutti Feb 21 '14 at 21:10
  • Also, note that I assumed that your form id is "myForm" and your select box's id is "mySelectBox" ;) – lucasnadalutti Feb 21 '14 at 21:12
3

You'll want something along the lines of this…

<form id="myForm" name="myForm" method="POST">
    <select id="mySelect" name="mySelect" onchange="document.getElementById('myForm').submit();">
        <option value="optionOne">Option One</option>
        <option value="optionTwo">Option Two</option>
    </select>
</form>
Patrick Q
  • 6,373
  • 2
  • 25
  • 34
3

made a jsfiddle http://jsfiddle.net/9p7nc/

<form action="test.php" method="POST">
<select name="value" id="value" onchange="this.form.submit()">
    <option value="blue">blue</option>
    <option value="green">green</option>
    <option value="red">red</option>
    <option value="yellow">yellow</option>
</select>
</form>
Venkat Reddy
  • 1,046
  • 1
  • 8
  • 13
2

If you use jQuery you could do something like this:

<script type="text/javascript">

$(function() {
   $('#yourSelect').change(function(){
      $('#hiddenSubmitButton').click();
   })
});

</script>
anders
  • 202
  • 1
  • 3