Remove all letters from input value - javascript

I want to make a button that clears an input type='text' from all its letters. I want it to, when clicked, remove all characters except numbers and commas.
<input type="text" id="txt" value="1a,2b,3c">
<input type="button" id="reml" value="Remove Letters" onclick="???????">
I was thinking it would be something like:
onclick="document.getElementById('reml').value.replace(a[],'');
a = ['a','b','c',etc.];
But I'm not sure if something like that'd work...
Any ideas?

Something along these lines.
function clearInvalid() {
var input = document.getElementById('txt')
input.value = input.value.replace(/[^\d,]/g,'')
}
<input type="text" id="txt" value="1a,2b,3c">
<input type="button" id="reml" value="Remove Letters" onclick="clearInvalid()">

Make this the onclick code:
var theinput = document.getElementById('reml')
theinput.value = theinput.value.replace(/[^\d,]/g,'')
This uses a regex to find all non-digit and comma characters and replaces them with an empty string

You could use a function like the following one to transform the text:
function transform(s) {
var out = "";
for (var index = 0; index < s.length; ++index) {
if ((!isNaN(s[index])) || (s[index] === ',')) {
out += s[index];
}
}
return out;
};

You can use regex to do this, and jQuery can make your code even shorter:
<html>
<input type="text" id="txt" value="1a,2b,3c">
<input type="button" id="reml" value="Remove Letters">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script>
$("#reml").on("click", function(event) {
$("#txt").val($("#txt").val().replace(/[^\d,]/g, ''));
});
</script>
</html>

Related

Remove everything in every line after/before the mentioned text using JavaScript

I want to remove everything in every line after/before the mentioned text. In the following code, I want when the "Remove After!" button is pressed then in every line text after mentioned text "love" must be removed. When the "Remove Before!" button is pressed then in every line text before mentioned text "love" must be removed.
Example:
I love donuts! --> Remove After! --> "I love"
I love donuts! --> Remove Before! --> "love donuts!"
Note I want this for every line. I have no idea about how I can do this so I am just giving scratch code!
Code:
function afterFun() {
var rAfter = document.getElementById("iAfter").value;
document.getElementById("TextInput").value = document.getElementById("TextInput").value.replace(rAfter, "");
}
function beforeFun() {
var rBefore = document.getElementById("iBefore").value;
document.getElementById("TextInput").value = document.getElementById("TextInput").value.replace(rBefore, "");
}
<textarea cols="30" id="TextInput" rows="10" style="width: 100%;">I love donuts!</textarea><br><br>
<input value="love" type="text" id="iAfter"><br>
<input onclick="afterFun()" type="button" value="Remove After!" /><br /><br>
<input value="love" type="text" id="iBefore"><br>
<input onclick="beforeFun()" type="button" value="Remove Before!" /><br /><br>
You are doing the same thing in both function, just changing the variables name. My approach would be to split the input string by the target word:
let result = str.split(target);
It would return an array of strings saved in the result variable, with the beforeText at index [0] and the afterText at index [1];
Then, just get the index you want (depends on the button you clicked) and add the target before or after the result:
function afterFun() {
var target = document.getElementById("iBefore").value;
var text = document.getElementById("TextInput").value;
var lines = text.split("\n"); //split lines
document.getElementById("TextInput").value = "";
lines.map(line => {
var result = line.split(target);
document.getElementById("TextInput").value += result[0] + target + "\n";
})
}
function beforeFun() {
var target = document.getElementById("iBefore").value;
var text = document.getElementById("TextInput").value;
var lines = text.split("\n"); //split lines
document.getElementById("TextInput").value = "";
lines.map(line => {
var result = line.split(target);
document.getElementById("TextInput").value += target + result[1] + "\n";
})
}
<textarea cols="30" id="TextInput" rows="10" style="width: 100%;">I love donuts!</textarea><br><br>
<input value="love" type="text" id="iAfter"><br>
<input onclick="afterFun()" type="button" value="Remove After!" /><br /><br>
<input value="love" type="text" id="iBefore"><br>
<input onclick="beforeFun()" type="button" value="Remove Before!" /><br /><br>

