Making a value plural (Greater than, Less than) in Javascript - javascript

I have the following code:
$(function(){
var total_click = 0;
$("#mapKey a.showKey").click(function(){
total_click = total_click + 1;
$("#counter").text("I cheated " + total_click + " whole" + (total_click = 1 ? + ' time' + ((total_click > 1) ? 's ' : ' ') : ''));
return false;
});
});
I'm trying to have it output as such:
Clicked once: "I cheated 1 whole time."
Clicked more than once: "I cheated X whole times."
-- With an 's' at the end of "times".
The counter is working fine, it's just the last part making the "time" or "times" show up appropriately that I am having difficulty with.
Any ideas what I'm doing wrong?
Thanks!

Here is your problem: total_click = 1. Try changing it to total_click == 1. I don't see why you have that conditional in there however, as it won't work as you expect anyway. Try $("#counter").text("I cheated " + total_click + " whole time" + ((total_click == 1) ? ' ' : 's '));

You are not using the ternary operator correctly, and also assigning total_click to 1 instead of checking its value. I would suggest moving this to a function to simplify things.
function pluralize(singular, times) {
if (times == 1) return singular;
else return singular + 's';
}
Then change the string to
var text = "I cheated " + clicks + " whole " + pluralize("time", clicks);
Here's an example.

