1

First of all, I had a hard time formulating my title, so I'm sorry for that. Anyway, on to my question.

I have a big table of information, where some cells have form fields, specifically two form fields for each row. At the end of the row, I have a "Save" link.

There are multiple rows where each row have their own sets of fields.

I am having a hard time getting these two values stored in a variable, since they are dynamically rendered, I do not have a specific id connected to each .

Therefore I would think that traversing the DOM upwards would yield me my results, but no, so far I am only getting "undefined" (I think I am on the right path, I just can't figure it out).

Take this code as an example;

<td>
<select multiple="multiple" name="paintings">
<option value="The Persistance of Memory" selected="selected">The Persistance of Memory</option>
<option value="The Great Masturbator" selected="selected">The Great Masturbator</option>
<option value="The Scream">The Scream</option>
</select>
</td>
<td>
<select name="painters">
<option value="VanGogh" selected="selected">Van Gogh</option>
<option value="Dali">Dali</option>
<option value="Munch">Munch</option>
</select>
</td>
<td>
<a href="#">Save</a>
</td>

When the user clicks on Save, the selected values should be stored in a variable. This is what I have tried thus far;

$("a").click( function (e){
    str = $(this).find("select[name|='painters']").val() || [];
    alert(str.join(","));

Instead of "find", I have also tried "parent", "prev" and "closest". I have also tried specifying the selector to "select option:selected".

This works fine for getting all elements or just a single one, but when I'm trying to find the closest two and storing it in two different variabels it won't work.

Greatful for any advice or help. Thank you.

4

1 に答える 1

1

を使用.map()して値の配列を取得できます: (DOM ツリーをたどるので、そこから に戻る必要があるため、あなたのものは機能しfind()ません)trfind

$("a").click( function (e) {
    var selectValues = $(this).closest("tr").find("select").map(function() {
        return this.value;
    }).get();
});

あなたのためのフィドル!http://jsfiddle.net/5tLxk/

編集: があるので、そこにmulti-select別のものをネストmapしてすべての値を取得できます (フィドル: http://jsfiddle.net/5tLxk/1/ )

$("a").click( function (e) {
    var selectValues = $(this).closest("tr").find("select").map(function() {
        return $(this).find("option:selected").map(function() {
            return this.value;
        }).get();
    }).get();

    console.log(selectValues);
});
于 2013-10-15T21:04:46.000 に答える