Marek123
Marek123

Reputation: 1211

JQuery - focus by click in form

I'm programming a contest app for a customer.

Description:
I have three pictures on a page. A user has to choose one of the picture, "select" it and click on "I want to participate". After that, he will be redirected to a form. (the easy part).

My Problem:
How can I achieve, that if a user click on one of the three pictures, the picture will be the "chosen one" / has the focus / is selected.
The submit button shall just work, if a picture has been selected.
After that, I need to "submit" / send the chosen picture (by id or class or data attribute) to the next page and check it if it's the right picture or not.

How can I do that? By "styling" checkboxes or via jQuery?
Thank you for the hints.

EDIT:
here's a fiddle of what I mean, it's working fine, I think. Any suggestions?

HTML:

<img src="http://placekitten.com/50/50" id="first"><br/>
<img src="http://placekitten.com/50/50" id="second"><br/>
<img src="http://placekitten.com/50/50" id="third"><br/>
    <input type="hidden" name="result" value="" id="hiddenresult" />
    <button name="submit" id="submit">Submit</button>

JS:

$('#first, #second, #third').click(function(){      
         $('#hiddenresult').attr('value', $(this).id);
        $(this).css('border','1px solid red');
     }); 

Fiddle: http://jsfiddle.net/vmV75/1/

My "new" problem is:
How can I just give the selected element a border and not all. I need to set the old border = none when a new img is selected. What Am I missing?

Upvotes: 1

Views: 191

Answers (2)

Khanh TO
Khanh TO

Reputation: 48982

A simple solution is:

$('#first, #second, #third').click(function(){      
         $('#hiddenresult').attr('value', $(this).id);
        $('#first, #second, #third').css('border','');
        $(this).css('border','1px solid red');
     }); 

A better solution is to create a class and style on it:

$('#first, #second, #third').click(function(){      
             $('#hiddenresult').attr('value', $(this).id);
            $('#first, #second, #third').removeClass('selected');
            $(this).addClass('selected');
         }); 

And the css:

img.selected{
   border:1px solid red
}

Upvotes: 0

nickromano
nickromano

Reputation: 908

Style the images as radio buttons and make use of the :checked pseudo selector to add a border around the chosen image.

Guide for styling checkboxes and radio buttons: http://webdesign.tutsplus.com/tutorials/htmlcss-tutorials/quick-tip-easy-css3-checkboxes-and-radio-buttons/

Upvotes: 1

Related Questions