$(function(){
var total_click = 0;
$("#mapKey a.showKey").click(function(){
total_click = total_click + 1;
$("#counter").text("I cheated " + total_click + " whole " + (total_click == 1 ? "time" : "times");
return false;
});
});

It's okay to use suggested implementations for a trivial cases, however it will not scale for a bigger set of problems and will not work for multiple languages (or it will get ugly very fast).
With this in mind, I’ve created a very simple JavaScript library that can be used to pluralize words in almost any language. It transparently uses CLDR database for multiple locales. It’s API is very minimalistic and integration is extremely simple. It’s called Numerous.
I’ve also written a small introduction article to it: «How to pluralize any word in different languages using JavaScript?».
Feel free to use it in your project. I will also be glad for your feedback on it!

Related

How do I remove the last character in some text being copied from one field to another using JavaScript or other methods?

I have a form that I created to make my work easier and recently figured out how to make certain fields automatically generate a comma and separates after 5 letters or numbers have been typed into it (CPT codes for medical claims that I have to look up) using the same coding you would for putting spaces between numbers. I also have coding here that would force letters to be capitalized since I'm a bit OCD about that stuff for work:
<input name="checkbox24" type="checkbox" id="checkbox24" onClick="FillDetails24(this.form);" /><span style="background-color:yellow">CPT</span>
<input type = "text" size="8" class = "uc-text-smooth" name="textfield24" id="textfield24" />
<script language = "JavaScript">
const forceKeyPressUppercase = (e) => {
let el = e.target;
let charInput = e.keyCode;
if((charInput >=97) && (charInput <= 122)) { // lowercase
if(!e.ctrlKey && !e.metaKey && !e.altKey) { // no modifier key
let newChar = charInput - 32;
let start = el.selectionStart;
let end = el.selectionEnd;
el.value = el.value.substring(0, start) + String.fromCharCode(newChar) + el.value.substring(end);
el.setSelectionRange(start+1, start+1);
e.preventDefault();
}
}
};
document.querySelectorAll(".uc-text-smooth").forEach(function(current) {
current.addEventListener("keypress", forceKeyPressUppercase);
});
document.getElementById('textfield24').addEventListener('input', function (g) {
g.target.value = g.target.value.replace(/[^\dA-Z]/g, '').replace(/(.{5})/g, '$1, ').trim();
});
</script>
When I use the checkbox, it automatically generates pre-written text using the following JavaScript:
function FillDetails24(f) {
const elem = f.Reason;
const x = f.Action;
const y = f.Resolution;
f.Reason.value += ("Verify CPT " + f.textfield24.value + ". " + '\n');
f.Action.value += ("Adv on how to locate and use CPT lookup tool on plan website. Information provided in resolution. " + '\n');
f.Resolution.value += ("Adv on how to locate and use CPT lookup tool on plan website. Caller is looking to verify CPT " + f.textfield24.value + ". " + '\n' + '\n' );
}
However, because of the way that I put it together, the end result would be, "Adv on how to locate and use CPT lookup tool on plan website. Caller is looking to verify CPT V2020, 99213,. " The extra comma at the end is driving me nuts.
Since it was my first time using this
document.getElementById('textfield24').addEventListener('input', function (g) {
g.target.value = g.target.value.replace(/[^\dA-Z]/g, '').replace(/(.{5})/g, '$1, ').trim();
});
with this
function FillDetails24(f) {
const elem = f.Reason;
const x = f.Action;
const y = f.Resolution;
f.Reason.value += ("Verify CPT " + f.textfield24.value + ". " + '\n');
f.Action.value += ("Adv on how to locate and use CPT lookup tool on plan website. Information provided in resolution. " + '\n');
f.Resolution.value += ("Adv on how to locate and use CPT lookup tool on plan website. Caller is looking to verify CPT " + f.textfield24.value + ". " + '\n' + '\n' );
}
I'm not certain how I can code it to eliminate the last comma generated at the end when it pulls the value of textfield24.
This is a very long, complex html form I've coded by hand for fun and for personal use at work for 4 years with only a couple years of HTML training and a little bit of JavaScript I learned in high school forever ago and I've been busting my butt to make this work perfectly so that I only have to tweak the pre-written stuff when things change at work.
I'm at a loss on how to continue. Any suggestions?
You can replace with regex /,$/.
f = { textfield24: { value: 'V2020, 99213,'} }
console.log(f.textfield24.value);
console.log(f.textfield24.value.replace(/,$/, ''));
function FillDetails24(f) {
const elem = f.Reason;
const x = f.Action;
const y = f.Resolution;
f.Reason.value += ("Verify CPT " + f.textfield24.value + ". " + '\n');
f.Action.value += ("Adv on how to locate and use CPT lookup tool on plan website. Information provided in resolution. " + '\n');
f.Resolution.value += ("Adv on how to locate and use CPT lookup tool on plan website. Caller is looking to verify CPT " + f.textfield24.value.replace(/,$/, '') + ". " + '\n' + '\n' );
}
you can use substring to remove the last comma, but you have to make sure that the last comma always be there. otherwise, you're gonna remove something else.
const example = "Adv on how to locate and use CPT lookup tool on plan website. Caller is looking to verify CPT V2020, 99213,. ";
const result = example.substring(0, example.lastIndexOf(",")) + ".";
console.log(result);

Javascript .indexof 'typeError' error despite forcing string conversion

JS drives me insane with issues like this. I have the following code which creates a string (composed of session data and date information) to be written to an array, as such:
var _writes = String(req.session.subscriber + ":" + req.session.postal + "[" + req.session.id + "]=" + _onYear + "-" + _onMonth + "-" + _onDay + "-" + _onHour + "-" + _onMinute);
_users.push(_writes);
Later, I wish to perform an 'indexof' command on the string of the array, as such:
for (_cycle = 0; _cycle < _users.length; ++_cycle) {
_seeks = String(_users[_cycle]);
_score = _seeks.indexof("="); //ERROR THROWN HERE
//do other stuff here...
} //for loop
My error is "TypeError: _seeks.indexof is not a function"...? I thought by converting everything to a string I should be able to perform the 'indexof' command. Can somebody please advise what the issue is here? I thank you in advance.
Probably not a js issue. You are using "indexof" instead of "indexOf" (Uppercase O). Check https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/indexOf
It should be:
_seeks.indexOf("=");
Don't give up, it will make sense soon :)

My if and else statement always think it's -and [duplicate]

This question already has answers here:
IF Statement Always True
(3 answers)
Closed 4 years ago.
I have a selector on my page that has -and or -or. I'd like to change the content of a div depending on what users choose with -And or -Or.
My if and else statements aren't working right now, well it's almost working it just always add -And. It looks as if it always see's -And?
First time I'm trying to use an if and else statement and I think I made mistake.
<script>
function Andor' + count + '(selTag) {
var x = selTag.options[selTag.selectedIndex].text;
if (x = '-and'){
document.getElementById("and-or-' + count + '").innerHTML = " " + x + " ";
} else {
document.getElementById("and-or-' + count + '").innerHTML = " " + x + " (";
}
}
</script>
You use one =, which is 'assign'. You want === (or ==) for 'equals'.
You do the same as: var example = 'foo';. You set the value to a string ('-and'), which always results in true, which makes it look like it's true.
What you want is example=='foo' to check if the content of example equals 'foo'.
Suggested reading material: https://codeburst.io/javascript-double-equals-vs-triple-equals-61d4ce5a121a

How to .join() arrays nicely

I find Array.prototype.join() method very useful when constructing strings from arrays, like
"one two three".split(' ').join(', ');
But very often I want to generate a string like this:
"one, two and three"
The method I use is this:
var parts = "one two three".split(' ');
parts.slice(0, parts.length-1).join(', ') + ' and ' + parts.slice(-1)
This generates what I want, however is an ugly solution I should put into a separate function.
I love one liners and believe there should be more elegant one-liner in JS to accomplish this task. Can someone provide me with one ?
EDIT
Please no need to comment that it is a bad practice to write unreadable code. I ask for one! :)
I have learned a lot from one liners about the language constructs and so have a situation where I see a possibility for one. No offense.
FINAL EDIT
I appreciate Pavlo answer as it really shows how easily one liner can become a beautiful readable code. Since I was asking for a one liner so as per my question h2ooooooo gets the highest score.
I'm surprised with the amount of cryptic solutions and the fact that nobody used pop():
function splitJoin(source) {
var array = source.split(' ');
var lastItem = array.pop();
if (array.length === 0) return lastItem;
return array.join(', ') + ' and ' + lastItem;
}
splitJoin('one two three'); // 'one, two and three'
splitJoin('one two'); // 'one and two'
splitJoin('one'); // 'one'
Edit: Modified to properly work for any string.
It's still a function, but why not use a prototype for this?
Array.prototype.joinNice = function() {
return this.slice(0, this.length-1).join(', ') + ' and ' + this.slice(-1);
}
"one two three".split(' ').joinNice();
//one, two and three
I'm surprised no one has pointed out that most of these answers won't work properly with zero or one elements in the array. Here's a simple solution that will work fine for 0+ elements:
function prettyJoin(array) {
return array.length > 1
? array.slice(0, -1).join(", ") + " and " + array.slice(-1)
: array + "";
}
prettyJoin([]); // ""
prettyJoin("one".split(" ")); // "one"
prettyJoin("one two".split(" ")); // "one and two"
prettyJoin("one two three".split(" ")); // "one, two and three"
What about this?
(parts = "one two three".split(" ")).slice(0, parts.length - 1).join(", ") + " and " + parts.slice(-1);
"one two three".split(' ').join(', ').replace(/^(.+),/, "$1, and")
(It even more grammatically correct!)
Though it won't work as expected if last part itself contains a comma.
If you want a one liner
"one, two and three"
A bit more generic..
function splitJoin (str,del,arr) {
for (x=str.split (del),i=x.length;i--;x[i]+=(arr[i]||"")); return x.join("");
}
console.log (
splitJoin ("one two three"," ", [", "," and "])
) //one, two and three
I'm not saying it's pretty though. Or supported in all browsers.
parts.reduce(function(val1, val2, i, arr) {return val1 + (i + 1 < arr.length ? ', ' : ' and ') + val2});

