0

I am trying to build a loop of forms in rails that will create (among else) multiple instances of the following two inputs:

<input class="input-small" id="offer_value" min="0" name="offer[value]" step="any" type="number" />
<input class="input-small" id="total" readonly="readonly" value=""/>

The value of the second one should change with a change in the value of the first one according to the following coffeescript:

$ ->
  $('#offer_value').change ->
    $('#total').val($('#offer_value').val()*2).change();

My problem is that if I give the same id to all (offer_value, total), then the coffeescript hanldes only the first that it finds (giving the same ids sounds wrong anyway).

If I give unique ids (offer_value1, offer_value2,...) then how can I catch them all without writing coffeescripts for all of them?

Panagiotis
  • 401
  • 4
  • 13

1 Answers1

1

With JQuery if you select by Id (# selector) you will get only one element, since Id is supposed to be unique and JQuery will use getElementById

Therefore, select by class (. selector)

Check this answer for more information https://stackoverflow.com/a/8498617/643500.

Edit:

Use the same class for the inputs.

<input class="input-small offer_value" min="0" name="offer[value]" step="any" type="number" />
<input class="input-small" id="total" readonly="readonly" value=""/>

Then for the script

$ ->
  $('.offer_value').keyup ->
    $(this).next().val($(this).val()*2).change();
Community
  • 1
  • 1
Sully
  • 14,672
  • 5
  • 54
  • 79
  • so if I assign a class name to these inputs, I will be able to catch the change of anyone of the offer_value inputs in the loop and change its corresponding total input? – Panagiotis Dec 08 '13 at 09:44
  • Each event will be triggered seperatly. You update the value for the element that kicked the event. So, the .className selector is saying on any element with that class name do what's needed. – Sully Dec 08 '13 at 11:11