I have a form with 11 inputs that relate to each column on a table, which is displayed above. Each input has an id that matches the a class in the table based on the column name. I want all the inputs to be droppable, the logic for all of them is identical to below.
$(function() {
$( "#dest_city" ).droppable({
drop: function( event, ui ) {
$( ".ui-selected.dest_city" ).each(function(){
$( '#dest_city' )
.val( $( '#dest_city' ).val() == "" ? $( this ).html() : $( '#dest_city' ).val() + ", " + $( this ).html() );
})
}
});
});
$(function() {
$( "#dest_state" ).droppable({
drop: function( event, ui ) {
$( ".ui-selected.dest_state" ).each(function(){
$( '#dest_state' )
.val( $( '#dest_state' ).val() == "" ? $( this ).html() : $( '#dest_state' ).val() + ", " + $( this ).html() );
})
}
});
});
$(function() {
$( "#car" ).droppable({
drop: function( event, ui ) {
$( ".ui-selected.car" ).each(function(){
$( '#car' )
.val( $( '#car' ).val() == "" ? $( this ).html() : $( '#car' ).val() + ", " + $( this ).html() );
})
}
});
});
And the inputs -
<td><input type="text" name="dest_city" id="dest_city" value="" size="7" /></td>
<td><input type="text" name="dest_state" id="dest_state" value="" size="3" /></td>
<td><input type="text" name="car" id="car" value="" size="11" /></td>
And the data -
<tr>
<td class="drag car">AAAAAAA</td>
<td class="drag">111111</td>
<td class="drag">1111</td>
<td class="drag">P</td>
<td class="drag loc_city">FTSCOTT</td>
<td class="drag loc_state">KS</td>
<td class="drag">L</td>
<td class="drag">AAAAA</td>
<td class="drag">11111</td>
<td class="drag">11</td>
<td class="drag">AAAAA</td>
<td class="drag dest_city">FRESNO</td>
<td class="drag dest_state">CA</td>
</tr>
This checks on drop for all selected cars and inserts each of them to the input, the ternary checks if the input is empty or already has something, and adds the items to make a comma separated list.
My question is, is there any way to refactor this instead of writing the above for each input?
I am using Ruby on Rails so I can easily set up a loop to create that for each input, but that's only shorter on my end, the actual output would still have a nearly identical block of code for each input.
A .car
can only be placed in #car
, .dest_city
in #dest_city
etc...