views:

63

answers:

2

In the past I have always used a hidden field, and on the submit button onClick event I stuff the list contents (the text of the li elements) into a hidden form field using custom code, and parse it out on the server-side using custom code.

This has always felt like a hack and I was wondering if there is a more modern approach. I'd like to find the most generic approach, but if tooling matters, I'm using JQuery on the client, and Ruby/Sinatra on the server. Maybe turn the list into a JSON object and then consume on the server side?

A: 

It's not clear exactly what aspect of a html <ol><li>...</li>...</ol> list you'd want to pass, but assuming you mean the text contentents of the member <li> tags, then you might do it something like this:

$('ol.selector li')
    .each(function(i) { 
        $("<input name='something-" + i + "'>")
            .val($(this).html())
            .appendTo('form.selector');
    }
};
MightyE
A: 

If you want to as a values sepearated by coma

var values = $.map($('ol li'), function(e,i) { 
  return $(e).html();
});
$('form').append('<input type="hidden" name="field" value="' + 
   values.join(',') + '"/>');

Or you can put it as an array

var inputs = $.map($('ol li'), function(e,i) { 
  return '<input name="field[]" value="' + $(e).html() + '"/>';
});
$('form').append(inputs.join(" "));
jcubic
Thanks. I went with a character a little more "out of the ordinary" instead of a comma in order to avoid issues when there is a comma in the user-entered list items, but used the delimited list.
Jeremy Mullin
If you’ll use the second example you won’t have to worry about your join string appearing in the content. You’ll also be able to access the values as a normal Ruby array in Sinatra using `params[:field]`. (The `[]` part of the field’s name makes this happen automatically for most web frameworks, including Sinatra and Rails.)
Todd Yandell