Search code examples
jqueryformstextinput

how to change property of all text boxes matching particular class using jquery


this is my jquery code. http://jsfiddle.net/geekrule/ZnAvP/1/
as i select an image,a text-box is added with the image's source and a 'name' property is added.
now when i unselect the image,i want the 'name' to be updated.
for ex: i select images 1,3,4,5 corresponding value of 'name' of input boxes will be 1,2,3,4 and now when i unselect images -3,4 value of 'name' should be 1 and 2(this part is what i am stuck at.the values i get are 1,4).
they are not getting updated.
hope you understood the problem.please help me out. thanks in advance


Solution

  • In my opinion the simpler solition is to re-generate textboxes on each image selection:

    <div id="selectList">
        <img src="http://tinyurl.com/26asnv7" />
        <img src="http://tinyurl.com/26asnv7" />
        <img src="http://tinyurl.com/26asnv7" />
        <img src="http://tinyurl.com/26asnv7" />
        <img src="http://tinyurl.com/26asnv7" />
        <img src="http://tinyurl.com/26asnv7" />
        <img src="http://tinyurl.com/26asnv7" />
        <img src="http://tinyurl.com/26asnv7" />
    </div><form id='if' name='forms' method='post'>
    <button type='submit' class="uploadPic">Upload Fb</button>
    </form>
    ​
    $(function() {
        $("#selectList img").click(
        function(event) {
            if( !$(this).is(".clicked") && $("#selectList img.clicked").length >= 3){
                event.preventDefault();
                alert('only 3 photos allowed');
                return;
            }
            $(this).toggleClass("clicked");
            regenerateTextBoxes();
        });
    });
    
    function regenerateTextBoxes() {
        $('#if .selection').remove();
        $("#selectList img.clicked").each(function(index, element) {
            var $input = $('<div>', {
                'class': 'selection',
                'html': $('<input>', {
                    'type': 'text',
                    'value': $(this).attr('src'),
                    'name': 'pics' + index
                })
            });
    
            $("#if").append($input);
        });
    }​