0

I think this should be really easy, but I can't seem to find an answer.

I'm using rails 4 and jquery to identify when one of multiple select boxes is altered on a page, and if so, perform some action.

This is the relevant code in my application.js file:

$('body').on('change', 'select',function(){
      *action*
});

The issue I'm having is that this code will pick up a select box change on any page within my application. How do I set things up so that it will only pick up select box changes on a specific page?

Do I do this by creating a new .js file which is specific to my view? If so, how do the file naming conventions work?

user3711600
  • 853
  • 3
  • 12
  • 27

4 Answers4

1

there are several ways to do this, but the cleanest seems to be this : add a class to the select you wish to be handled by this function. Let's call this class handlethis. The change your jQuery selector accordingly.

You HTML would look like :

<select name="myselect" id="myselect" class="handlethis">
    <option value="1">option 1</option>
    <option value="2">option 2</option>
    ...
</select>

and the JS :

$('body').on('change', 'select.handlethis',function(){
  *action*
});
Laurent S.
  • 6,816
  • 2
  • 28
  • 40
0

I have an example for you to understand this.I hope it will be helpful to you.

<!DOCTYPE html>
<html>
<head>
    <script type="text/javascript" src="http://code.jquery.com/jquery-1.7.2.js"></script>
    <script type="text/javascript">
    $(function(){
        $('select').change(function(){ // when one changes
            $('select').val( $(this).val() ) // they all change
        })
    })
    </script>
    <style type="text/css">

    </style>
    <title>HELLO</title>
</head>
<body>
(top of the page)
<select>
  <option value="big1">1big1</option>
  <option value="big2">2big2</option>
</select>
   other content here...
   (bottom of the page)
<select>
  <option value="big1">big1</option>
  <option value="big2">big2</option>
</select>
</body>
</html>

If it is helpful to you then please vote it up.

gargAman
  • 111
  • 1
  • 5
0

Provide id for the select box.and use that id for call function

0

To pick only the select you want, just add an id or a class to the select, your code should look like this :

HTML :

<select id="selector" name="selector">
    ...
</select>

JS :

$('#selector').change(function() {
    *action*
});

The change() function is just a shortcut for on('change').

You can add a new JS file specific to your view, for best practice about it, read this post :

Best way to add page specific javascript in a Rails 3 app?

Community
  • 1
  • 1
Stark
  • 1