How can I add minus sign in jquery? - javascript

My html code :-
<input type="text" id="test">
<span class="display"></span>
My jquery code :
$("#test").keyup(function(e){
$('span.display').text(formatCurrency($(this).val()));
this.value = this.value.replace(/[^0-9\.]/g,'');
});
Demo and full code is like this : https://jsfiddle.net/oscar11/nbLbb037/
I want the input text can enter this : -10000000
And the result who displayed in class display is : -10.000.000
How can I add minus (-) sign?

Need to change code like below:-
output = output.reverse();
if(output[1] == '.'){
output.splice(1, 1);
formatted = output.join("");
}else{
formatted = output.join("");
}
And every thing will be fine.
Example:-
$("#test").keyup(function(e){
$('span.display').text(formatCurrency($(this).val()));
this.value = this.value.replace(/[^0-9\.-]/g,'');
});
// format currency on pagu and revisi
var formatCurrency = function(num){
var str = num.toString().replace("$", ""), parts = false, output = [], i = 1, formatted = null;
if(str.indexOf(",") > 0) {
parts = str.split(",");
str = parts[0];
}
str = str.split("").reverse();
for(var j = 0, len = str.length; j < len; j++) {
if(str[j] != ".") {
output.push(str[j]);
if(i%3 == 0 && j < (len - 1)) {
output.push(".");
}
i++;
}
}
output = output.reverse();
if(output[1] == '.'){
output.splice(1, 1);
formatted = output.join("");
}else{
formatted = output.join("");
}
return(formatted + ((parts) ? "," + parts[1].substr(0, 1) : ""));
};
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" id="test">
<span class="display"></span>

adding a minus sign is very easy, just replace
this.value = this.value.replace(/[^0-9\.]/g,'');
with following
this.value = this.value.replace(/[^0-9\.-]/g,'');
updated js fiddle is https://jsfiddle.net/nbLbb037/3/
But. You need to use regular expression test to verify exact currency test. Try exploring js regular expression test for your "formatCurrency" function. Of course thats purly upto you. Current solution will let you move further.
I have updated the regular expression js code on fiddle. Refer to https://jsfiddle.net/nbLbb037/5/

Related

How to fetch urls in array from paragraphs in javascript

