L
L
Lesha Fedoseev2014-02-01 21:53:15
JavaScript
Lesha Fedoseev, 2014-02-01 21:53:15

How to add new object to jquery array after ajax insert?

The rails app page has a form with a set of checkboxes that act like radio buttons. The script looks like this:

window.$covers_set = $('#building_views').find("input[id$='is_cover']")
$covers_set.click( ->
  $covers_set.not(this).removeAttr('checked')
)

It works fine with elements that have been loaded on the page. But on the same page there is a form that uploads files via ajax ( gem jquery-fileupload-rails ) and adds new form elements, which also have checkboxes that need to be processed. Question: how can I add them to the array $covers_set?

I'm pretty green on js and the first thing that came to my mind was adding a js script via ajax along with a new form element that pushes a new checkbox into an array:
# rails хелпер
= javascript_tag "$covers_set.add($('#тут_id_нового_чек-бокса'));"

But I understand it needs to be initialized. How to do it?
Or am I thinking in the wrong direction?

Answer the question

In order to leave comments, you need to log in

2 answer(s)
I
itspers, 2014-02-01
@alexfedoseev

$('#building_views').on("click", "input[id$='is_cover']", function(){
  $covers_set.not(this).removeAttr('checked');
});

provided that #building_views is not touched by Ajax.
If touches - then the parent is taller or the document itself.
api.jquery.com/on

D
Danny Chernyavsky, 2014-02-01
@DEHisOK

I support the @itspers option .
I don't know how things are with on, but in the past, using live was considered not the best practice. Alternative is to update $coversSet onSuccess ajax. Those. something like this:

var $coversSet = $('#building_views').find("input[id$='is_cover']");

$.ajax({
    // url, data, type, etc
    success : function(result) {
         $coversSet = $('#building_views').find("input[id$='is_cover']");
    }
});

If this is some kind of widget and there is no explicit $.ajax(), you need to choose the appropriate. hook.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question