How to auto add a hyphen in user input using Javascript?

I am trying to validate and adjust user input for a zip code to match the format: xxxxx OR xxxxx-xxxx
Is there a simple way using javascript to add the hyphen (-) automatically if the user enters more than 5 digits?
Pretty sure there is! Just gotta check how many characters the inputted string has, and if it's 5, add a hyphen to the string :)
var input = document.getElementById("ELEMENT-ID");
input.addEventListener("input", function() {
if(input.value.length === 5) {
input.value += "-";
}
}
Try the following.
function add_hyphen() {
var input = document.getElementById("myinput");
var str = input.value;
str = str.replace("-","");
if (str.length > 5) {
str = str.substring(0,5) + "-" + str.substring(5);
}
input.value = str
}
<input type="text" id="myinput" value="a" OnInput="add_hyphen()"></input>
Anna,
The best way to do it would be to use a regular expression. The one you'll need is:
^[0-9]{5}(?:-[0-9]{4})?$
You would ten use something like:
function IsValidZipCode(zip) {
var isValid = /^[0-9]{5}(?:-[0-9]{4})?$/.test(zip);
if (isValid)
alert('Valid ZipCode');
else {
alert('Invalid ZipCode');
}
}
In your HTML call it like this:
<input id="txtZip" name="zip" type="text" /><br />
<input id="Button1" type="submit" value="Validate"
onclick="IsValidZipCode(this.form.zip.value)" />
For more on Regular Expressions this is a good article:
Regular Expressions on Mozilla Developers Network
You can try using simple javascript function as follows
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>JS Bin</title>
<script>
function FN_HYPEN(){
var input = document.getElementById("USER");
if(input.value.length === 5) {
input.value += "-";
}
}
</script>
</head>
<body>
<INPUT ID="USER" TYPE="TEXT" onKeypress="FN_HYPEN();"/>
</body>
</html>

<input type=“text” maxlength=“4”> should not count comma and dot in maxlength

I have input field which contains number and special characters e.g. comma and dot
while calulating the maxLength of the field i want to skip special characters .
I dont want to restrict the special character.
Expected Output should be :- 1,234 (Total Length :- 4)
<form action="/action_page.php">
Username: <input type="text" maxlength="3" id="myId"/>
<input type="submit" value="Submit">
</form>
jsfiddle link here
Try adding this javascript:
window.onload = function() {
var textInput = document.getElementById("myId");
textInput.oninput = function() {
var temp;
temp = this.value.replace(/[^\w\s]/gi,'');
if (temp.length > 3) {
alert("Invalid"); // Or other stuff you want to do
}
};
};
Note that this code checks input on real time
This should be done with javascript:
var input = document.getElementById('myId');
input.addEventListener('keyup', function () {
// Checking length of string ignoring all non-digit and non-letter characters
if (this.value.replace(/[^\d|[^a-zA-Z]]*/g, '').length == 3) {
console.log('stop and do whatever you need')
}
})
You can try to use HTML5 pattern attribute. Just instead of maxlength type pattern and give it some regex. Could do something like this:
<form action="/action_page.php">
Username: <input type="text" pattern="(?(?=^.\d{1,3},\d{1,3}$)^.{5}$|^.{4}$)" id="myId"/>
<input type="submit" value="Submit">
</form>

Re-feeding a variable into a looped function

I'm attempting to make a simple program for encoding things in base64 multiple times (not really for any particular reason, just more as an example and practice). I've been having quite a bit of trouble though, it could be because I've not had enough (or possibly had too much) coffee.
I can't seem to figure out how to refeed my variable (text) back into the function that encodes it until i is equal to times
Any assistance with this would be appreciated!
<html>
<head>
<script>
function encodeThis(text,times) {
var toEncode = text;
for (var i = 0; i < times, i++) {
btoa(toEncode);
}
document.getElementById("result").value = toEncode;
}
</script>
</head>
<body>
<b>Text to Encode</b><br/>
<input type="text" id="encode"><br/>
<b>Number of Times to Encode (Integers Only)<br/>
<input type="text" id="times">
<button type="submit" onclick="encodeThis(encode,times)">Test</button>
<br/>
<br/>
<b>Result</b><br/>
<input type="text" id="result">
</body>
</html>
Would I need to put a function inside of that function to refeed the variable in?
You need to assign the result of the encoding back to the variable.
function encodeThis(text, times) {
var toEncode = text;
for (var i = 0; i < times, i++) {
toEncode = btoa(toEncode);
}
document.getElementById("result").value = toEncode;
}
But in terms of the overall code in your example you also need to actually get the text from the #encode and the #times elements and fix the syntax error in the for loop.
So
function encodeThis(text, times) {
var toEncode = text.value, // read the value from the encode input element
numTimes = parseInt(times.value, 10); // read the value from the times element and convert to number
for (var i = 0; i < numTimes; i++) {
toEncode = btoa(toEncode);
}
document.getElementById("result").value = toEncode;
}
<b>Text to Encode</b><br/>
<input type="text" id="encode" /><br/>
<b>Number of Times to Encode (Integers Only)</b><br/>
<input type="text" id="times" />
<button type="submit" onclick="encodeThis(encode,times)">Test</button>
<br/>
<br/>
<b>Result</b><br/>
<input type="text" id="result">

I need to find the longest word in a sentence using JS

I am having trouble getting my JS to return the longest word when I click on the button. I am not sure what in my JS code I am missing or have put incorrectly, but when I type in three words nothing is given back to me. I have pasted below both my JS and html codes.
HTML:
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>Longest Word</title>
<link rel="stylesheet" href="../css/easy.css">
<script src="p3-longest.js"></script>
</head>
<body>
<header>
<h1>Longest Word</h1>
</header>
<body>
<form action="demo_form.asp" id="demo_form">
Phrase:
<input type="text" id="input1" name="LongestWord" placeholder="Put Phrase Here">
<br>
<input type="button" id="btn1" value="Longest Word">
</form>
</body>
</html>
JS:
function longestWord(string) {
var str = string.split(" ");
var longest = 0;
var word = null;
for (var i = 0; i < str.length ; i++) {
if (longest < str[i].length) {
longest = str[i].length;
word = str[i];
}
}
return word;
}
function init() {
alert('count words');
var countTag = document.getElementById('btn1');
countTag.onclick = longestWord(string);
}
window.onload = init;
try this:
Phrase:
<input type="text" id="input1" name="LongestWord" placeholder="Put Phrase Here">
<br>
<input type="button" id="btn1" value="get Longest Word">
<br/>
Longest Word: <span id='sp1'></span>
<script>
var btn = document.getElementById("btn1");
var in1 = document.getElementById("input1");
var sp1 = document.getElementById("sp1");
btn.onclick = function(){
var vals = in1.value.split(' ');
var val = vals[0];
vals.forEach(function(v){ if(v.length>val.length) val = v;});
sp1.textContent = val;
}
</script>
Fiddle Demo
Add this to your button:
onClick="alert(longestWord(document.getElementById('input1').value))"
It will take the value of input1 and send it to your longestWord-function. Then put up an alert-box with the return value from your function.
I don't see anything particularly wrong with your code ... except for the fact that "I don't see any code here that will ever 'give anything back to you!'" :-)
Presumably, "onload", the init() function dutifully runs ... and setting countTag.onclick to whatever integer value longestWord() might return when given the undefined value of the non-declared non-variable length. (Which is of no good use at all to onclick, which expects a function, not an integer...)
None of which, even if it did work (which it doesn't ...), ever asks the digital computer to, by any means at all, "give anything back to you!"

Categories

Resources