Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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!

like image 414
Muhambi Avatar asked Dec 20 '22 08:12

Muhambi


1 Answers

  • 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();
like image 133
Tim M. Avatar answered Dec 24 '22 01:12

Tim M.