How to target data attribute of a select option? - javascript

I'm trying to make an image change based on the dropdown/select option that a user chooses. However, I need to do this using a data attribute rather than the easier option value, since I need that to be used for something else. I can't seem to figure out what I'm doing wrong. The code I've attached doesn't target the data-image attribute. And ideas what I'm doing wrong?
Example Code:
<html>
<div>
*Flavor 1:
</div>
<div>
<select class="custom-cupcake-flavor" name="custom-cupcake-flavor">
<option data-image="noimage.jpg" value="">-- Please Choose an Option --</option>
<option data-image="Chocolate-Covered-Strawberry.jpg" value="Chocolate Swirl">Chocolate Swirl</option>
<option data-image="strawberryLemonade.jpg" value="Extreme Lemon">Extreme Lemon</option>
<option data-image="Cookie-Dough-Delight.jpg" value="Vanilla Blast">Vanilla Blast</option>
</select>
</div>
<br>
<div class="col-md-6">
<img id="uploadedImage" src="https://placeholdit.imgix.net/~text?txtsize=33&txt=400%C3%97400&w=400&h=400">
<br>
</div>
<script src="//code.jquery.com/jquery-1.11.3.min.js"></script>
<div style="clear:both;"></div>
<script type='text/javascript'>
$(document).ready(function() {
var flavor;
var image_name;
$(".custom-cupcake-flavor").on('change', function() {
flavor = $(this).data("image");
image_name = ("/images/" + flavor);
$('#uploadedImage').fadeOut(200, function() {
$('#uploadedImage').attr('src', image_name).bind('onreadystatechange load', function() {
if (this.complete) $(this).fadeIn(400);
});
});
});
});
<!-- Hides Product Image when "No image" option is selected.-->
$(document).ready(function() {
$('.custom-cupcake-flavor').on('change', function() {
if (this.val() !== "") {
$("#uploadedImage").hide();
} else {
$("#uploadedImage").show();
}
});
});
</script>
</html>

You can use the :selected selector to get the selected option in your dropdown:
$('.custom-cupcake-flavor').on('change', function() {
var $option = $(this).find(':selected');
var imageUrl = $option.data('image');
// You might want to do something with imageUrl here:
$('#uploadImage').attr('src', imageUrl);
});
// If you want to run the above on initial load you can trigger the change event:
// $('.custom-cupcake-flavor').trigger('change');

Related

jquery about attributes ( load from loaded html )

I have a 2 select options. When I select the first one it posts to a link using javascript then return full options to the second one with data from a database.
I have an attributes in the second select called data-price. When I'm trying to use it, it shows nothing:
var x = $("#services").find(':selected').attr('data-price');
However when I'm trying with the first select attribute it works correctly. Anyone know how to fix ? Thanks
<script type="text/javascript">
$(document).ready(function(){
var category = document.getElementById("category").value;
$.ajax({
type:'POST',
url:'<?=base_url();?>dashboard/ajaxData',
data:'main_category='+category,
success:function(html){
$('#services').html(html);
}
});
$('#category').on('change',function(){
var category = $(this).val();
if(category){
$.ajax({
type:'POST',
url:'<?=base_url();?>dashboard/ajaxData',
data:'main_category='+category,
success:function(html){
$('#services').html(html);
}
});
}else{
$('#services').html('<option value="">Select category first</option>');
}
});
});
var x = $("#services").find(':selected').attr('data-price');
document.getElementById("demo").innerHTML = x;
</script>
<div class="form-group">
<label>Category</label>
<select name="category" id="category" class="form-control">
<?php foreach($categories->result() as $cat): ?>
<option data-price="55" value="<?=$cat->id;?>">- <?=$cat->title;?></option>
<?php endforeach; ?>
</select>
</div>
<div class="form-group">
<label>Service</label>
<select name="service" id="services" class="form-control">
<option data-price=""></option>
</select>
</div>
<div id="demo"></div>
To find the selected one you do:
$("#services option:selected")
then you can get whatever you want from that option.
For a data attribute it can be:
$("#services option:selected").data('price');
or alternatively
$("#services option:selected").attr('data-price');
This answer is based on the assumption that your select as an id attribute of services, if it is not all the above code will fail
Based on the updated code you posted you probably are looking to update the selected value when the user changes the selection.
I'd do it binding the change event like this:
$("#services option:selected").change(function(){
var price = $(this).attr('data-price');
$('#demo').html(price);
});

