how to remove everything except numeric 1234567890 using javascript - javascript

i have the following javascript how and where to set so when it will get the data and shows in a textbox it will show only numeric values:
<script type="text/javascript">
function showData($sel){
var str='';
document.getElementById("demo").innerHTML;
for (var i=0;i<sel.options.length;i++){
str+=(str!='') ? ', '+sel.options[i].value : sel.options[i].value;
}
}
sel.form.selectedFruits.value = str;
}
</script>
i have multiple select dropdown and it has multiple values like Staff No and email so i dont want to show email in text box only staff no and even i dont want to remove email from values.
it is working fine except what i want to do :D

A simple solution, if you want to get only numbers from a string (or html in your example), will be :
var str= document.getElementById(id).innerHTML;
return str.replace(/[^0-9]/ig, '');
See this jsfiddle.

if I've gotten the point correctly try something like this
<script type="text/javascript">
function showData($sel){
var str=[];
document.getElementById("demo").innerHTML;
for (var i=0;i<sel.options.length;i++){
str[i]+=sel.options[i].value.replace(/\D/g, ''); // remove everything except digits
}
}
sel.form.selectedFruits.value = str.join();
}
</script>

<script type="text/javascript">
function showStaffno(sel){
var str='';
document.getElementById("demo").innerHTML;
for (var i=0;i<sel.options.length;i++){
if (sel.options[i].selected){
str+=(str!='') ? ', '+sel.options[i].value.replace(/\D/g, '') : sel.options[i].value.replace(/\D/g, '');
}
}
sel.form.selectedFruits.value = str;
}
</script>

Related

Reusing Javascript code without repasting it again and again

