简体   繁体   中英

closest tr selection in JQuery select dropdown

Hope someone can advise.

I'm facing small issue trying to add certain data into a select dropdown which is <option> elements that I'm fetching it with Ajax after clicking the check box in same td in a table.

Html:

<td class="col-lg-4"><select name="name[]" class="form-control name"></select>

Now the JS:

$(document).on('click', '.check_box', function(){
            var name = $(this).data('name');
            $.ajax({
                type: 'POST',
                url: '/someactionhere/',
                data:{name:name},
                success: function(data){
                    $(this).closest('tr').find('.name').html(data);
                }
            });

});

I know it's should be real simple but and looks like right to me. So I don't no if something wrong or not.

Any ideas?

Thanks in advance.

In your ajax function, $(this) refers to the ajax function object, not the element that was clicked. To refer to that element, you need to first store it in a variable, like the comments suggest.

 $(document).on('click', '.check_box', function() { var name = $(this).data('name'); let elem = $(this) $.ajax({ method: 'GET', url: 'https://jsonplaceholder.typicode.com/todos/1', data: { name: name }, success: function(data) { elem.closest('tr').find('.name').html("<option>here is the html</option>"); } }); });
 <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <table> <tr> <td class="col-lg-4"> <input type='checkbox' data-name='test' class='check_box' /> <select name="name[]" class="form-control name"> </select> </td> </tr> </table>

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