I currently have a HTML select box like below.
<select name="item_1">
<option value="0">Choose one...</option>
<option value="1">Value (1)</option>
<option value="2">Value (2)</option>
<option value="3">Value (3)</option>
</select>
I have to do the following. Either way works, but I want to learn both, if possible.
A.
- Imagine there is 3x different select boxes called item_1, item_2 and item_3.
- Imagine a div (or a table) on any place of current document.
- Whenever the value on select box changes, the div should contain a link to picture with option value.
For example, if “Value (2)” gets selected in “item_1” selectbox, then it should print 2.jpg on the div. If there are selected values in other selectboxes, it should also be printing their images.
Example:
item_1 -> Value (2) —
item_2 -> Value (3) —
Output -> < img src=”2.jpg”>, < img src=3.jpg”>
How can I do this?
B.
The same question as above, except; instead of directly printing the picture link depending on selectbox value, we will do a AJAX request to our PHP file. PHP will return the additional information about the selected value in selectbox. (e.g if you selected “value 2”, it may get it’s price, stock_count or picture_path or w/e from database.)
Depending on the returned values, we will get image_path value from database so instead of printing 2.jpg, it may print my_cute_dog.jpg.
How can I do this? I’ll be glad if you can guide me.
Thank you,
Anil
Ps. No need to code PHP. Just give me the PHP file name, parameters and method. (POST prefered). I just need some basic jQuery/JS help, or guidance.
Ps. 2 You can name divs however you want.
The first part of your question is easy. Bind to the change event for your dropdown list. Then access
$(this).val()to get the newly selected value.You can then modify the
srcattribute of an existing image to be the new value. Note that I useprophere because I am in jQuery 1.7+. If you are not using newer jQuery then useattrinstead.Finally there are a number of AJAX methods cooked into jQuery. I chose
load, but you could use something more complex likegetorajaxfor more fine grained control of the returned values. Load basically takes whatever is returned by the server and stuffs it into the matched elements.http://jsfiddle.net/LHpJd/