Change to plural if value in textbox is greater than 1 - javascript

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')));
}
});
});

Related

How do I show a message for a specific dropdown selection using javascript?

I would like to show a message when someone makes a specific selection from an HTML dropdown list. I have this so far:
<select name="configoption[56]" onchange="recalctotals()">
<option value="235"">USA</option>
<option value="206">Europe</option>
</select>
<span class="message">You selected USA!</span>
And the script:
$(document).ready(function() {
$('#configoption[56]').change(function() {
var selectedValue = $('#configoption[56]').find(":selected").text();
if ( selectedValue == '235' ) {
$('.message').show();
} else {
$('.message').hide();
}
});
});
The above does not appear to be working for me, any suggestions? I would also like to be able to show the message on multiple selected values.
Well your .change function is specifically binded to an element with id="configoption[56]" So just add id to your select element as below
<select name="configoption[56]" id="configoption[56]" onchange="recalctotals()">
//Options
</select>
UPDATE
As per #T.J.Crowder's suggestion on invalid selector I would like to modify a slight change on the id. You can use configoption56 as id and write your select.change as follows:
<select name="configoption[56]" id="configoption56" onchange="recalctotals()">
<!--Options-->
</select>
.change
$('#configoption56').change(function() {
//other codes
});
$('#configoption[56]') is looking for an element with the id, not name, configoption[56] (or it would be, but the selector is invalid, you'd have to escape those brackets).
To use the name:
$('select[name="configoption[56]"]')...
Separately, you can just use val, you don't have to use find to get the selected option. You can also use toggle for show/hide:
$(document).ready(function() {
$('select[name="configoption[56]"]').change(function() {
$('.message').toggle($(this).val() == '235');
});
});
Re your comment about toggling based on || and two values:
$(document).ready(function() {
$('select[name="configoption[56]"]').change(function() {
var value = $(this).val();
$('.message').toggle(value == '235' || value == '123');
});
});
I should be doing it like this: http://jsfiddle.net/nmn17cr6/
HTML:
<select name="configoption[56]" id="configoption" onchange="recalctotals()">
<option value="1">Dummy</option>
<option value="235">USA</option>
<option value="206">Europe</option>
</select>
<span class="message">You selected USA!</span>
CSS:
.message {
display:none;
}
jQuery:
$(document).ready(function() {
$('#configoption').change(function() {
var selectedValue = $(this).val();
if ( selectedValue == '235' ) {
$('.message').show();
} else {
$('.message').hide();
}
});
});
Your approach needs a little modification. All you had to do these changes
$(document).ready(function() {
$("select[name=configoption[56]]").change(function() { // change jquery selector for name
var selectedValue = $('#configoption[56]').val(); // and val to get the value
if ( selectedValue == '235' ) {
$('.message').show();
} else {
$('.message').hide();
}
});
});
And with the same jQuery code. below has to be
<select name="configoption[56]" >
// onchange="recalctotals()"> was not required

issue with change function on select option in Jquery

I have a little select form. When I change options using JQUERY, new suitable price appears inside .prices. AN old price is 100 $. if user is student or pupil, I want make him discount -10 $. So when user choose option student or pupil price is changed from 100 to 90$. But when user choose option again to pupil it must not be change the price, but it changes it to 80 $. Again when choose option student, price was changed to 70. I exactly want that if user choose option: student or pupil, there will be -10 $ discount.
you can ask why I used each function? The option: other is selected and first time page shows price 110$. each function fixed this problem. I have also JS fiddle, you can check it.
Sorry for my English Language.
DEMO
HTML
<select name="status" id="status">
<option value="1">Student</option>
<option value="2">Pupil</option>
<option value="3" selected>Other</option>
</select>
<div class="price">
<span class="prices">100</span> $
</div>
JQUERY
$( "#status" ).change(function () {
var price2 = ($(".prices").text());
$('.prices').text('');
var value = $( "#status option:selected" ).val();
if(value=="3")
{
new_price2 = +price2 + +10;
$('.prices').append(new_price2);
}
else
{
new_price2 = price2 - 10;
$('.prices').append(new_price2);
}
})
.change();
$('#status option').each(function() {
if(this.selected)
{
var price2 = ($(".prices").html());
$('.prices').html('');
new_price2 = price2 - 10;
$('.prices').append(new_price2);
}
});
You only need the change handler in your jQuery code. Also, you need to keep a static base price value so that you can do all calculations on that instead of keeping a running total of all changes. Try this:
$("#status").change(function () {
var price2 = $(this).data('base-price');
if ($("option:selected", this).val() == "3") {
new_price2 = price2;
} else {
new_price2 = price2 - 10;
}
$('.prices').text(new_price2);
}).change();
Example fiddle
Try this:
$( "#status" ).change(function () {
var price2 = ($(".prices").text());
$('.prices').text('');
var value = $( "#status option:selected" ).val();
if(value=="3"){
new_price2 = price2;
}
else{
new_price2 = price2 - 10;
}
$('.prices').html(new_price2);
})
DEMO here.

form select option dynamic attr

I need to make Select name with option value, to select a specific value or index. the data where comes from db in a value "{{design}}".
I do get the value currectly, but I dont manage to set "selected" on the currect option value.
here is the code:
console.log("{{design}}");
$(document).ready(function () {
var options = $('select').children('option');
var size = $('select').children('option').length;
for (i=0;i<size;i++)
{
if ( options[i].innerHTML==="{{design}}")
{
options.selectedIndex=i;
}
}
});
the html is :
<select name="design" required id="design" >
<option value="1">flowers</option>
<option value="2">classic</option>
<option value="3">roses</option>
</select>
I need to make to currect {{design}} value, lets say it's 2, so it will be <option value="2" selected>classic</option>`
thanks!
SOLVED
Hi, found the solution to the issue, if anyone eles goes into trouble.
$(document).ready(function () {
var options = $('select').children('option');
var size = $('select').children('option').length;
for (i=0;i<size;i++)
{
if ( $('select').children('option')[i].value === "{{design}}")
{
$('select').children('option')[i].selected=true;
}
}
});
the currect way is to find the right option value and then-> [i].selected=true
goodluck
Try this
var selectedvalue=2; //option with value 2 should be selected
$("#design option[value=selectedvalue]").attr("selected","selected");
Hope this helps...
If I understood right, you are on the right path just taking a minor detour. Try this:
if ( options[i].innerHTML==="{{design}}")
{
options.attr('selected', 'selected');
}
The example of .each() usage:
$(document).ready(function(){
$('select option').each(function(i){
if( i.value === "{{design}}"){
$(this).attr('selected','selected');
}
});
});
try this:
$(document).ready(function(){
$('select option').each(function(i){
//if this option contains the word "{{design}}" Then this is selected
if( $(this).html().indexOf("{{design}}") != -1)
$(this).attr('selected',true);
});
});

How to select the HTML5 data attribute in jQuery?

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>

How do i manipulate select box using jquery?

I have some select boxes like the following:
<select id="my_box1" rel="cal_10">
<option value="A"></option>
</select>
<select id="my_box2" rel="cal_10.50">
<option value="A"></option>
</select>
....
<select id="my_boxn">
<option value="B"></option>
</select>
On changing, I want to add the related value (that is 10 and 10.50) only when the select boxes has the same option value.
For Example: if the first and second select box has option value as A, then I want to add it.
How can I do this using jQuery?
Well, I really can't tell exactly what you're asking, so I'll just guess.
I'm guessing that when a select element receives a change event, we should find all other selects where the selected value is the same, and sum the numeric portion of the rel attribute.
If so, you can do this:
var boxes = $('select[id^="my_box"]');
boxes.on('change', function() {
var n = 0,
val = this.value;
boxes.each(function() {
if( this.value === val ) {
n += +$(this).attr('rel').replace('cal_','');
}
});
alert( n );
});
If you're using a version of jQuery older than 1.7, then use boxes.bind instead of boxes.on.
Something like this, I believe:
$(function() {
$('select#my_box1, select#my_box2').bind('change', function() {
if ($('select#my_box1').val() == $('select#my_box2').val())
$('select#my_box2').append('<option value="10">10</option><option value="10.50">10.50</option>');
else $('select#my_box2').find('option[value="10"], option[value="10.50"]').remove();
});
});
I tried by below code,
$('select').change(function(){
var totalWeight = 0;
var post_array = [];
var actual_val = value;
//alert(actual_val);
var x=0;
$("select").each(function(index, selectedObj) {
current = $(this).val();
var combined = $(this).attr('rel');
if(combined!=undefined)
{
combined = combined.split("_");
var is_combined = combined[0];
var combined_pid = combined[1];
if(actual_val == current && is_combined == "cal"){
post_array[x++] = combined_pid ;
totalWeight+=parseFloat(combined_pid);
}
}
});
alert(totalWeight);
});
I will get my total value in totalWeight

Categories

Resources