Abramodj
Abramodj

Reputation: 5879

Rails - Handle multiple dynamic fields with ajax

I have a model foo in my rails app, and in the index page all the foos are listed in a table. Each foo has 2 integer properties: quarto and jesolo.

enter image description here

I'm giving different ids to the html number fields, in the following way:

foo #1

1st field: foo1_quarto

2st field: foo1_jesolo

foo #2

1st field: foo2_quarto

2st field: foo2_jesolo

ecc...

At the moment I'm using the following ajax code (written in coffee script) to make the user input on foo1_quarto being reflected also in foo1_jesolo:

$("#foo1_quarto").keyup ->
    a = parseInt document.getElementById("foo_quarto").value
    $("#foo1_jesolo").val a

But now I need to serialize this. I don't know in advance how many food there will be, and I'd like to have a piece of ajax code that covers all of them

Upvotes: 0

Views: 128

Answers (1)

Trip
Trip

Reputation: 27114

Not sure I understand your english, but couldn't you collect all the inputs and serialize them like so ?

$("input").serialize ->

So in an AJAX call it would be :

$.ajax '/',
    type: 'POST'
    data: $("#my_form input").serialize ->
    dataType: 'script' error: (jqXHR, textStatus, errorThrown) ->
        $('body').append "AJAX Error: #{textStatus}"
    success: (data, textStatus, jqXHR) ->
        $('body').append "Successful AJAX call: #{data}"

Also, I'd personally stray away from using unique ID's for your keyup method. In this way, you wouldn't have to write the same thing for every single item.

Instead I would make each one share a common class .foo_input and/or .other_foo, and write it like so :

$(".foo_input").keyup ->
    $(this).sibling(".other_foo").val $(this).value

But ideally, you would use one class and use jQuery selectors to get to it. Not sure how your HTML is set up.

Upvotes: 1

Related Questions