user-33324
user-33324

Reputation: 17

Use jquery to set a hidden input value using attr of an image

Let's say for example I have some images

<img class="selectImage" src="..." value="John" />
<img class="selectImage" src="..." value="Sally" />
<img class="selectImage" src="..." value="Joe" />

When an image is clicked I want the value of

 <input type="hidden" name="First Name" />

to become the value of "value="

Upvotes: 1

Views: 850

Answers (3)

musefan
musefan

Reputation: 48425

I would recommend using a data-* attribute for associating data with an element, rather then the value attribute which, as others have said, is not valid markup.

Change your html to be formatted like so:

<img class="selectImage" src="..." data-firstname="John" />

You can then access the data-* attribute with JQuery as follows:

var x = $("selector").data("firstname");//get
$("selector").data("firstname", x);//set

The complete code for your requirements is as follows:

$('.selectImage').click(function(){
    var firstName = $(this).data("firstname");
    $('input[name="First Name"]').val(firstName);
});

Here is a working example

Upvotes: 0

DevlshOne
DevlshOne

Reputation: 8457

$(function() {
    $('img.selectImage').click(function(e) {
        e.preventDefault();
        var myVal = $(this).attr("value");
        $('input:hidden[name="First Name"]').val(myVal);
    });
 });

Upvotes: 0

Arun P Johny
Arun P Johny

Reputation: 388406

Try

jQuery(function($){
    var hinput = $('input[name="First Name"]');
    $('.selectImage').click(function(){
        hinput.val($(this).attr('value'))
    })
})

Demo: Fiddle

Upvotes: 1

Related Questions