[英]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/ 这是一个JSFiddle: http : //jsfiddle.net/T3Sxb/
As you can see, the select options are in the form of word(s)
如您所见,选择选项为
word(s)
形式
but I want to have a script where when 但是我想要一个脚本,什么时候
word
word
形式 Is this possible? 这可能吗? How can I do this?
我怎样才能做到这一点? Thanks for all help!
感谢所有帮助!
input[type="number"]
: http://jsfiddle.net/T3Sxb/15/ input[type="number"]
替代: http : //jsfiddle.net/T3Sxb/15/ 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.
在许多情况下,仅添加“ s”并不起作用。
Also note that zero items usually (always?) takes a plural form. 还要注意,零项通常(总是?)采用复数形式。
HTML 的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 的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/ 您可以尝试以下方法: 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. 从用户体验的角度来看,我认为
(s)
是完全可以接受的。 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')));
}
});
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.