I’m having hard time trying to set certain cell’s value in table.
Here is link to jsfiddle with contains a sample of this: Sample
I have table, which is created in following way:
var r = [];
var j = -1;
r[++j] = '<table cellspacing="0" id="TableWeeklyFrame"><thead><tr><th><div>Day</div></th><th><div>Profile</div></th></tr></thead><tbody>';
for (var i=0; i<data.length; i++) {
r[++j] = '<tr class="WeeklyFrameTR">';
r[++j] = '<td class="WeeklyFrameDay">';
r[++j] = data[i];
r[++j] = '</td><td><select class="SelectionWeeklyFrameProfile"></select>';
r[++j] = '</td>';
r[++j] = '</tr>';
}
r[++j] = '</tbody></table>';
$('#TableWeeklyFrame').html(r.join(''));
So table has 7 rows and 2 columns:
|Day|Profile|
|Monday|Value|
|Tuesday|Value|
|Wednesday|Value|
|Thursday|Value|
|Friday|Value|
|Saturday|Value|
|Sunday|Value|
Value is a selection containing several values.
Now the problem..
I have a set of values, e.q. (day=Monday,value=Off). Since days aren’t always in that order (well most are but that’s not the point here) I need to first find the row which contains the day and then set the value of selection to whatever I want.
I can find the row which has the certain day by doing
$('#TableWeeklyFrame tr.WeeklyFrameTR').find('td.WeeklyFrameDay:contains("Monday")');
And finally the question: How can I set the next/second cell’s value of that row?
I’m trying not to loop through the whole table. So far I have tried several things, including:
$('#TableWeeklyFrame tr.WeeklyFrameTR').find('td.WeeklyFrameDay:contains("Monday")').find('td select.SelectionWeeklyFrameProfile').val()
$('#TableWeeklyFrame tr.WeeklyFrameTR').find('td.WeeklyFrameDay:contains("Monday")').next('td').val()
$('#TableWeeklyFrame tr.WeeklyFrameTR').find('td.WeeklyFrameDay:contains("Monday")').find('select.SelectionWeeklyFrameProfile').val()
$('#TableWeeklyFrame tr.WeeklyFrameTR').find('td.WeeklyFrameDay:contains("Monday")').next('select.SelectionWeeklyFrameProfile').val()
They all return undefined. I’m missing something here and I have a feeling it’s something stupid and small..
Also, if there’s a simpler and faster way of achieving similar result, please let me know.
You could solve this in a simpler way by going through the parent:
Overall, I think this solution of moving around the dom will be hard to maintain and results in ugly code (like mine or any of the solutions offered here).
Why not just give each select an unique id? It would make changing the value so much easier.
Could then be changed with