Code Cowboy
Code Cowboy

Reputation: 53

Submit dropdown form upon changing selected option

So I have a dropdown menu with 'Next' and 'Prev' (previous) buttons. I would like it so upon pressing next or prev it would also submit the dropdown choice.

<input type="button" id="change2" value="prev" />
<select id="Questions">
  <option value="QA">QUESTION A</option>
  <option value="QB">QUESTION B</option>
  <option value="QC">QUESTION C</option>
  <option value="QD">QUESTION D</option>
</select>
<input type="button" id="change" value="next" />

And here is the JQuery for it:

$(window).load(function(){
    var dd = $('#Questions'),
        max_len = dd.find('option').length;

    $('#change').click(function () {
        var x = dd.find('option:selected').index();
        if (max_len == x + 1) {
            x = -1;
        }
        dd.find('option').eq(x + 1).prop('selected', true);
    });
    $('#change2').click(function () {
        var x = dd.find('option:selected').index();
            if (max_len == x + 1) {
                x = -1;
            }
        dd.find('option').eq(x - 1).prop('selected', true);
    })
});

How can I make it so that when I click next or prev it submits the form too?

Thanks

Upvotes: 0

Views: 627

Answers (3)

Lesley
Lesley

Reputation: 1395

You can submit the form using jQuery. Check the top answer on this question for details. Assuming you have an action attribute set on the form, something like this might be all you need:

$('#change').click(function () {
    // your other logic here
    $('form').submit();
});

Upvotes: 1

Ivan Modric
Ivan Modric

Reputation: 619

You could use $.ajax();.

A very general solution might look something like this:

$(document).ready(function() {
    $("#change, #change2").on('change', function(){
        $.ajax({
            url: 'sendTheDataHere',
            type: 'POST',
            data:  {keyname:$('#Questions option:selected').val()},
            success: function () {},
            error: function () {}
        });
    });
});

Upvotes: 1

Vasim Shaikh
Vasim Shaikh

Reputation: 4542

<input type="button" id="change2" value="prev" onclick="changeS()"/>
<select id="Questions">
  <option value="QA">QUESTION A</option>
  <option value="QB">QUESTION B</option>
  <option value="QC">QUESTION C</option>
  <option value="QD">QUESTION D</option>
</select>
<input type="button" id="change" value="next" onclick="changeS()"/>

JS Code

<script>
function changeS() {
/* document.getElementById('change').getElementsByTagName('option')[1].selected = true;*/
var r=document.getElementById('change').selectedIndex+1;
document.getElementById('change').getElementsByTagName('option')[r].selected = true;
}
</script>

Upvotes: 0

Related Questions