Change to plural if the value in the text box is greater than 1

I have a textbox and selectbox as follows:

<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 JSFiddle: http://jsfiddle.net/T3Sxb/

As you can see, the selection options are in the form of word(s)

but i want to have a script where

  • If the number in the input field is 1, the value in the parameters is in the form of word
  • If the number in the input field is greater than 1, the value in the parameters is plural.

Is it possible? How can i do this? Thanks for the help!

+4
source share
3 answers

I use data attributes so that you can declare the correct single / multiple forms for each element. Just adding "s" does not work in many cases.

Also note that null elements usually (always?) Take 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(); 
+6
source

You can try the following: 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] ); } }); }); 
+3
source

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

All Articles