How to select the HTML5 data attribute in jQuery? - javascript

My current jQuery selects the value attribute. How do I change my jQuery to select the data attribute "data-price"?
$('#trapfabric, #trapsize').on('change', function() {
var $selected = $('#trapfabric, #trapsize').children(":selected");
sum = parseInt($('#trapsize').val()) + parseInt($('#trapfabric').val());
$('#priceToSwap3').html('$' + sum
);
});
I know I have to fit something like this in the above but I can't get it to work:
$('#priceToSwap3').text($selected.data("price"))
EDITED
My HTML:
<span id="priceToSwap3"">$238</span>
<select id="trapsize" onChange="swapImage()">
<option data-price="238">foo</option>
<option data-price="288">foo</option>
</select>
<select id="trapfabric" onChange="swapImage()">
<option data-price="0">foo</option>
<option data-price="20">foo</option>
</select>

I believe this is what you want:
var $elements = $('#trapfabric, #trapsize');
$elements.on('change', function() {
var $selected = $elements.children(":selected");
var sum = 0;
$selected.each(function() {
sum += $(this).data('price');
});
$('#priceToSwap3').html('$' + sum);
});
You have to iterate over the selected elements to get the price datum of each of them.
DEMO

You are binding event to two elements #trapsize, #trapfabric if you want to get the source element you need to use $(this);
jsfiddle
$('#trapfabric, #trapsize').on('change', function() {
$('#priceToSwap3').text( '$' + $(':selected', this).data("price") );
});

We had a similar scenario wherein we assign security value(1,2,3 as security level) for each input. We have to change the security values "0" when the user logs into the system.
Eg:
<input type="text" security="3" id="super-admin" />
<input type="text" security="2" id="main-admin" />
<input type="text" security="1" id="normal-user" />
<script>
function userValidation(userType){
if(userType="super-admin"){
$("[security=1]").attr("security", 0);
$("[security=2]").attr("security", 0);
$("[security=3]").attr("security", 0);
}
if(userType="main-admin"){
$("[security=1]").attr("security", 0);
$("[security=2]").attr("security", 0);
}
if(userType="normal-user"){
$("[security=1]").attr("security", 0);
}
}
<script>

Related

Using selector to replace all dropdownlist (select) with label

