tags:

views:

38

answers:

2

I am working on a simple news module. There is a form where user adds multiple image IDs to one textbox then submits it. To improve the usability, I listed all the images they can add (ID numbers displayed next to it) on one side. However, this still is little bit confusing. I want image IDs added/deleted to the textbox when user clicks on the images.

Spare me codes, methods, ideas, examples... I will take anything.

A: 

Something like this (not tested)?

var $input = $('#textbox'); // <-- your input field

$('img').click(function() {
    var value = $input.val();
    var id = $(this).attr('id');
    if (value.match(id)) {
        value = value.replace(id, '');
    }
    else {
        value += ' ' + id;
    }
    $input.val(value);
});
Felix Kling
If you check and uncheck the same image a few times you'll result with: `123 32 32 32 32`
Crozin
@Crozin: Yes, I changed it. Thank you.
Felix Kling
A: 
  1. Create list of hidden inputs: <input type="hidden" name="photo[ID_HERE]" value="0" />.
  2. Create list of images: ...<li><img src="..." id="photo-123" /> Photo #123</li>...
  3. Add listener for click event for those images that will change value of input associated with image:

    $("#images img").click(function() {
       var id = $(this).attr("id").replace(/\D/g, "");
       $("input[name='photo[" + id + "]']").val(Math.abs($("input[name='photo[" + id + "]']").val() - 1));
    });
    
Crozin
I have a question. When photo clicked, where will the value of that image will be copied?
zurna
to image's hidden input.
Huseyin
But I have a question as well. I put the js code between "$(document).ready(function(){" ? But it did not work. I did not receive any errors either? Where could be the problem?
Huseyin
I've fixed the code (there were two missing `]` in jQuery selectors).
Crozin