JQuery: Getting number from html element and alter it in Jquery/Javascript - javascript

I have some number printed on my html for special usage, therefore i need to grab it from html, alter it in javascript and output again.
So i have few numbers like below in my HTML:
<p id="usage">6564</p>
and i'd like to have a if statment in order do some modifcation of "6564",
below is some pseudo codes, which tells what i'd like to do.
var checker = $("#usage").html();
if(checker >= 2 digits){
//display the first two digits
}
else {
$("#usage").html("1");
}
The if statement should display the first two digits only, if the number has more than 2 digits otherwise it will return "10", So the result should be "65"
Solution :
For people who experience the same issues as me
var checker = $(".totalPage").text().replace(/,/g, ""); //it you have comma between your number like 6,545
var pagevalue = parseInt(checker.slice(0,2));
if(checker.length >= 2){
$(".totalPage").text(pagevalue+1);//you can modify the our put even further
}
else {
$(".totalPage").text("10");
}

var checker = $("#usage").text();
if(checker.length >= 2){
$("#usage").text(checker.slice(0,2));
}
else {
$("#usage").text("10");
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<p id="usage">6564</p>
Use slice to get the 2 digits.
Use length to tell if number has more than 2 digits

Here's the pure Js version.
function extractFunction() {
var checker = document.getElementById("usage").innerHTML;
if (checker.length > 2) { //if cheacker lentgh > 2
var result = checker.substr(0, 2); //start at char 1 and pull first 2 chars
document.getElementById("usage").innerHTML = result;
}
else{
document.getElementById("usage").innerHTML = "1";
}
}
<p id="usage">6564</p>
<button onclick="extractFunction()">Extract it</button>

Related

How to create ordered list inside text area using javascript?

I have a text area where I add the number of orderlist item on click of a button.This is my code,
var addListItem = function() {
if (!this.addListItem.num) {
this.addListItem.num = 0
}
++this.addListItem.num;
var text = document.getElementById('editor').value;
console.log('text', text);
var exp = '\n' + this.addListItem.num + '.\xa0';
text = text.concat(exp);
document.getElementById('editor').value = text;
}
<div>
<button onclick="addListItem()">NumberList</button>
<textarea id="editor" col=10 rows=10></textarea>
</div>
As I have used a static variable to increment it increments on every click and so if I delete the list and create a new list again it doesn't starts from '1' and also I couldn't figure out how to update the numbers when a item is added in between.Could anyone suggest me how to fix this?
If you want a more robust solution that handles all sorts of different cases, you can use regular expressions to detect what number you're at in your list.
This solution also allows users to type in their own numbers and the button click WILL STILL WORK!
That's because this solution uses the text area content as the source of truth and doesn't track state on the side.
var addListItem = function() {
var text = document.getElementById('editor').value;
// regex to match against any new line that has a number and a period
// and extracts the number. feel free to use regex101.com to understand
// this in more depth.
var listNumberRegex = /^[0-9]+(?=\.)/gm;
var existingNums = [];
var num;
// get all the matches
while ((num = listNumberRegex.exec(text)) !== null) {
existingNums.push(num);
}
// sort the values
existingNums.sort();
// use the existing biggest number + 1 or use 1.
var addListItemNum;
if (existingNums.length > 0) {
// get last number and add 1
addListItemNum = parseInt(existingNums[existingNums.length - 1], 10) + 1;
} else {
// otherwise if there's nothing, just use 1.
addListItemNum = 1;
}
var exp = '\n' + addListItemNum + '.\xa0';
text = text.concat(exp);
document.getElementById('editor').value = text;
}
<div>
<button onclick="addListItem()">NumberList</button>
<textarea id="editor" col=10 rows=10></textarea>
</div>
understanding regular expressions is tricky, feel free to view https://regex101.com/r/gyX7oO/1 to get a better understanding of what is going on.
You can try something like this:
Logic:
On every click, get the text in textarea and split it be new line.
Now that you have line items, you need to get last sentence that starts with a numeric value. But user can enter new lines on his own to format text.
For this, loop on every line and validate it it starts with number followed by ..
If yes, use substring to fetch this number and parse it to int. If no match is found, you can return 0.
This will ensure the numbering system and you do not need a variable to hold last value.
Note: This logic assumes that last value will be the maximum. If you wish to handle that, you can just compare n and parseInt and assign maximum value
Sample:
var addListItem = function() {
var text = document.getElementById('editor').value;
var exp = '\n' + (getLastNumber(text) + 1) + '.\xa0';
text = text.concat(exp);
document.getElementById('editor').value = text;
}
function getLastNumber(str){
var list = str.split(/[\r\n]/g);
var n = 0;
list.forEach(function(s){
if(/^\d+\./.test(s)){
n = parseInt(s.substring(0, s.indexOf(".")));
}
});
return n;
}
<div>
<button onclick="addListItem()">NumberList</button>
<textarea id="editor" col=10 rows=10></textarea>
</div>
If you delete the list and create a new list again it will start from '1'.
also, counts from whatever the last number is.
var addListItem = function() {
if (!this.addListItem.num) {
this.addListItem.num = 0
}
++this.addListItem.num;
var text = document.getElementById('editor').value;
//HERE start new counting if textarea is empty
if(text.trim() == ''){
this.addListItem.num = 1; //restart counting here
}
//else check if textarea has previous numbers to proceed counting
else {
var lastLine = text.substr(text.lastIndexOf("\n") + 1).trim();
this.addListItem.num = parseInt(lastLine.slice(0, -1)) + 1; //add 1 to last number
}
console.log('text', text);
var exp = '\n' + this.addListItem.num + '.\xa0';
text = text.concat(exp);
document.getElementById('editor').value = text;
}
<div>
<button onclick="addListItem()">NumberList</button>
<textarea id="editor" col=10 rows=10></textarea>
</div>

Regex to replace non-numeric characters and insert dashes for phone number as it is typed

I need javascript to format a telephone number as it is typed. This would replace all non-numeric characters and insert dashes if the user doesn't type them in. So far this is the closest I've gotten, but it is thrown off if they put a dash in the wrong spot. The ideal solution would be to replace dashes only in the wrong spots. I was looking for a way to possibly replace the 4th and the 8th digit differently but haven't come up with a solution.
$('#TelephoneNo').keyup(function (ev) {
if (/[^0-9\-]/g.test(this.value))
{
this.value = this.value.replace(/[^0-9\-]/g, '');
}
if (/^(\d{3})(\d)/.test(this.value))
{
this.value = this.value.replace(/^(\d{3})(\d)/, '$1-$2');
}
if (/^(\d{3}-\d{3})(\d)/.test(this.value))
{
this.value = this.value.replace(/^(\d{3}-\d{3})(\d)/, '$1-$2');
}
});
Assuming you want the format "123-456-7890":
function formatPhoneNumber(s) {
var s2 = (""+s).replace(/\D/g, '');
var m = s2.match(/^(\d{3})(\d{3})(\d{4})$/);
return (!m) ? null : m[1] + " -" + m[2] + "-" + m[3];
}
<html>
<head>
<script type="text/javascript">
function CheckNum(ev) {
var inputval=document.getElementById("TelephoneNo").value;
debugger
if(inputval){
if (/[^0-9\-]/g.test(inputval))
{
inputval = inputval.replace(/[^0-9\-]/g, '');
}
if(detectPosition()){
if (/^(\d{3})(\d)/.test(inputval))
{
inputval = inputval.replace(/^(\d{3})(\d)/, '$1-$2');
}
if (/^(\d{3}-\d{3})(\d)/.test(inputval))
{
inputval = inputval.replace(/^(\d{3}-\d{3})(\d)/, '$1-$2');
}
}
document.getElementById("TelephoneNo").value=inputval;
}
}
function detectPosition() { var inputval=document.getElementById("TelephoneNo").value;
if(inputval.indexOf("-") ==4 || inputval.indexOf("-") ==8)
{
return 1;
}
return -1;
}
</script>
</head>
<body>
<input type="text" id="TelephoneNo" onkeyup="CheckNum(this)">
</body>
</html>
I know this is an old question, but I figured I might help someone out.
I did this xxx-xxx-xxxx as-you-type formatting using two cases: one for formatting where the length required one hyphen, and another for formatting with two required. That way, the last group always expects an unknown char count and doesn't wait until the end of the user input to enforce the format.
function formatPhone() {
var element = document.getElementById('phone');
var inputValue = element.value;
// length < 3 : no formatting necessary
if (inputValue.length > 3 && inputValue.length < 8)
// length < 8 : only one hyphen necessary, after first group of 3
// replace (remove) non-digits, then format groups 1 and 2
result = inputValue.replace(/\D/gi, '').replace(/(.{3})(.{0,3})/g, '$1-$2');
else
// length >= 8 : 2 hyphens required, after first two groups of 3
// replace (remove) non-digits, then format groups 1, 2, and 3
result = inputValue.replace(/\D/gi, '').replace(/(.{3})(.{3})(.{0,4})/g, '$1-$2-$3');
element.value = result;
}
Type a phone number, it will be formatted to xxx-xxx-xxxx as you type:<br/><br/>
<input type="text" id="phone" maxlength="12" onkeyup="formatPhone()"></input>

javascript validate swedish birthnumber

im trying to do a simple validation for an input who shall allow a number formated like this: 112233-1111 and when i accomplish that i would make it so that 22 cant exceed 12 and 33 exceed 31, this is what i got so far
var pn=document.forms.kontakt.pnr.value;
var spos=pn.indexOf("-");
var as= /^[0-9]{10}$/;
if (pn<11 || spos+4=pn.length || pn==null || pn=="")
{
alert ("Fyll i korrekt personnummer xxxxxx-xxxx");
kontakt.pnr.style.background = "red";
return false;
}
but it aint working, have i missed something?
There are a few problems here that I'd like to point out. First, spos+4=pn.length should be spos+4==pn.length (double equals because you are comparing). x does not seem to be defined and should be removed. Your regex variable as is never used.
Really, what you want to do is:
function calculate() {
//this matches 6 numbers followed by a ("-" or "+") followed by 4 more numbers
var as = /^[0-9]{6}[-+][0-9]{4}$/;
var pn=document.forms.kontakt.pnr.value;
if (as.test(pn)) {
var year = pn.substr(0,2);
var month = pn.substr(2,2);
var day = pn.substr(4,2);
//You probably need a better date checker, this is just an example
if (month <= 12 && day <= 30) {
document.body.innerHTML = 'great success!';
return;
}
}
document.body.innerHTML = 'Too bad!';
}
<form name="kontakt">
<input name="pnr" type="text" value="991222-1111"/>
<button type="button" onclick="calculate()">Calculate</button>
</form>

converting numbers into alphabets

I want to convert numbers into alpha characters using JavaScript. For example, 01=n, 02=i 03=n, 04=a, etc.
When someone enters the numbers:01020304 in the form he will get the response: nina. Whatever the user enters gets replaced with the equivalent characters including spaces.
Update
Thank you all for quick response. I have found this code in one site. It converts alpha characters into numbers, but code for converting numbers into alpha characters isn't working. Here is the code for converting alpha characters into numbers:
var i,j;
var getc;
var len;
var num, alpha;
num=new Array("01","02","03","04","05","06","07","08","09","10","11","12","13","14","15","16","17",
"18","19","20","21","22","23","24","25","26","00","##","$$");
alpha=new Array("a","b","c","d","e","f","g","h","i","j","k","l","m","n","o","p","q","r","s","t","u","
v","w","x","y","z"," ",".",",");
function encode() {
len=document.f1.ta1.value.length;
document.f1.ta2.value="";
for(i=0;i<len;i++) {
getc=document.f1.ta1.value.charAt(i);
getc=getc.toLowerCase();
for(j=0;j<alpha.length;j++) {
if(alpha[j]==getc) {
document.f1.ta2.value+=num[j];
}
}
}
}
Can anyone show me how to convert this to do the opposite character conversion?
I agree with Skrilldrick, you should learn how to do this yourself, but I couldn't help myself: http://jsfiddle.net/dQkxw/
HTML
<html>
<body>
<input type="text" id="code">
<button onclick="decode($('#code').val())">
Decode
</button>
</body>
</html>
JavaScript
window.decode = function(numbers) {
if (numbers.length % 2 != 0)
{
alert("invalid code!");
return;
}
var result = "";
for (var i = 0; i < numbers.length; i+=2) {
var number = Number(numbers.substring(i, i+2));
if (number < 1 || number > 26)
{
alert("invalid number: "+number);
return;
}
result += String.fromCharCode(96+number);
}
alert(result);
}
A good way to do this easily, and so it is a scalable solution would be to have a multi dimensional array that maps each char to it's corresponding char. You can have multiple dimensions for each conversion and pick between them.
var myCharArray=new Array(4)
for (i=0; i < 4; i++)
myCharArray[i]=new Array(2)
myCharArray[0][0]="a"
myCharArray[0][1]="1"
myCharArray[1][0]="b"
myCharArray[1][1]="2"
myCharArray[2][0]="c"
myCharArray[2][1]="3"
myCharArray[3][0]="d"
myCharArray[3][1]="4"
Then, upon conversion, loop every single character in your string to be encoded, and search for it in the array. If it is found, switch it with the encoded value. This should be reasonably easy to do.
The method you described seems to be a simple derivative off a Caesar cipher. Also remember because the script is client side, it will be incredible easy to decode, so make sure it's not for anything important!

Adding characters to string (input field)

I have a text box where the value is the result of a calculation carried out in jQuery. What I would like to do, using jQuery, is to display brackets around the number in the text box if the number is negative.
The number may be used again later so I would then have to remove the brackets so further calculations could be carried out.
Any ideas as to how I could implement this?
Thanks
Zaps
function FormatTextBox(id) {
var txtBox = $(id).val();
//strip bracket to get the number only
txtBox = txtBox.replace("[", "").replace("]", "");
var val = parseFloat(txtBox);
if (val < 0) {
txtBox.val("[" + val + "]");
} else {
txtBox.val(val);
}
return val;
}
First, store your calculation in a variable. You shouldn't be using the DOM to store data (in most cases). This basically eliminates your problem.
Number.prototype.bracketed = function() {
if(this < 0) {
return '[' + -this + ']';
} else {
return '' + this;
}
};
var result = do_calculation();
myTextBox.value = result.bracketed();
// result still holds the original Number value.
If you really want to store the data as the .value of the text input, you can make an unbracketed function as well:
String.prototype.unbracketed = function() {
var parts = this.match(/^\[([0-9]+)\]$|^([0-9]+)$/); // [number] or number
if(parts[1]) { // [number]
return -parseInt(parts[1], 10);
}
if(parts[2]) { // number
return parseInt(parts[2], 10);
}
return NaN;
};
Assuming you might have multiple fields (and you don't want the negative sign):
jQuery('input').each(function(){
if(jQuery(this).val() < 0 ){
jQuery(this).val('['+-1*jQuery(this).val()+']');
}
}
)
Then when you grab the value again, just strip the brackets and multiply by -1 to make it negative.
EDIT:
You can also use jQuery('input').data() to store the original number so you don't have to parse it again. (read more: http://api.jquery.com/data/ )

Categories

Resources