I'm trying to replace all the drop down lists with a p element or a label that have only the selected option, reason is I want to prepare this for printing without showing the down arrow that is in dropdownlist.
I need to use type selector as the select element have different classes name and no IDs. Problem is I can't seem to get the complete select element when I'm using $("select").
I notice when I use $("select") I got different results than using the ID selector in console
$("#id") //return
init {context: document, selector: "#2"}
var allInputs = $("select"); //return
<select id="2">
<option>Option</option>
<option>Option2</option>
</select>
allInputs[key].replaceWith("<p>" + text+ "</p>") //so this doesn't work
Here's a copy of the JS code
var allInputs = $("select");
if($("#2")==allInputs[0])
{alert("True");}
$.each( allInputs, function(key, value ) {
var text=value.find("option:selected").text() ;
allInputs[key].replaceWith("<p>" + text+ "</p>");
});
Jsfiddle here:
https://jsfiddle.net/abahrani/fzhv41s7/4/
how about use mapping (I did it with an unordered list but you get the idea) run the snippet below
$('#mybutton').click(function() {
$("select").map(function() {
return $(this)
}).get()
.forEach(function(element) {
$('#container').append(
`<ul><li>
${element.val()}<ul>${getOptions(element)}</ul>
</li></ul>`)
});
function getOptions(element) {
let html = ''
element.find('option').map(function() {
return $(this).val();
}).get()
.forEach(function(option) {
html += `<li>${option}</li>`
});
return html;
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form>
<input type="file">
<input type="text">
<select id="2">
<option>Option</option>
<option>Option2</option>
</select>
<select>
<option>selector</option>
<option>Option3</option>
</select>
</br>
<button type="button" id="mybutton">
print all options
</button>
</form>
<div id="container">
</div>
As per thmsdnnr comment, I found out the reason
allInputs[key].replaceWith("<p>" + text+ "</p>") // doesn't work
didn't work because I needed to use the $ sign, when $(allInputs[key]) used. everything worked.
$(allInputs[key]).replaceWith("<p>" + text+ "</p>") //works

ddslike get two values from diffrentes select

i have little problem with ddslike jquery lib
I have two select box like this:
<select id="from">
<option value="1" data-imagesrc="img.png" data-description="USD">Dollar</option>
<option value="2" data-imagesrc="img.png" data-description="EUR">Euro</option>
</select>
<select id="to">
<option value="1" data-imagesrc="img.png" data-description="USD">Dollar</option>
<option value="2" data-imagesrc="img.png" data-description="EUR">Euro</option>
</select>
Javascript of SELECT BOX (Want just the design from ddslike):
<script type="text/javascript">
$(document).ready(function () {
$('#from_fees').ddslick({
width: 100,
});
$('#to_fees').ddslick({
width: 100,
});
});
</script>
Here my script that i wanted to fetch value of select's options:
$(function(){
$("#from").change(function(event){
//alert("Click event on Select has occurred!");
$("option:selected", $(this)).each(function(){
var obj = document.getElementById('from').value;
alert("selected value"+obj);
});
});
});
But i get no results !
I want get the two value from the two select in the same time.
Thank you.
First, you've got to be consistent with your IDs. You've got id="from" in the html, but you call .ddslick() on the element with id "from_fees".
If I understand, you'd like to get the values of each whenever either one changes. How about:
<script>
$('select').change(function(){
var to = $('#to').val();
var from = $('#from').val();
// alert("To: " + to + " and from: " + from + ".");
});
</script>
You don't need to use "this", because you want the value out of both of them.

JQuery - Trying to look at the change from one input to another input

I have one input that's value is a SUM of a bunch of select options. From there I am setting up another input that looks at the value from the first input and is suppose to update when the first one changes (plan to do more with it, but can't get past this step). Unfortunately the second is not updating on change.
Sample HTML:
<select name="product-attr-os">
<option data-selected="house" value="10">Made in House</option>
<option data-selected="license" value="
15">Licensed Software</option>
<option data-selected="open" value="20">Open Source</option>
</select>
<br>
<select name="product-attr-network">
<option data-selected="3g" value="40">3G</option>
<option data-selected="4g" value="
45">4G/LTE</option>
<option data-selected="5g" value="50">5G</option>
</select>
<p>Attr Total Cost</p>
<input type="text" class="product-attr-totalCost" name="product-attr-totalCost" readonly />
<p>Standard Cost</p>
<input type="text" class="product-standardCost" name="product-standardCost" readonly />
JQuery:
// SUM (Product Attributes)
var productAttrTotal = function (inputs, output, selected) {
$(document).ready(function () {
$(inputs).bind('change', function () {
var sum = 0;
$(inputs).find(selected).each(function () {
sum += parseInt($(this).val());
});
$(output).val(sum);
});
$(inputs).trigger('change');
});
};
productAttrTotal('select', '.product-attr-totalCost', ':selected');
// Product Attributes Total + Wifi
var productTotalCost = function (attrCost, totalCost) {
$(document).ready(function () {
$(attrCost).bind('change', function () {
$(totalCost).val($(attrCost).val());
});
$(attrCost).trigger('change');
});
};
productTotalCost('.product-attr-totalCost', '.product-standardCost');
Jsfiddle
If you want to display same value in both the input fields, pass the selector for both of them as the output using multiple selector
productAttrTotal('select', '.product-attr-totalCost, .product-standardCost', ':selected');
Demo: Fiddle
Also note to trigger the change event on page load for only one of the select element
$(inputs).first().trigger('change');
In that case
productAttrTotal('select', '.product-attr-totalCost', ':selected');
then once the value of update is changed using script trigger the change event
$(inputs).first().trigger('change');
Demo: Fiddle

Change to plural if value in textbox is greater than 1

I have a textbox and a selectbox like this:
<h3>Recipe Yield</h3>
<input style='width:100px' type="text" name="yield" class="small" />
<select name='yieldType'>
<option value='Servings'>Serving(s)</option>
<option value='Cups'>Cup(s)</option>
<option value='Loaves (Loaf)'>Loaves (Loaf)</option>
</select>
Here's a JSFiddle: http://jsfiddle.net/T3Sxb/
As you can see, the select options are in the form of word(s)
but I want to have a script where when
If the number in the inputbox is 1, the value in the options are in the form of word
If the number in the inputbox is greater than 1, the value in the options are plural.
Is this possible? How can I do this? Thanks for all help!
Demo: http://jsfiddle.net/T3Sxb/8/
Alternate using input[type="number"]: http://jsfiddle.net/T3Sxb/15/
Multiple inputs, styled: http://jsfiddle.net/T3Sxb/17/
I'm using data attributes so that you can declare the proper singular/plural forms for each item. Simply adding "s" doesn't work in many cases.
Also note that zero items usually (always?) takes a plural form.
HTML
<input style='width:100px' type="text" id="yield" class="small" />
<select id='yieldType'>
<option value='Servings' data-single="Serving" data-other="Servings"></option>
<option value='Cups' data-single="Cup" data-other="Cups"></option>
<option value='Loaves (Loaf)' data-single="Loaf" data-other="Loaves"></option>
</select>
JavaScript
var yield = $("#yield");
var yieldType = $("#yieldType");
function evaluate(){
var single = parseInt(yield.val(), 10) === 1;
$("option", yieldType ).each(function(){
var option = $(this);
if(single){
option.text(option.attr("data-single"));
}else{
option.text(option.attr("data-other"));
}
});
}
// whatever events you want to trigger the change should go here
yield.on("keyup", evaluate);
// evaluate onload
evaluate();
You could try this: http://jsfiddle.net/T3Sxb/7/
var plural = {
Serving: "Servings",
Cup: "Cups",
Loaf: "Loaves"
};
var singular = {
Servings: "Serving",
Cups: "Cup",
Loaves: "Loaf"
};
$( "#pluralizer" ).on( "keyup keydown change", function() {
var obj = parseInt( $( this ).val() ) === 1 ? singular : plural;
$( "#YieldType option" ).each( function() {
var html = $( this ).html();
if ( html in obj ) {
$( this ).html( obj[html] );
}
});
});
From a UX point of view, I think (s) is perfectly acceptable. But anyway, how about this:
<option value='Servings' data-singular="Serving" data-plural="Servings">Servings</option>
then:
// you should really use IDs ;)
$('input[name="yield"]').on('change', function () {
var singular = parseInt($(this).val(), 10) === 1;
$('select[name="yieldType"]').each(function () {
if (singular) {
$(this).val($(this.attr('data-singular')));
} else {
$(this).val($(this.attr('data-plural')));
}
});
});

Add <select> options based on the value of a text input

How I can add options to a select field based on the value of a text input?
This is my input text:
<input type="text" id="amount" size="30" />
This is my element I want to add to:
<span id="span_combo">
<select name="foo" id="combo">
<option value="1">1</option>
<option value="2">2</option>
</select>
</span>
This is my current JS:
$("#amount").keyup(function(){
var flag;
$("#combo").show("slow");
var a = $("#amount").val();
if(a==""){
$("#span_combo select").remove(true);
}
var i;
for(i=1;i<=a-1;i++){
$("#span_combo").append($("#span_combo select").first().clone(true));
}
});
Something like this should do it
Live demo here : http://jsfiddle.net/NdpuM/1/
$("#amount").keyup(function(){
var $combo = $('#combo');
$combo.html('');
var value = parseInt($('#amount').val(), 10);
for (i = 1; i <= value; i++) {
var $option = $('<option>').val(i).html(i);
$combo.append($option);
}
});
Basically, clear the select box everytime there is a keydown and repopulate it. You could optimize this more by adding a few checks to see whether it's the same value
If you want to rebuild the entire array:
$("#amount").keyup(function(){
$("#combo").show("slow");
var a = $("#amount").val();
if(a==""){
$("#span_combo select").remove(true);
}
$('#combo').empty();
for(var i=1;i<=a-1;i++){
$('<option />').attr('value', i)
.text(i)
.appendTo($('#combo'));
}
});
I think this could work:
$("#amount").keyup(function() {
var current = $("#combo option").length;
if(current < $(this).val()) {
for(var i = current + 1;i<=$(this).val();i++) {
$("#combo").append('<option value="'+i+'">'+i+'</option>');
}
} else {
for(var i=(parseInt($(this).val(),10)+1);i<=current;i++) {
$('#combo option[value="'+i+'"]').remove();
}
}
});
You might want to add input verification to this function, but it does what you want if you use it right.
EDIT: Just to clarify, this code doesn't clear the whole select box on every keyup event, it just adds new options or removes the last ones to get the specified amount of values.

Categories

Resources