I am trying to make text singular or plural based on the value of templateCount
. If templateCount
's value is 1 then I just want 'Template' to say that, but if templateCount
is plural, I want it to say 'Templates Selected'.
What am I doing wrong with my code?
$('#templateCount').html(templateCount + " Templates Selected" + templateCount.length == 1 ? "" : "s");
Are you sure you thought this through? You have the string "Templates selected"
there and you are conditionally appending s
to the end of that (which would make it "Templates Selecteds"
).
Do this:
$('#templateCount').html(templateCount +
" Template" +
(templateCount === 1 ? "" : "s") +
" Selected");
I'm not sure if what you mean is that you want to put an 's' on the end if templateCount == 1 or if templateCount's length is 1. Those can be two very different things.
If you want it based on the variable == 1, then I would try:
var templateCount;
// set it somewhere
var plural = templateCount === 1 ? "" : "s";
$('#templateCount').html(templateCount + " Template"+plural+ " Selected");
If it's the length you're actually after, change plural to
var plural = templateCount.length > 1 ? "" : "s";
Try this
function makeStatement(templateCount) { return templateCount + " Template" + (templateCount == 1 ? "" : "s") +" Selected"; } console.log(makeStatement(1)); console.log(makeStatement(2));
And in your case
$('#templateCount').html(templateCount + " Template" + (templateCount == 1 ? "" : "s") + " Selected");
也许我读错了您的问题,但是您是否仅需要更改代码以使其看起来像这样?
$('#templateCount').html(templateCount + " Template" + (templateCount.length == 1 ? "" : "s") + " Selected");
Like this?
var templateCount = [ 1 ]; function test() { var tmp = templateCount.length == 1 ? 1 : "Templates Selected"; $("#test").val(tmp); }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <input id="test"> <button onclick="test()">Test</button>
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.