Jeff Solomon
Jeff Solomon

Reputation: 473

Single jQuery Image Selector for Multiple Fields

I'm trying to figure out the approach to this problem, if someone can't provide a direct solution, I would benefit from a conceptual approach so I can try to solve it myself.

I have a page with text form fields, each field having a corresponding IconId. On the page will be list of small image icons (PNG). Goal is when a user clicks on one of the text boxes, it will activate the 100 icons, user can select 1 icon which will add the IconId to the corresponding hidden field. When a user clicks on a field that already has a IconId assigned or in the hidden field, they can choose a different icon and that swaps out the IconId. Page will be submitted as a standard form post via PHP and page framework will be Bootstrap 3 w/ jQuery 1.11.

Here is a Fiddle demonstrating the use case: http://jsfiddle.net/pitashi/xpvt214o/182828/

Upvotes: 0

Views: 113

Answers (2)

Keith
Keith

Reputation: 24191

Here is a simple example of using a data attribute,..

I've not actually used icons here, or a hidden field for demo purposes, but it should be easy for you to alter for your needs.

var lastFocus = null;

$(document.body).on("focus", "input", function () {
  lastFocus = this;
});

$(document.body).on("click", "[data-icon-id]", function () {
  $(lastFocus).val(this.dataset.iconId).focus();
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>


<p>Click each LI, and you will get the id inside the last focused input field.</p>
<input /><br>
<input /><br>
<input /><br>


<ul>
  <li data-icon-id="1">Icon 1</li>
  <li data-icon-id="2">Another icon (2)</li>
  <li data-icon-id="3">It's three</li>
</ul>

Upvotes: 1

MarvHock
MarvHock

Reputation: 874

You could add an unique id to each input field (e.g. iterating them input-1, input-2 etc.). Then, you could store the id of the currently selected input field into a variable of your script. When clicking an icon, you select the input field by that saved variable/id and update its corresponding icon-id hidden field.

Upvotes: 0

Related Questions