Cyril Duchon-Doris
Cyril Duchon-Doris

Reputation: 13949

Javascript - remove duplicate entries

I am trying to code a workaround for this bug I have with the gem nested_form. No knowledge of ruby/rails is required, it's all gonna be about javascript.

So in a nutshell, when my page reloads, I have some duplicate fields with the same model ID (in the value attribute of hidden inputs).

EDIT : added a non-duplicated input with value 50, that should not be modified

<tbody class="echange fields>
   ...
   <input id="etude_echanges_attributes_0_id" type="hidden" name="etude[echanges_attributes][0][id]" value="42">
</tbody>
<tbody class="echange fields>
  ...
  <input id="etude_echanges_attributes_1_id" type="hidden" name="etude[echanges_attributes][1][id]" value="42">
</tbody>
<tbody class="echange fields>
  ...
  <input id="etude_echanges_attributes_2_id" type="hidden" name="etude[echanges_attributes][1][id]" value="50">
</tbody>

The 2 first inputs have value 42. Only the last one is the good one, the first one is a duplicate. So basically I would need a code that scans for all id=".*attributes_x_id" and their value, and only keep the last one.

So in the example I gave above, the javascript should detect that ...

<input id="etude_echanges_attributes_0_id" ... value="42">
<input id="etude_echanges_attributes_1_id" ... value="42">

...have the same value of 42, which means they are duplicates

Then it will remove all but the last one. Also the following should not be modified because it's the only one with model ID value 50

<input id="etude_echanges_attributes_2_id" ... value="50">

EDIT : the parameters that can change are

(note 42 and 50 are just examples, the real ones are MongoDB IDs, that look like 5470b5075374611500040000)

What I want to do :

  1. Find <input> that correspond to duplicates of the same instance model (see above)
  2. Process all but the last one doing :
  3. extract echanges from _echanges_attributes_
  4. singularize it so it becomes echange
  5. Find the parent by its class "echange fields"
  6. Remove this element from the DOM

For now the step that is a problem for me is step n°1. I don't know if it's posible to do it with a simple jquery/css selector ?

Upvotes: 0

Views: 713

Answers (1)

Joseph
Joseph

Reputation: 119847

Well, you could do this in jQuery:

$('input[id^="etude_echanges_attributes"][value="42"]:not(:last)').remove();

We match the id to ensure we get the right <input>s, and not just any <input>. Since id has a variable value, we cannot use #. So instead we use the attribute selector to match the prefixed value. Also threw in value in the selector.

Upvotes: 1

Related Questions