I have the below code, which looks for the text "UID" and changes it to "UID *"
On my page, there are other terms such as "description", "score" and so on. I would also like to append * to these as well - is there a tidy way to get the below code to edit those as well? Only way I know is to repeat this code block again and again?
<script type="text/javascript">
//Mark UID as Mandatory
var CFN = "UID";
$(document).ready(ExecuteOrDelayUntilScriptLoaded(MainFunction, "sp.js"));
function MainFunction() {
Mandatory();
}
function Mandatory(){
$(".ms-accentText").each(function() {
var text = $(this).text();
$(this).text(text.replace(CFN, 'UID *'));
});
}
</script>
EDIT. I tried the below reply, but this didn't work for me, I have got this code now, but again, doesn't seem to work (its trying to add a * onto "UID" and "Description" where found using a multi variable;
<script type="text/javascript">
//Mark UID as Mandatory
var MandatoryCFs = ["UID", "Description"];
$(document).ready(ExecuteOrDelayUntilScriptLoaded(MainFunction, "sp.js"));
function MainFunction() {
Mandatory();
}
function Mandatory(){
$(".ms-accentText").each(function() {
var text = $(this).text();
$(this).text(text.append(MandatoryCFs, ' *'));
});
}
</script>
Replace multiple strings by using list of| Regex
//Mark UID as Mandatory
var MandatoryCFs = ["UID", "Description"];
$(document).ready(ExecuteOrDelayUntilScriptLoaded(MainFunction, "sp.js"));
function MainFunction() {
Mandatory();
}
function Mandatory(){
$(".ms-accentText").each(function() {
var text = $(this).text();
$(this).text(text.replace(new RegExp(MandatoryCFs.join('|'),'g'), '$& *'));
});
}
or like this if you don't need to the replaced strings to be dynamic:
text.replace(/UID|Description/g, '$& *')

Extract email addresses from a text file using JavaScript

I have more than 2000 email addresses. which i have exported from feedburner.
And the email address look like below;
adminvicky#gmail.com Active 12/05/2015 03:07
adminvishal250#gmail.com Pending Verification 8/05/2015 01:07
I want to extract email address from the text file by removing Active, Pending Verification, Date [i.e. 8/05/2015] and time [i.e 03:07] using JavaScript.
I have created a JavaScript Program which something like below which working properly for removing Active, Pending verification text,
<script>
function extracter() {
var a = document.getElementById('input').value;
document.getElementById('output').innerHTML =
a.replace(/Active|Pending|Verification| /g, '');
}
</script>
<textarea id="input"></textarea><br/>
<br/>
<input type="button" value="click" onclick="extracter()"/>
<br/>
<br/>
<textarea id="output"></textarea>
And the output is,
adminvicky#gmail.com 12/05/2015 03:07
adminvishal250#gmail.com 8/05/2015 01:07
And I want the below output. Just help me to remove "Date" and "Time",
adminvicky#gmail.com
adminvishal250#gmail.com
Try this one, i think it will do the job
var a = document.getElementById('input').value;
document.getElementById('output').innerHTML = extractEmails(a).join('\n');
And the function:
function extractEmails (text)
{
return text.match(/([a-zA-Z0-9._-]+#[a-zA-Z0-9._-]+\.[a-zA-Z0-9._-]+)/gi);
}
Here is a fiddle
Here is also an example using jQuery also Extract all email addresses from bulk text using jquery
Try to use this regex:
([a-zA-Z0-9._-]+#[a-zA-Z0-9._-]+\.[a-zA-Z0-9._-]+)
REGEX DEMO
In your Javascript you can implement it like this:
function getMail ( text ){
return text.match(/([a-zA-Z0-9._-]+#[a-zA-Z0-9._-]+\.[a-zA-Z0-9._-]+)/gi);
}
JSFIDDLE DEMO
you can easily write a regex and iterate over the results like:
var reg = new RegExp(/^[\w-\.]+#([\w-]+\.)+[\w-]{2,4}$/g);
var email;
while((email = reg.exec(targetText)) !== null) {
// do something with the email
}
Let's try with this simple regular expression:
var record = ' adminvicky#gmail.com Active 12/05/2015 03:07';
var regExp = /^\s*(.*?)\s+/;
console.log(record.match(regExp)[1]);
You can try this regex instead:
a.replace(/\s+.+$/g, '')
This should work for your case.
I would use string.split(" ") and split the textfile at its spaces.
Example:
var string = " adminvicky#gmail.com Active 12/05/2015 03:07 adminvishal250#gmail.com Pending Verification 8/05/2015 01:07"
var array = string.split(" ");
var emails = [];
for(var i = 0; i < array.length; i++){
if(array[i].indexOf("#") != -1){
emails.push(array[i]);
}
};
Then you have an array emails which contains your email adresses.
Using JQuery load function to read content from .txt file and display email as hyperlink:
$(document).ready(function(){
//Get the text content from txt file using load function
$( "#divid" ).load( "/xyz.txt",function(response, status, xhr){
if(status=='success') {
/* After loading the static text, modifying the email address to hyper link */
var corrected = response;
var emailRegex =/[a-zA-Z0-9._-]+#[a-zA-Z0-9.-]+\.[a-zA-Z]{2,4}/g;
corrected.match(emailRegex).forEach(function(email) {
console.log(email);
corrected = corrected.replace ( email, '' + email + '' );
});
$('#divid').html(corrected);
}
});
});

Verify specific input value

First off, thanks for anyone's help on this. I have an input id #Mailer_Code. I want to submit a specific value based on whether this mailer code value matches the user's value or not, and create 2 different IDs based on whether this value is valid or not.
In general terms:
ID is 1234;
if Mailer_Code is yourock, then ContactID is DWID
if Mailer_Code is not yourock, then ContactID is WWID
I would really appreciate if "yourock" was some sort of comma separated list so the Mailer_Code could be any of the specified values. ie. #Mailer_Code = "yourock, or yourawesome, or supercool, etc." (not case sensitive)
Also, if the #Mailer_Code is anything other than the list of allowed values, it simply returns a #Mailer_Code of "none" and WW1234.
So far I'm here:
if ( $('#Mailer_Code').val = "yourock" ) {
contactSource = "DW";
mailer_true_false = "true";
}
else {
contactSource = "WW";
mailer_true_false = "false";
$("#Mailer_Code").val('0');
}
Any help is much appreciated. Thanks for reading.
The following should get you started.
Note that instead of a comma separated list of valid values I added them to an array. jQuery has a very useful array function inArray that makes checking the values a simple matter.
<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js" type="text/javascript"></script>
</head>
<body>
<div>
<span id="Mailer_Code">yourock</span>
<span id="Id">1234</span>
</div>
<span id="ContactId"></span>
<script type="text/javascript">
var arr = [ "yourock", "youareawesome", "youarethebest" ];
var inListPrefix = "DW";
var outListPrefix = "WW";
var mailerCode = $("#Mailer_Code").text();
var pre = "";
if (jQuery.inArray(mailerCode, arr) >= 0)
{
pre = inListPrefix;
}
else
{
pre = outListPrefix;
$("#Mailer_Code").text("none");
}
$("#ContactId").text(pre + $("#Id").text());
</script>
</body>
</html>

jQuery Fetching data and making sum

What i'm trying to do is taking the price of every input checked, making a sum out of it.
Here's my code
function totalSum(e) {
e.preventDefault();
var unit = $("input:checked").parent("dt").siblings("dd").find("span");
total = 0;
$.each(unit, function(index, obj){
total += parseInt($(obj).text(), 10);
});
$("#totalPrice").html('<span class="count">€ ' + total + '</span> €');
}
Every unit is found inside its span. Total is set to 0. I try to call a parseInt on each checked object, then add the total inside a span. In HTML, price is stated like that:
<dd><span class="costo">€199</span></dd>
So as you see there is the Euro mark. I am afraid it could not be parsed, is this it? Because nothing change! How should I write it?
Thanks in advance
Ok I feel so ashamed but I cannot get it to work. I decided to put the code at its minimum, so I tried that way
<body>
<div class="bla"><span class="count">1</span></div>
<div class="bla"><span class="count">1</span></div>
<div class="bla"><span class="count">1</span></div>
<div id="total"></div>
<script type="text/javascript" src="js/jquery-1.9.0.min.js" /></script>
<script>
$(document).ready(function(){
function sum() {
var prices = $("div.bla").find(".count");
total= 0;
$.each(prices, function(index, obj){
total += parseFloat($(obj).text());
});
$("#total").html('<span class="count">'+total +'</span> €');
};
});
This should work, yet nothing appear. Could someone be so kind to tell me what's going wrong?!
You can just replace any non-numeric characters:
total += parseInt($(obj).text().replace(/[^\d.-]/, ''), 10);
Also, you can do unit.each() instead of $.each(unit, but that has no effect on what you're trying to do.
You can simply remove the unit from the text :
var text = $(obj).text().replace(/[€\$]/,''); // add other units if needed
total += parseInt(text, 10); // are you sure you don't prefer parseFloat ?
Or, if you want to only keep digits and + and -, do
var text = $(obj).text().replace(/[^\d\-\+]/g, '');
Change your parseInt to skip the first character.
total += parseInt($(obj).text().substring(1),10);
After a couple of days trying and reading the best way to do it, I believe this could be an elegant solution of what I was trying to achieve :)
$("input").on("click", function() {
var j = $("input:checked");
t = 0;
$(j).each(function() {
t += parseInt(this.value, 10);
});
$("#total").html("<span>€ " + t + "</span>");
});

How do I write a variable a certain amount of times?

var x=5
var char="Hi!
Is there any way to make JS write char x amount of times inside of an html element?
<span>Hyper guy wants to tell you
<script>
var x=5;
var char="Hi!;
document.write(char) and repeat x times;
</script>
</span>
The problem with using document.write is that it erases the whole page, so how would I insert it in context?
Use a loop that loops 5 times, each time adding 'Hi!' onto the end.
var x = 5;
var char = '';
while (x--) {
char += 'Hi!';
}
// write once
document.write(char);
Or, you can just write 5 times:
var x = 5;
var char = 'Hi!';
while (x--) {
document.write(char);
}
Up to you which you choose, though I'd prefer the first (the less you mess with the document, the better).
try this:
<span>Hyper guy wants to tell you
<script type="text/javascript">
var x=5;
var c="Hi!"; //close the quotes.
for (;x>=0;--x)
document.write(c);
</script>
</span>
document.write(..) doesnt erase the content of the entire page, if it is used in a proper way.
Really? I'm not sure where you got the idea that it erases the page first.
When I execute the following in FF3, after adding the missing closing quote following Hi!:
<html>
<head></head>
<body>
<span>
Hyper guy wants to tell you
<script type="text/javascript">
var x=5;
var chars="Hi! ";
var i;
for (i = 0; i < x; i++) document.write(chars);
</script>
</span>
</body>
</html>
I get:
Hyper guy wants to tell you Hi! Hi! Hi! Hi! Hi!
Create a HTML element in the page where you want to insert text
Use document.getElementById to get the element and append the text to element using .innerHTML .text property to it
http://www.tizag.com/javascriptT/javascript-innerHTML.php
example:
//add this empty span in the HTML page
<span id="newText"></span>
<script type="text/javascript">
var x=5, count;
var char='Hi!', resultString = '';
for(count=0;count<x;count++)
{
resultString = resultString + char;
}
document.getElementById('newText').innerHTML = resultString;
</script>

Categories