Selecting images inside a form using jQuery
I've got some server side PHP code that dynamically displays thumbnails of all the images contained in a directory:
<form>
<input type="hidden" name="animal">
<div id="thumbs">
\\ Dynamically created thumbnails start
<img src="images/bat.jpg">
开发者_运维百科 <img src="images/cat.jpg">
<img src="images/rat.jpg">
\\ Dynamically created thumbnails end
</div>
</form>
I want the correct jQuery syntax so that when a user clicks on one of the images it:
- Removes border styles from all of the thumbnails
- Highlights the selected thumbnail by adding a coloured border
- Changes the value of the form field "animal" to the file name shown in the image.
Any help much appreciated.
demo: http://jsfiddle.net/9rFKB/
jquery
$('#thumbs').delegate('img', 'click', function() {
var $this = $(this);
// Clear formatting
$('#thumbs img').removeClass('border-highlight');
// Highlight with coloured border
$this.addClass('border-highlight');
// Changes the value of the form field "animal" to the file name shown in the image.
$('[name="animal"]').val( $this.attr('src').substring($this.attr('src').lastIndexOf('/')+1) );
alert( $('[name="animal"]').val() );
});
css
.border-highlight {
border:5px dashed red;
}
I've used delegate
instead of click
since you have stated that the images are to be created dynamically.
If by "removes formatting on thumbnails" means removing all css on your images, then I think what you want is this.
精彩评论