I want to have a user's input auto fill the punctuation of a phone number to look like this (xxx) xxx-xxxx. I have written an example jfiddle here but it breaks when filling in the last 4 digits of the phone number.
$("#phone").on("change keyup paste", function () {
var output;
var input = $("#phone").val();
input = input.replace(/[^0-9]/g, '');
var area = input.substr(0, 3);
var pre = input.substr(3, 4);
var tel = input.substr(6, 4);
if (area.length < 3) {
output = "(" + area;
} else if (area.length == 3 && pre.length < 3) {
output = "(" + area + ")" + " " + pre;
} else if (area.length == 3 && pre.length == 3) {
output = "(" + area + ")" + " " + pre + "-" + tel;
}
$("#phone").val(output);
});
HTMl:
<input id='phone'></input>
I realize this post is older but i found it quite useful and made some minor modifications to enhance it for all telephone fields and to allow for deleting characters if the user makes a mistake.
$("input[type='tel']").each(function(){
$(this).on("change keyup paste", function (e) {
var output,
$this = $(this),
input = $this.val();
if(e.keyCode != 8) {
input = input.replace(/[^0-9]/g, '');
var area = input.substr(0, 3);
var pre = input.substr(3, 3);
var tel = input.substr(6, 4);
if (area.length < 3) {
output = "(" + area;
} else if (area.length == 3 && pre.length < 3) {
output = "(" + area + ")" + " " + pre;
} else if (area.length == 3 && pre.length == 3) {
output = "(" + area + ")" + " " + pre + "-" + tel;
}
$this.val(output);
}
});
});
<input type="tel" placeholder="(XXX) XXX-XXXX" />
When you're getting the pre code from the number, you're trying to get the index of 4, instead of four digits. So change that, and it should start working:
var pre = input.substr(3, 3);
If you don't want the dynamic filling, the other posted answers might be useful.
Regular expressions are your friend.
var ok = phNum.search(/^\(?\d{3}\D*\d{3}\D*\d{4}$/);
if (ok==0) {
var parts = phNum.match(/^\(?(\d{3})\D*(\d{3})\D*(\d{4})$/);
output.value='('+parts[1]+') '+parts[2]+'-'+parts[3];
}
Accepts: 404-555-1234, 4045551234, (404) 555-1234, etc.
Returns: (404) 555-1234
If you started to use regexp, why dont you go whole way through. Below the code that filter input value and convert it to your look.
Beware, this code only for value that contains only digits. You could block any other types via plugins or your own code. (jquery.numeric plugin is a good choice)
jquery
$(document).on('change', '.js-phone-number', function() {
var
$this = $(this),
number = $this.val();
number = number.replace(/(\d{3})(\d{3})(\d{4})/, '($1)-$2-$3');
$this.val(number);
});
You are fetching variable pre as substring of length 4 and then checking it for it is less than or equal to 3. So, basically your last else if block will never be true.
Change var pre = input.substr(3,3);
Your code will work fine.
Related
The code is used in a HTML document, where when you press a button the first word in every sentence gets marked in bold
This is my code:
var i = 0;
while(i < restOftext.length) {
if (text[i] === ".") {
var space = text.indexOf(" ", i + 2);
var tekststykke = text.slice(i + 2, space);
var text = text.slice(0, i) + "<b>" + tekststykke + "</b>" + text.slice(i + (tekststykke.length + 2));
var period = text.replace(/<b>/g, ". <b>");
var text2 = "<b>" + firstWord + "</b>" + period.slice(space1);
i++
}
}
document.getElementById("firstWordBold").innerHTML = text2;
}
It's in the first part of the code under function firstWordBold(); where it says there is an error with
var space1 = text.indexOf(" ");
Looks like you're missing a closing quote on your string, at least in the example you provided in the question.
Your problem is the scope of the text variable. In firstWordBold change every text to this.text, except the last two where you re-define text
Also, if you want to apply bold to the first word this is easier...
document.getElementById('test-div-2').innerHTML = '<b>' + firstWord + '</b>' + restOftext;
It now works for me, with no errors and it applies bold to the first word.
Here's how the function ended up,
function firstWordBold() {
console.log('bolding!');
var space1 = this.text.indexOf(' ');
var firstWord = this.text.slice(0, space1);
var restOftext = this.text.slice(space1);
document.getElementById('test-div-2').innerHTML = '<b>' + firstWord + '</b>' + restOftext;
}
To make every first word bold, try this...
function firstWordBold() {
let newHTML = '';
const sentences = this.text.split('.');
for (let sentence of sentences) {
sentence = sentence.trim();
var space1 = sentence.indexOf(' ');
var firstWord = sentence.slice(0, space1);
var restOftext = sentence.slice(space1);
newHTML += '<b>' + firstWord + '</b>' + restOftext + ' ';
}
document.getElementById('test-div-2').innerHTML = newHTML;
}
One last edit, I didn't notice you had sentences ending with anything other that a period before. To split on multiple delimiters use a regex, like so,
const sentences = this.text.split(/(?<=[.?!])\s/);
I have set of numbers from an excel like this
05143
05250
05252
05156
05143
05441
05143
05031
05050
05101
05821
05822
05861
and after every 5th digit I wanted to add a ,
My problem is that after every 5th digit it considers a white space carriage as a digit and then split the items such as
05143 ↵0525 0↵052 50↵05 and so on...
and that's why , split is breaking. I tried to replace it as item.replace(/↵/g, ""); but its not working.
here is my code
item.replace(/↵/g, "")
console.log(item)
if(item.length > 5){
for (var i = 0; i < item.length; i += 5) {
chunks.push(item.substring(i, i + 5));
}
console.log(chunks)
var tempItem;
chunks.forEach(function(item2) {
if (tempItem == undefined) {
tempItem = "'" + item2 + "'";
} else {
tempItem = tempItem + ",'" + item2 + "'";
}
})
It's not clear from the question what character code you have in your string that cause the problem.
But I think that if you use this general replace you will solve.
item.replace(/\W/g, '')
it works when we write it as
item.split('\n')
I created a "custom append" function that taking in two parameters and appending their's value in a one line.
I need to make the first parameter's value to append in a gray color but the second value have to stay as it is.
I tried to use a "css(property, name)" function but it didn't work.
Where is my fallacy and how to get a needed result?
var showText = function(who, str) {
if (str !== "") {
var colorWho = who.name;
colorWho.css("color", "gray");
$("#storyBoard").append("<br>" + colorWho + ": " + str + "<br>");
var element = document.getElementById("storyBoard");
element.scrollTop = element.scrollHeight;
}
};
Here you go
Fiddle
CSS
p > span { /* If you're going to take this to a larger environment, you may want to use classes instead */
color:gray;
}
JS
var showText = function(who, str) {
if(str !== ""){
var colorWho = who.name;
$("#storyBoard").append("<p><span>"+colorWho + "</span>: " +str+ "<p>");
}
};
var obj = {
name : "Preacher",
}
showText(obj, "Is an awesome comic book !");
Is this what you require?
$("#storyBoard").append("<br><span style='color:gray;'>" + colorWho + "</span>: " + str + "<br>");
Okay, that title will sound a bit crazy. I have an object, which I build from a bunch of inputs (from the user). I set them according to their value received, but sometimes they are not set at all, which makes them null. What I really want to do, it make an item generator for WoW. The items can have multiple attributes, which all look the same to the user. Here is my example:
+3 Agility
+5 Stamina
+10 Dodge
In theory, that should just grab my object's property name and key value, then output it in the same fashion. However, how do I setup that if-statement?
Here is what my current if-statement MADNESS looks like:
if(property == "agility") {
text = "+" + text + " Agility";
}
if(property == "stamina") {
text = "+" + text + " Stamina";
}
if(property == "dodge") {
text = "+" + text + " Dodge";
}
You get that point right? In WoW there are A TON of attributes, so it would suck that I would have to create an if-statement for each, because there are simply too many. It's basically repeating itself, but still using the property name all the way. Here is what my JSFiddle looks like: http://jsfiddle.net/pm2328hx/ so you can play with it yourself. Thanks!
EDIT: Oh by the way, what I want to do is something like this:
if(property == "agility" || property == "stamina" || ....) {
text = "+" + text + " " + THE_ABOVE_VARIABLE_WHICH_IS_TRUE;
}
Which is hacky as well. I definitely don't want that.
if(['agility','stamina','dodge'].indexOf(property) !== -1){
text = "+" + text + " " + property;
}
If you need the first letter capitalized :
if(['agility','stamina','dodge'].indexOf(property) !== -1){
text = "+" + text + " " + property.charAt(0).toUpperCase() + property.substr(1);
}
UPDATE per comment:
If you already have an array of all the attributes somewhere, use that instead
var myatts = [
'agility',
'stamina',
'dodge'
];
if(myatts.indexOf(property) !== -1){
text = "+" + text + " " + property.charAt(0).toUpperCase() + property.substr(1);
}
UPDATE per next comment:
If you already have an object with the attributes as keys, you can use Object.keys(), but be sure to also employ hasOwnProperty
var item = {};
item.attribute = {
agility:100,
stamina:200,
dodge:300
};
var property = "agility";
var text = "";
if(Object.keys(item.attribute).indexOf(property) !== -1){
if(item.attribute.hasOwnProperty(property)){
text = "+" + text + " " + property.charAt(0).toUpperCase() + property.substr(1);
}
}
Fiddle: http://jsfiddle.net/trex005/rk9j10bx/
UPDATE to answer intended question instead of asked question
How do I expand the following object into following string? Note: the attributes are dynamic.
Object:
var item = {};
item.attribute = {
agility:100,
stamina:200,
dodge:300
};
String:
+ 100 Agility + 200 Stamina + 300 Dodge
Answer:
var text = "";
for(var property in item.attribute){
if(item.attribute.hasOwnProperty(property)){
if(text.length > 0) text += " ";
text += "+ " + item.attribute[property] + " " + property.charAt(0).toUpperCase() + property.substr(1);
}
}
It's unclear how you're getting these values an storing them internally - but assuming you store them in a hash table:
properties = { stamina: 10,
agility: 45,
...
}
Then you could display it something like this:
var text = '';
for (var key in properties) {
// use hasOwnProperty to filter out keys from the Object.prototype
if (h.hasOwnProperty(k)) {
text = text + ' ' h[k] + ' ' + k + '<br/>';
}
}
After chat, code came out as follows:
var item = {};
item.name = "Thunderfury";
item.rarity = "legendary";
item.itemLevel = 80;
item.equip = "Binds when picked up";
item.unique = "Unique";
item.itemType = "Sword";
item.speed = 1.90;
item.slot = "One-handed";
item.damage = "36 - 68";
item.dps = 27.59;
item.attributes = {
agility:100,
stamina:200,
dodge:300
};
item.durability = 130;
item.chanceOnHit = "Blasts your enemy with lightning, dealing 209 Nature damage and then jumping to additional nearby enemies. Each jump reduces that victim's Nature resistance by 17. Affects 5 targets. Your primary target is also consumed by a cyclone, slowing its attack speed by 20% for 12 sec.";
item.levelRequirement = 60;
function build() {
box = $('<div id="box">'); //builds in memory
for (var key in item) {
if (item.hasOwnProperty(key)) {
if (key === 'attributes') {
for (var k in item.attributes) {
if (item.attributes.hasOwnProperty(k)) {
box.append('<span class="' + k + '">+' + item.attributes[k] + ' ' + k + '</span>');
}
}
} else {
box.append('<span id="' + key + '" class="' + item[key] + '">' + item[key] + '</span>');
}
}
}
$("#box").replaceWith(box);
}
build();
http://jsfiddle.net/gp0qfwfr/5/
i have created one form for user to submit a abstract. but while submitting i need to check weather they have added more than 250 words or not. i need to allow only 250 words . how to do this ?
i have tried some JavaScript but it works for only 250 character.
here is my code
function maxlength(element, maxvalue)
{
var q = eval("document.upload."+element+".value.length");
var r = q - maxvalue;
var msg = "Sorry, you have input "+q+" characters into the "+
"text area box you just completed. It can return no more than "+
maxvalue+" words to be processed. Please abbreviate "+
"your text by at least "+r+" words";
if (q > maxvalue) alert(msg);
}
and my textarea is :
<tr>
<td><label>Abstract Details</label> </td>
<td><label>Please enter data, at most 250 words:</label>
<br/><textarea rows="6" cols="80"name="box_name" onChange="maxlength('box_name', 250)" style="width: 257px; height: 131px;"> </textarea></td>
</tr>
<tr>
how to limit for 250 words .
thanks in advance
To prevent submitting form when there is more than 250 characters in the textarea, add id="box_id" to your textarea and add this event to form element:
onsubmit="return maxlength(getElementById('box_id'), 250);
Now in your function split this value by multiple spaces:
function maxlength(element, maxvalue){
var q = element.value.split(/[\s]+/).length;
if(q > maxvalue){
var r = q - maxvalue;
alert("Sorry, you have input "+q+" words into the "+
"text area box you just completed. It can return no more than "+
maxvalue+" words to be processed. Please abbreviate "+
"your text by at least "+r+" words");
return false;
}
}
To take advantage from new HTML attributes, you can also add "pattern" attribute to textarea with regex limiting input to 250 words:
<textarea rows="6" cols="80"name="box_name" onChange="maxlength(this, 250)" style="width: 257px; height: 131px;"
pattern="^(?:\b\w+\b[\s\r\n]*){1,250}$">
</textarea>
This regex pattern was taken from following SO thread, which touches similar problem with 250 words: Limit the number of words in a response with a regular expression
use this:
function maxlength(element, maxvalue)
{
var value = $(elment).val();
var words = value.split(' ');
var msg = 'Sorry, you have input ' + words.length + ' words into the ' +
'text area you just completed. It can return no more than ' +
maxvalue + ' words to be processed. Please abbreviate ' +
'your text by at least ' + (words.length - maxvalue) + ' words';
if (words.length > maxvalue) {
alert(msg);
}
}
If you want 250 characters, You can set the maxlength attribute to 250
if you want 250 words:
function maxlength(obj,wordLen){
var len = obj.value.split(/[\s]+/);
if(len.length > wordLen){
alert("You cannot put more than "+wordLen+" words in this text area.");
}
}
Function Call:
onChange="maxlength(this, 250)"
Working Demo
This statement eval("document.upload." + element + ".value.length") will return no of characters not words, if you want to limit 250 words then just split value of textarea with space and verify it with max words allowed and then return appropriate message:
You may try this code.
function maxlength(element, maxvalue) {
var q = eval("document.upload." + element + ".value");
var textLength = q.split(/\S+/).length - 1
var r = textLength - maxvalue;
var msg = "Sorry, you have input " + textLength + " characters into the " +
"text area box you just completed. It can return no more than " + maxvalue + " words to be processed. Please abbreviate " +
"your text by at least " + r + " words";
if (textLength > maxvalue) alert(msg);
}