I want to fetch all urls available in paragraph or sentence in javascript in array. For example check paragraph below:
Please checkout http://stackoverflow.com. It has very cool logo https://d13yacurqjgara.cloudfront.net/users/1249/screenshots/2247671/stackoverflow.png.
From above string, We have to get array of these two url.Solution 1: Solution 1, I know is to split paragraph with space, iterate over array and check for url one by one and push into url's array. But, It's a time taking solution.Are there better solution for finding it or above solution is fastest and good to go?Thank you.
Is this what you are looking for?
var list = [];
var sentence = "Please checkout http://stackoverflow.com. It has very cool logo https://d13yacurqjgara.cloudfront.net/users/1249/screenshots/2247671/stackoverflow.png.";
var result = checkForURL(sentence);
function checkForURL(text) {
var urlRegex = /(https?:\/\/[^\s]+)/g;
return text.replace(urlRegex, function (url) {
return '<a>' + url + '</a>';
})
}
var number = result.split('<a>');
for (var i = 1; i < number.length; i++) {
list.push(number[i].split(".</a>")[0]);
}
alert(list);
You might want to split on :// to get a smaller array to iterate over.
Example:
Demo
JSFiddle
HTML
<p id='p'>
Please checkout http://stackoverflow.com. It has very cool logo https://d13yacurqjgara.cloudfront.net/users/1249/screenshots/2247671/stackoverflow.png.
</p>
<h4>
URLs
</h4>
<ol id='results'>
</ol>
Javascript
findUrls();
function findUrls(){
var p = document.getElementById('p');
var res = document.getElementById('results');
var pStr = p.innerText;
var parts = pStr.split(/:\/\//);
if (parts.length < 2)
return;
for (var i = 1 ; i < parts.length ; i++){
var part = parts[i];
var lastPart = parts[i-1];
if (lastPart.length < 4 )
continue;
if (lastPart.length >= 4 && lastPart.substr(-4) == 'http')
part = 'http://' + part;
else if (lastPart.length >= 5 && lastPart.substr(-5) == 'https')
part = 'https://' + part;
var firstSpace = part.indexOf(' ');
if (firstSpace > -1)
part = part.substring(0, firstSpace);
var lastChar = part.charAt(part.length - 1);
if (lastChar == ',' || lastChar == '.' /* || ... */)
part = part.substring(0,part.length - 1);
res.innerHTML += '<li>' + part + '</li>'; // or push part to some result array
}
}
Try this approach. It might need some fine tuning..
var paragraphs = document.getElementsByTagName('p')
var regex = /(https?:\/\/.*?)(\s|$)/g;
var urls = [];
var badLastChars = [".", ","];
for (var i = 0; i < paragraphs.length; i++) {
var p = paragraphs[i].innerText;
var match;
while (match = regex.exec(p)) {
var url = match[1];
var lastChar = url[url.length-1];
if (badLastChars.indexOf(lastChar) > -1 ) {
url = url.slice(0,url.length-1);
}
console.log(url);
urls.push(url);
}
}
<p> Please checkout http://stackoverflow.com. It has very cool logo https://d13yacurqjgara.cloudfront.net/users/1249/screenshots/2247671/stackoverflow.png.</p>
<p> Another paragraph https://stackexchange.com. and here is another url I am making up: https://mycoolurlexample.com/this/is/an/example</p>

How do I input a number / time of 01:10 from my code?

I have this working code below to input a number/tme in textbox. This code below is functioning well but I want to set my textbox value into 00:00 and edit my function code like the second jsfiddle however my edited code is not going well as my idea. In my second jsfiddle I want to input a time of 05:30 but the code is replacing any number that input by a user from the textbox 0
function MaskedTextboxDPSDeparture() {
var myMask = "__:__";
var myCorrectionOut2 = document.getElementById("Departure");
var myText = "";
var myNumbers = [];
var myOutPut = ""
var theLastPos = 1;
myText = myCorrectionOut2.value;
//get numbers
for (var i = 0; i < myText.length; i++) {
if (!isNaN(myText.charAt(i)) && myText.charAt(i) != " ") {
myNumbers.push(myText.charAt(i));
}
}
//write over mask
for (var j = 0; j < myMask.length; j++) {
if (myMask.charAt(j) == "_") { //replace "_" by a number
if (myNumbers.length == 0)
myOutPut = myOutPut + myMask.charAt(j);
else {
myOutPut = myOutPut + myNumbers.shift();
theLastPos = j + 1; //set current position
}
} else {
myOutPut = myOutPut + myMask.charAt(j);
}
}
document.getElementById("Departure").value = myOutPut;
document.getElementById("Departure").setSelectionRange(theLastPos, theLastPos);
}
document.getElementById("Departure").onkeyup = MaskedTextboxDPSDeparture;
HTML
< input id="Departure" type="text" style="width: 35px; text-align: center" value="__:__" />
JSFIDDLE
JSFIDDLE 2
Any suggestion will accepted. Thanks.

detect natural line breaks javascript

When I type in a non-resizeable text area something like hello world, this is a demo and the text area is small enough, it will look like this:
hello world,
this is a demo
This is not caused by a \n or something.
How can I detect this natural line break in a text area?
A fiddle can be found here: http://jsfiddle.net/yx6B7/
As you can see, there is a line break, but javascript just says that it's one big line without any line-breaks in it.
Finally I found this script on the internet:
function ApplyLineBreaks(strTextAreaId) {
var oTextarea = document.getElementById(strTextAreaId);
if (oTextarea.wrap) {
oTextarea.setAttribute("wrap", "off");
}
else {
oTextarea.setAttribute("wrap", "off");
var newArea = oTextarea.cloneNode(true);
newArea.value = oTextarea.value;
oTextarea.parentNode.replaceChild(newArea, oTextarea);
oTextarea = newArea;
}
var strRawValue = oTextarea.value;
oTextarea.value = "";
var nEmptyWidth = oTextarea.scrollWidth;
var nLastWrappingIndex = -1;
for (var i = 0; i < strRawValue.length; i++) {
var curChar = strRawValue.charAt(i);
if (curChar == ' ' || curChar == '-' || curChar == '+')
nLastWrappingIndex = i;
oTextarea.value += curChar;
if (oTextarea.scrollWidth > nEmptyWidth) {
var buffer = "";
if (nLastWrappingIndex >= 0) {
for (var j = nLastWrappingIndex + 1; j < i; j++)
buffer += strRawValue.charAt(j);
nLastWrappingIndex = -1;
}
buffer += curChar;
oTextarea.value = oTextarea.value.substr(0, oTextarea.value.length - buffer.length);
oTextarea.value += "\n" + buffer;
}
}
oTextarea.setAttribute("wrap", "");
document.getElementById("pnlPreview").innerHTML = oTextarea.value.replace(new RegExp("\\n", "g"), "<br />");
}
Which is working fine.
This isn't a javascript problem.
Look at the word-wrap, white-space and overflow css properties.

Counting and limiting words in a textarea

I managed to make this little jquery function to count the number of words entered in textarea field.
here is the fiddle
and here is the code:
JQUERY:
$(document).ready(function()
{
var wordCounts = {};
$("#word_count").keyup(function() {
var matches = this.value.match(/\b/g);
wordCounts[this.id] = matches ? matches.length / 2 : 0;
var finalCount = 0;
$.each(wordCounts, function(k, v) {
finalCount += v;
});
$('#display_count').html(finalCount);
am_cal(finalCount);
}).keyup();
});
and here is html code
<textarea name="txtScript" id="word_count" cols="1" rows="1"></textarea>
Total word Count : <span id="display_count">0</span> words.
how can i make modifications in it to have the output like this
Total word Count : 0 words. Words left : 200
and when it reach 200 words it shall not allow to either paste, or type more words in the textarea field, in jquery? i.e. it shall restrict user to type exactly 200 words not more than that.
Please help.
Thanks a lot in advance.
EDIT: The modification is needed in this code only, as i am very well aware of the plugins, but they may interfere with the main code.
Using return false to stop keyup events doesn't block the event, because in this case the event has already fired. The keyup event fires when the user releases a key, after the default action of that key has been performed.
You will need to programmatically edit the value of the textarea you have as #wordcount:
$(document).ready(function() {
$("#word_count").on('keyup', function() {
var words = 0;
if ((this.value.match(/\S+/g)) != null) {
words = this.value.match(/\S+/g).length;
}
if (words > 200) {
// Split the string on first 200 words and rejoin on spaces
var trimmed = $(this).val().split(/\s+/, 200).join(" ");
// Add a space at the end to make sure more typing creates new words
$(this).val(trimmed + " ");
}
else {
$('#display_count').text(words);
$('#word_left').text(200-words);
}
});
});
http://jsfiddle.net/k8y50bgd/
I would do it like this ?
$("#word_count").on('keydown', function(e) {
var words = $.trim(this.value).length ? this.value.match(/\S+/g).length : 0;
if (words <= 200) {
$('#display_count').text(words);
$('#word_left').text(200-words)
}else{
if (e.which !== 8) e.preventDefault();
}
});
FIDDLE
A simple plugin can be found here:
Simple Textarea Word Counter using jQuery
Adding a simple if condition will solve your problem.
$.each(wordCounts, function(k, v) {
if(finalCount <= 200) {
//Todos
}
else {
return false; //prevent keyup event
}
});
$(document).ready(function(){
$("textarea").on('keyup',function(){
var value = $('textarea').val();
var wordCount = 0;
if(value == ""){
$('textarea').empty();
}
else{
var regex = /\s+/gi;
var wordCount = value.trim().replace(regex, ' ').split(' ').length;
}
if(wordCount > 25){
var trimmed = $(this).val().split(/\s+/,25).join(" ");
$(this).val(trimmed + " ");
}
else{
$('#display_count').html(25- wordCount +" words left");
}
});
});
You can use positive lookahead regexes to preserve the whitespace - so that returncodes and tabs are not collapsed to a single space. Something like this:
var wordLimit = 5;
var words = 0;
var jqContainer = $(".my-container");
var jqElt = $(".my-textarea");
function charLimit()
{
var words = 0;
var wordmatch = jqElt.val().match(/[^\s]+\s+/g);
words = wordmatch?wordmatch.length:0;
if (words > wordLimit) {
var trimmed = jqElt.val().split(/(?=[^\s]\s+)/, wordLimit).join("");
var lastChar = jqElt.val()[trimmed.length];
jqElt.val(trimmed + lastChar);
}
$('.word-count', jqContainer).text(words);
$('.words-left', jqContainer).text(Math.max(wordLimit-words, 0));
}
jqElt.on("keyup", charLimit);
charLimit();
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div class="my-container">
<textarea class="my-textarea"></textarea>
<span class="words-left"></span> words left
<div>
Here is the final solution.
(function(){
$("textarea").after("<p>Number of words: <span class='count'>0</span>/10</p>");
$("textarea").keypress(function(){
var words = $.trim($(this).val()).split(" ").filter(function(word){
return $.trim(word).length > 0
});
var wordlength = words.length;
$(".count").text(wordlength);
if(wordlength > 10){
alert("Please do not enter more than 10 words");
$(this).val( words.splice(0,10).join(" "));
return false;
}
})
})

Convert characters to asterisks in Javascript

Im trying to write a function that will convert all charactewrs after the first word into asterisks,
Say I have MYFIRSTWORD MYSECONDWORD, id want it to convert to asterisks on Keyup, but only for the second word, rendering it as so...
MYFIRSTWORD ***
I've been using the following only it converts each and every letter, is this possible?
$(this).val($(this).val().replace(/[^\s]/g, "*"));
I'm not sure about doing it with a single regex, but you can do this:
$("input").keyup(function() {
var i = this.value.indexOf(" ");
if (i > -1) {
this.value = this.value.substr(0, i)
+ this.value.substr(i).replace(/[\S]/g, "*");
}
});
Demo: http://jsfiddle.net/fc7ru/
<input type="text" onkeyup='$(this).val($(this).val().replace(/[^\s]/g, "*"));' />
Check in JsFiddle
you should try this code
var array = $(this).val().split(" ");
var newValue = "";
for(var i=0; i<array.length; i++) {
if ( i==0){
newValue = array[i];
continue;
} else{
newValue+= array[i].replace(/[^\s]/g, "*");
}
}
$(this).val(newValue);

Categories

Resources