I have an HTML table representing a database table and a sidebar which holds different anchors ready to perform CRUD operations on click.
Because the hrefs in the anchors aren't in general valid for all columns I have written a script which automatically inserts the id of a selected column into the hrefs:
/localhost/image/var/edit => /localhost/image/4/edit
The code I have written works but it isn't very clean and smart :( Could somebody take a look and say where I have space of improvement?
<script type="text/javascript">
$('table tr').click(function(){
$('.selected').removeClass('selected');
$(this).addClass('selected');
var name = $(this).find('td:nth-child(2)').html();
$('.image_bar ul li a').each(function(){
$(this).attr('href', $(this).attr('href').replace('var', name));
});
});
</script>
How could I improve the td:nth-child(2)
selector and the long line modifying the link?
EDIT:
<aside class="left image_bar">
<ul>
{% if image is defined %}
<li><a href="{{ path('AcmeCoreBundle_Image_index')}}">Bilder verwalten</a></li>
<li><a href="{{ path('AcmeCoreBundle_Image_show', { name: image.name }) }}">Bild betrachten</a></li>
<li><a href="{{ path('AcmeCoreBundle_Image_new') }}">Bild hinzufügen</a></li>
<li><a href="{{ path('AcmeCoreBundle_Image_edit', { name: image.name }) }}">Bild bearbeiten</a></li>
<li><a href="{{ path('AcmeCoreBundle_Image_delete', { name: image.name }) }}">Bild löschen</a></li>
{% else %}
<li><a href="{{ path('AcmeCoreBundle_Image_index')}}">Bilder verwalten</a></li>
<li><a href="{{ path('AcmeCoreBundle_Image_show', { name: 'var' }) }}">Bild betrachten</a></li>
<li><a href="{{ path('AcmeCoreBundle_Image_new') }}">Bild hinzufügen</a></li>
<li><a href="{{ path('AcmeCoreBundle_Image_edit', { name: 'var' }) }}">Bild bearbeiten</a></li>
<li><a href="{{ path('AcmeCoreBundle_Image_delete', { name: 'var' }) }}">Bild löschen</a></li>
{% endif %}
</ul>
</aside>
As you see when having an available singe object (while editing, showing, deleting) the server side renders the right id/name into the href. Under circumstances when I only have a collection of objects or none object available, jquery has to do the rendering of the right urls. Also some URLs don't require an id (new, index)
$('.image_bar ul li a')
selects all elements from document, not from the selected row. Are you sure that it is correct? \$\endgroup\$