CLiown
CLiown

Reputation: 13843

Change field field value on click

I want to supply the user with 3 images, each image will have an associated value:

1. left,middle,right
2. middle,left,right
3. left,right,middle

I then want to write that value to the text field in a form, so it gets saved when the user clicks submit.

I already have a working form where the user can type in values, 1,2 or 3 but want the text field to be hidden and the user to select an image instead and that update the text field.

Upvotes: 0

Views: 634

Answers (4)

Coreus
Coreus

Reputation: 5610

jQuery makes this a trivial task. You can bind the click event to the images.

excerpt:

    <img src="/images/lmr.png" class="direction" name="left,middle,right" />
    <img src="/images/mlr.png" class="direction" name="middle,left,right" />
    <img src="/images/lrm.png" class="direction" name="left,right,middle" />


  <input type="text" value="Click an image" />

<script>
    $('.direction').click(function () {
      var text = $(this).attr('name');
      $("input").val(text);
    });
</script>

Tested locally, and the input type field gets its value set. Now you can make it hidden and it will be posted. (<input type="hidden" etc.)

Upvotes: 0

Matt
Matt

Reputation: 75317

Attach an onclick handler to the images, which sets the value attribute of the text field to whatever you want.

Here is something for it in jQuery:

<img class="clickable" src="something.jpg" alt="left,middle,right"/>
<img class="clickable" src="something.jpg" alt="middle,left,right"/>
<img class="clickable" src="something.jpg" alt="left,right,middle"/>
<input type="hidden" id="clicked-image" name="something"/>

<script>
$(document).ready(function() {
  $('.clickable').bind('click', function () {
    $('#clicked-image').val($(this).attr('alt'));
  });
});
</script>

Upvotes: 0

Adam Kiss
Adam Kiss

Reputation: 11859

if you're using jQuery:

<img class="selector123" src="..." rel="1"/>

in jQuery

$(".selector123").click(function(){
  $("#value123input").val($(this).attr('rel'));
});

That's one example:)

Upvotes: 0

antyrat
antyrat

Reputation: 27765

Set @id attribute to your hidden inputs, and then at your images you can use javascript code, for example

<img src="1.jpg" onclick="document.getElementById('inputID').value='your value'">
<input type="hidden" id="inputID" name="somename">

Upvotes: 1

Related Questions