On Page Load select option jquery like user behaviour (Real Time Change Event Fire)

I want to autoselect select box option on page load. Here is my code which is not working.
jQuery(document).ready(function(){
jQuery(".configure_supre_select_1 option:eq(1)")
.attr('selected',true)
.trigger('change');
});
You are triggering the selected option instead of the select - also use prop
$(function(){
$(".configure_supre_select_1 option:eq(1)").prop('selected',true);
$(".configure_supre_select_1").trigger('change');
});
Alternatively set the value
$(function(){
$(".configure_supre_select_1").val("firstOptionValue").change();
});
$(function() {
$(".configure_supre_select_1").on("change", function() {
$(".optdiv").hide();
var val = this.value;
if (val) {
$("#" + val.replace("OptionValue", "")).show();
}
});
$(".configure_supre_select_1").val("firstOptionValue").change();
$(".configure_supre_select_2 option:eq(1)").prop('selected',true);
$(".configure_supre_select_2").trigger('change');
});
.optdiv {
display: none
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<select class="configure_supre_select_1">
<option value="">Please select</option>
<option value="firstOptionValue">First</option>
<option value="secondOptionValue">Second</option>
</select>
<div class="optdiv" id="first">First is selected</div>
<div class="optdiv" id="second">Second is selected</div>
<hr />
Here I use your version <br/>
<select class="configure_supre_select_2">
<option value="">Please select</option>
<option value="firstOptionValue">First</option>
<option value="secondOptionValue">Second</option>
</select>
For make real time click by jquery i added below code. It used "Event".
For change select option on page load i use below code:
jQuery(".configure_supre_select_1").val(jQuery(".configure_supre_select_1 option:eq(1)").val()).change();
and then make it real time changing i use below code:
var dropdown = $("SelectAttributeId"); // Id of select box
var element = dropdown;
var event = 'change';
var evt = document.createEvent("HTMLEvents");
evt.initEvent(event, true, true );
return !element.dispatchEvent(evt);

Show image depending on select option with custom value attribute

What I want to reach:
Show an image depending on select box selection. But I don't want to take attribute value="", I want to take a custom attribute data-img="" instead.
This is the code I actually have, but it's not working:
<html>
<head>
<script src="http://code.jquery.com/jquery-latest.pack.js"></script>
<script>
function showFormatImage() {
var image = document.getElementById("itemImage");
image.src = $('select[name=itemImage] option:selected').data('img');
return false;
}
document.getElementById("itemImage").onchange = showFormatImage;
</script>
</head>
<body>
<select id="itemImage" name="itemImage">
<option data-img="first.png">First</option>
<option data-img="second.png">Second</option>
<option data-img="third.png">Third</option>
</select><br>
<img id="itemImage" src="">
</body>
</html>
No image is shown. Does anybody know what's wrong?
P.S.: If there's a non-Javascript solution, that would be even better but I don't think there is.
var image = document.getElementById("itemImage");
var image is the select - not the img, also - itemImage does not exist at time of execution so the event handler isn't placed.
you should change your code to:
<html>
<head>
<script>
window.onload = function() {
document.getElementById("itemImage").onchange = showFormatImage;
};
function showFormatImage() {
var image = document.getElementById("changeImage");
image.src = $('select[name=itemImage] option:selected').attr('data-img');
return false;
}
</script>
</head>
<body>
<select id="itemImage" name="itemImage">
<option data-img="first.png">First</option>
<option data-img="second.png">Second</option>
<option data-img="third.png">Third</option>
</select><br>
<img src="" id='changeImage'/>
</body>
</html>
jquery solution:
$(document).ready(function(){
$('#itemImage').change(function(){
var src = $(this).find('option:selected').attr('data-img');
$('img#changeImage').attr('src',src);
});
});
Should replace .data function with .attr(data-img)

Comparing each of the <option>s in a <select> element using jQuery

I am writing a plugin for WordPress and am confused as to how to compare the user-input (got from an <input> element) to a set of <option> elements in a <select> element.
At the moment I am doing the following:
$('button#test_button').click(function(event) {
event.preventDefault();
// Get the text in the input box:
var input_text = $('input#input_test').text();
$("#selectId > option").each(function() {
if ($(this).text() == input_text) {
alert("Alert Triggered");
}
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<input id="input_test"></input>
<select id="selectId">
<option value="hello">Foo</option>
<option value="test">Test</option>
</select>
<button id="test_button">Click me!</button>
However, if you run the snippet you can see that the alert is never triggered, but I'm not sure why? I'm new to JavaScript so I'm not aware of any intricacies to the language, so this is probably a simple query, but I'd be grateful for any assistance.
You need to use val() method to get input value. And you have a typo of getting text content of <option> tag. Should be $(this).text(), not $(this).text
$('button#test_button').click( function(event) {
event.preventDefault();
// Get the text in the input box:
var input_text = $('input#input_test').val();
$("#selectId > option").each(function() {
if( $(this).text() == input_text )
{
alert("Alert Triggered");
}
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<input id="input_test"></input>
<select id="selectId">
<option value="hello">Foo</option>
<option value="test">Test</option>
</select>
<button id="test_button">Click me!</button>

Jquery selectmenu plugin with text input option

I need jquery plugin which would transform my simple
<select>
<option>text</option>
</select>
In to fully customizable list something like a <lu> list or list of <div>, i have found quite a lot of this kind of plugins, but none of them have option to type something in and set it as an option.
Lets say i have kind of list:
<select>
<option value="text">text</option>
<option value="other">other</option>
</select>
Now i want other option transform into <input type="text" />, and i'm quite sure there has to be plugin which does just that.
I have made an example how should it look, on the left is my current plugin and on the right is what i need, i know i could edit my current plugin but it's just way to big for me and it would take to much time.
There is no jQuery plugin which does exactly that. However, there is a jQuery UI selectmenu plugin, which converts a select element to a html representation such that you can style the select menu. This plugin also offers a callback for formatting text, such that in our case, we could format our 'other' option into an input box.
Suppose we have the following select:
<select name="otherselect" id="otherselect">
<option value="united-states">United States</option>
<option value="latvia" selected="selected">Latvia</option>
<option value="france">France</option>
<option>Other</option>
</select>
We can create a selectmenu with this plugin using:
$(function(){
selectMenu = $('select#otherselect').selectmenu({
style:'popup',
width: 300,
format: otherFormatting
});
});
In here the function otherFormatting is a function which will format our Other option. This is our function:
var otherFormatting = function(text){
// if text contains 'Other' format into Other input box...
if ( text == "Other" ) {
var button = $('<input type="submit" onclick="selectOther(this)" value="select"/>');
var input = $('<input class="other" type="text" value="Other..."/>');
return $('<span/>')
.append(input)
.append(button)[0].outerHTML;
}
return text;
}
The selectOther function that is called when the button is clicked, is a function we will extend the plugin with. This function, activated when the button is clicked, will set the values of our select, such that we can easily submit it using a form. But also, set the value which is displayed in the new selectmenu (instead of showing an input box in the select box).
We need to extend this plugin, which is a jQuery UI widget basically. However, since the plugin binds some events which make it impossible for us to get the input field and button working, we need to unbind some of these. We do this when we open the select menu. For this we need to override the open function of the widget, call our function that unbinds some events and then open the menu using the original open function.
Putting this all together:
<!DOCTYPE html>
<html>
<head>
<title>Demo Page for jQuery UI selectmenu</title>
<link type="text/css" href="../../themes/base/jquery.ui.all.css" rel="stylesheet" />
<link type="text/css" href="../../themes/base/jquery.ui.selectmenu.css" rel="stylesheet" />
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
<script type="text/javascript" src="../../ui/jquery.ui.core.js"></script>
<script type="text/javascript" src="../../ui/jquery.ui.widget.js"></script>
<script type="text/javascript" src="../../ui/jquery.ui.position.js"></script>
<script type="text/javascript" src="../../ui/jquery.ui.selectmenu.js"></script>
<style type="text/css">
body {font-size: 62.5%; font-family: "Verdana",sans-serif; }
fieldset { border: 0; }
label, select, .ui-select-menu { float: left; margin-right: 10px; }
select { width: 200px; }
</style>
<script type="text/javascript">
// We need to able to call the original open method, save intoIf you need to call original method
var fn_open = $.ui.selectmenu.prototype.open;
$.widget("ui.selectmenu", $.extend({}, $.ui.selectmenu.prototype, {
open : function() {
// Every the selectmenu is opened, unbind some events...
this._unbindEvents();
fn_open.apply(this, arguments);
},
_unbindEvents : function() {
var el = $(this.list).find('li:has(input.other)').eq(0);
// unbind events, we need a different event here...
el.unbind('mouseup');
el.unbind('mousedown');
el.bind('mousedown', function() {
// We need to call focus here explicitly
$(this).find('input.other').eq(0).focus();
// Empty field on click...
if ( $(this).find('input.other').eq(0).val() == 'Other...' )
$(this).find('input.other').eq(0).val("");
});
// Unbind keydown, because otherwise we cannot type in our textfield....
this.list.unbind('keydown');
// We only need to return false on the mousedown event.
this.list.unbind('mousedown.selectmenu mouseup.selectmenu');
this.list.bind('mousedown', function() {
return false;
});
},
selectOther : function(el) {
var button = $(el);
// li item contains the index
var itemIndex = button.parent().parent().parent().data('index');
var changed = itemIndex != this._selectedIndex();
// Get the value of the input field
var newVal = button.prev().val();
this.index(itemIndex);
// Update the display value in the styled select menu.
this.newelement.find('.' + this.widgetBaseClass + '-status').html(newVal);
// Update the value and html of the option in the original select.
$(this.element[0].options[itemIndex]).val(newVal).html(newVal);
// Call the select, change and close methods
var e = jQuery.Event("mouseup");
this.select(e);
if ( changed )
this.change(e);
this.close(e);
}
}));
var selectMenu;
$(function(){
selectMenu = $('select#otherselect').selectmenu({
style:'popup',
width: 300,
format: otherFormatting
});
});
function selectOther(el) {
// Call our self defined selectOther function.
selectMenu.selectmenu('selectOther', el);
}
//a custom format option callback
var otherFormatting = function(text){
// if text contains 'Other' format into Other input box...
if ( text == "Other" ) {
var button = $('<input type="submit" onclick="selectOther(this)" value="select"/>');
var input = $('<input class="other" type="text" value="Other..."/>');
return $('<span/>')
.append(input)
.append(button)[0].outerHTML;
}
return text;
}
</script>
</head>
<body>
<h2>Select with Other option input field</h2>
<fieldset>
<label for="otherselect">Select a value:</label>
<select name="otherselect" id="otherselect">
<option value="united-states">United States</option>
<option value="latvia" selected="selected">Latvia</option>
<option value="france">France</option>
<option>Other</option>
</select>
</fieldset>
<button onclick="console.log($('#otherselect').val());">Test</button>
</body>
</html>
To try this, download the plugin here and make sure the urls to the js/css files are correct. (I have put this html file into the demos/selectmenu folder and it works...). Ofcourse you can replace the button with an image.
Try this, this little script will create a text input after a select box if the select box value is other. The new text input as the same name of the select so that its value overwrite the one set by the select (as it is other)
If the value is something else than other we just check for the text input presence and remove it (so it doesn't overwrite the select value)
http://jsfiddle.net/cW725/1/
HTML
<form>
<p>
<select>
<option value="text">text</option>
<option value="text">text</option>
<option value="text">text</option>
<option value="other">other</option>
</select>
</p>
<p>
<select>
<option value="text">text</option>
<option value="text">text</option>
<option value="text">text</option>
<option value="other">other</option>
</select>
</p>
</form>
​
jQuery
$(function() {
// bind all select on change
$('select').on('change', function() {
// if value is other
if ($(this).val() == 'other') {
// add a text input we match the name so that this input overwrite the select one as after in the form
$(this).after('<input type="text" name="' + $(this).attr('name') + '" class="otherInput" />');
} else {
if ($(this).next().is('input.otherInput')) {
$(this).next().remove();
};
};
});
});​
I was looking for a jquery 'select or edit' solution, and found this can be done with help of select2 plugin.
Turned out to be pretty simple solution that does exactly what I wanted.
HTML:
<select name="otherselect" id="otherselect">
<option value="united-states">United States</option>
<option value="latvia" selected="selected">Latvia</option>
<option value="france">France</option>
</select>
JS:
$('#otherselect').select2({tags: true});
Example:
https://jsfiddle.net/h0qp37jk/
You might check out chosen.js - it might fit your needs. Might be easier that making something from scratch. Good luck.

Categories

Resources