at.
at.

Reputation: 52540

Auto-submitting HTML select drop-down in Rails

I have a simple drop-down menu using HTML's select tag. The code for the select tag becomes:

<select name="menu_id" id="menu_id">
  <option selected="selected" value="1">Dinner</option>
  <option value="2">Lunch</option>
</select>

In my menu.js.coffee file I have:

$("select#menu_id").change(-> $(this).closest("form").submit())

This becomes menu.js:

(function() {
  $("select#menu_id").change(function() {
    return $(this).closest("form").submit();
  });
}).call(this);

The problem is changing the select menu doesn't submit the form! It doesn't even enter the above menu.js code (I place breakpoints there and it never enters after selecting a menu option).

If I then just copy the inside of the above (function() {, and I paste it into the Firebug or Chrome console, then it runs as expected and changing the menu does in fact submit the form. So how am I supposed to write the coffeescript code in rails to allow forms to be submitted when a select menu is changed?

I'm using Rails 3.2.8.

Upvotes: 1

Views: 2381

Answers (2)

DavidRH
DavidRH

Reputation: 819

Try putting your code inside the $(document).ready () -> block.

$(document).ready () ->
  $("select#menu_id").change(-> $(this).closest("form").submit())

Upvotes: 2

suresh gopal
suresh gopal

Reputation: 3156

document.ready functions use only when page reload occur. you may use separate function and call using onchange.

Example:

    <select name="menu_id" id="menu_id" onchange="callThisFunction()">
    <option selected="selected" value="1">Dinner</option>
    <option value="2">Lunch</option>
    </select>

    <form name="myform"></form>

    function callThisFunction()
    {
      document.forms["myform"].submit();
    }

Upvotes: 0

Related Questions