display pointlabel in highlighter jqplot

I've many series of just two points on a graph to simulate a timeline. These points have a pointlabel. I'd like to have the name of that pointlabel in the highlighter. How do I do that?
please see my JsFiddle http://jsfiddle.net/NVbjv/8/
I'd tried to add a highlighter object to each series, and give it a format string. But how can I make this more dynamic?
I also like to only display time in the hoverbox-thingy in the bottom right. How do I get remove the ",1 " and ",2"?
The only idea that comes to my mind is to use a custom processing of the tooltip of highlighter and cursor. Something along the lines as it is presented here.
In your case you would apply the following code:
$("#container").bind('jqplotMouseMove', function(ev, gridpos, datapos, neighbor, plot) {
var date = new Date(datapos.xaxis);
var time = "" + (date.getHours() < 10 ? "0" + date.getHours() : date.getHours()) + ":" + (date.getMinutes() < 10 ? "0" + date.getMinutes() : date.getMinutes());
$(".jqplot-cursor-tooltip").html(time + " Oi");
if (neighbor) {
$(".jqplot-highlighter-tooltip").html("Label name= " + neighbor.data[2] + "; time= " + time);
}
});
The working code sample is available here.
EDIT:
In Chrome I have noticed that the null is printed for the pointLabels therefore use empty strings for their values instead.

Categories

Resources