简体   繁体   中英

Rails 5: show selected value at edit action with JS

In View I have drop-down, where User can be selected:

   <!-- more code above -->
<% for role in user.roles %>
<div class="col-sm-10"><select class="form-control m-b" name="users" id="user_list">
   <option value="<%= user.id %>" data-edit-url="<%= edit_common_role_path(role.id) %>"><%= user.name %></option>

This JS script on select, opens role of selected User by role ID for edit (eg, /common/roles/1/edit )

<script type="text/javascript">
            edit = $('#user_list').change(function() {
            window.location = $(this).find(":selected").data('edit-url');
            });
</script>

How to achieve that when Edit path is opened, in drop-down menu selected User name is shown? At the moment it always get 1st value in list. I'm on Rails 5, Bootstrap. Thank you for any help!

I am not aware of rails. But, can you cross check once if you it is edit-url not data-edit-url .

And also instead of $(this).find(":selected").data('edit-url'); simply use $(this).data('edit-url') .

I have a small working example in Plain HTML and Jquery.

<html>

<head>
<script   src="https://code.jquery.com/jquery-3.1.1.js"   
        integrity="sha256-16cdPddA6VdVInumRGo6IbivbERE8p7CQR3HzTBuELA="   crossorigin="anonymous"></script>    
</head>

<body>

    <select id="url">
        <option value="Please Select">1</option>
        <option value="https://google.com">2</option>        
    </select>

</body>

<script>

    $('#url').change(function(){
                     window.location = $(this).val();
                     });

</script>    


</html>

I hope, it will help.

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