简体   繁体   中英

jquery select box change on a specific page

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?

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*
});

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.

提供选择框的ID,并将该ID用于呼叫功能

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?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM