How to format input in html using javascript - javascript

How to format input text on html, sample input: Hi hello
I like to display the input like this
'Hi','hello',
When I hit enter, single quote with a comma will automatically display.
Any suggestion? Thank you.

The text is then formatted and returned to the input field. You only need an eventlistener, a function that converts the text.
const input = document.getElementById('watch');
input.addEventListener('keypress', function (e) {
e.preventDefault();
if (e.key === 'Enter') {
input.value = input.value.split(' ').map(s => `'${s}'`).toString() + ',';
}
return false;
});
<form>
<input type="text" value="Hi World" id="watch">
</form>

You can use split and join
const str = "Hi hello";
let output = '';
if(str)
output = `'${str.split(" ").join("','")}',`;
console.log(str);

const string = 'a b c'
console.log(string.split(' ').map(str => `'${str}'`).toString() + ',')

Related

How to detect when a user types a string in an input type number?

I have a form with an input type number. I want to display a message when the user types a string.
When I try to retrieve the value of the input, I always get an empty string.
When I type a number it works fine but not with a string...
I tried with both jQuery and javascript.
var inputVal = $(this).val();
var inputValJs = document.getElementById("myInput").value;
console.log(inputVal); // if 99 => 99 if test => ''
console.log(inputValJs); // if 99 => 99 if test => ''
How should I proceed ?
Input type number only allow you to enter numbers
var inputValJs = document.getElementById("myInput").value;
console.log(inputValJs);
<input type="number" id="myInput" name="tentacles" value ="33">
If you really need an input text you can do the following:
The event input captures the changes in the input text.
var messageElem = document.querySelector('#myMessage');
document.querySelector('#myInput').addEventListener('input', function(e) {
if (this.value === '' || /^[0-9]+$/.test(this.value)) {
messageElem.textContent = "";
} else {
messageElem.textContent = "Only numbers";
}
});
<input type="txt" id='myInput'>
<p id='myMessage'>
Number type input only accept number value.
To retrieve input value, use event listener :
var myValue = '';
document.getElementById("myInput").addEventListener('input', function(e) {
myValue = e.target.value;
console.log(myValue);
});
<input type="number" id="myInput">

Replace string as you type

I want to create a web-friendly image name from user input on a form. I want to replace any spaces in the user entered string with a dash as the user types.
My code only replaces the first space.
How do I replace all spaces with dashes?
$('#form_model').keyup(function(event) {
var newText = event.target.value;
newText = newText.replace(" ", "-");
$('#form_image').val(newText+".png");
});
You have to replace the spaces globally for all the occurrences. So, use this,
newText = newText.replace(/ /g, "-");
Final Code
$('#form_model').keyup(function(event) {
var newText = event.target.value;
newText = newText.replace(/ /g, "-");
$('#form_image').val(newText+".png");
});
This is easily done by using a regexpression with the g flag. g stand for global, so it affects the whole string and NOT only the first value.
Here is the working fiddle:
$('#form_model').keyup(function(event) {
var newText = event.target.value;
newText = newText.replace(/\s/g, "-");
$('#form_image').val(newText+".png");
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input id="form_model" type="text">
<input id="form_image" type="text" readonly>
JS function replace() only replace the first character that matches. I usually use
.split('X').join('Y');
So, in your code it would be:
newText = newText.split(' ').join('-');
In this way, you can 'replace' all maching characters.
$(document).ready(function () {
$('#form_model').keyup(function(event) {
var newText = event.target.value;
newText = newText.replace(" ", "-");
$('#form_image').val(newText+".png");
});
});
Example is here: https://jsfiddle.net/55qxy624/

Concatenating to user input

An example would be if I type !greet it would output "Hello username".
The end goal is to integrate this into a discord bot.
An example of what I have tried:
function doGreeting() {
var input = document.getElementById('userInput')
alert(input);
}
if (msg.content === prefix + 'greet') {
msg.channel.sendMessage('Hello ' + doGreeting())
};
I don't know about your input field id or class but I am giving you example below so it may help you.
<input type="text" id="my_id" >
<span id="msg"></span>
<script>
var input_val = document.getElementById("my_id");
if(input_val .indexOf("!greet") !=-1){ // if there is !greet word
var split_str = input_val .split(" ");
document.getElementById('msg').innerHTML = "Hello "+split_str [1];
}
</script>

Replace part of input value on keypress jquery?

For example I have, input type with predefined length.
I want to achieve, when the input value is bigger or equal to 3, to replace that part of string[3] with '/';
<input type="text" id="number" maxlength="6" placeholder="MM/YY"/>
And here is jquery
$('#number').on('keypress',function(){
if(this.value.length <= 3) {
this.value.replace(this.value[3],'/');
}
});
So in short when user types inside input field for example: 1234, the number 3 needs to be replaced with '/' and than the value would be 12/2017, like expiration date of credit card. Thanks in advance
You can try something like this. Had to change the maximum length of input's value from 6 to 7.
Try with e.g. 12/2017.
$('#number').on('keypress', function() {
if (this.value.length >= 2) {
this.value = this.value.slice(0, 2) + '/' + this.value.slice(3, this.value.length)
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" id="number" maxlength="7" placeholder="MM/YY" />
You could try the following.
Where delimeterIndeces is where in the string you want to check and change the values. InputString is the string returned from the input tag.
let delimeterIndices = [2,5]; // "02[/]15[/]2017";
let inputString = "123152017";
let resultString = inputString.split('').map((char, index) => {
if(delimeterIndices.indexOf(index) !== -1) {
return '/';
} else {
return char;
}
}).join('');
console.log(resultString);

How to split a string into several html text fields

I have 2 input fields in a html file, text1 and text2. Then I copy a long string and paste it into text1. I want the string splited automatically into text1 and text2. So there must be a delimiter e.g TAB (ASCII 9) in the string. I have been trying many times but no lucky. In my experiment, there is a button calling javascript function as follows :
<script>
function Chr(AsciiNum)
{
return String.fromCharCode(AsciiNum)
}
function test()
{
c = "ABC"+Chr(9)+"DEF";
document.getElementById("text1").value=c;
}
</script>
<input type="button" value="Paste it" onClick="test()">
What I want is text1 filled with ABC and text2 filled with "DEF"
Thanks you for your helps .....
Splitting is simple:
function test(pastedText) {
var parts = pastedText.split(Chr(9));
document.getElementById("text1").value = parts[0];
document.getElementById("text2").value =
(parts[1] === undefined ? "" : parts[1]);
}
The tricky part, actually is the pasting, check the full code below.
See a online DEMO for code here.
Text1: <input type="text" id="text1"><br />
Text2: <input type="text" id="text2"><br />
<br />
<div>Sample string (copy the red text and paste it on Text1):</div>
<div style="color:red">ABC DEF</div>
<script>
function Chr(AsciiNum) {
return String.fromCharCode(AsciiNum)
}
function test(pastedText) {
var parts = pastedText.split(Chr(9));
document.getElementById("text1").value = parts[0];
document.getElementById("text2").value = (parts[1] === undefined ?
"" : parts[1]);
}
/** HANDLING PASTE EVENT
* Credits to: http://stackoverflow.com/a/6035265/1850609 */
function handlePaste(e) {
var pastedText = undefined;
if (window.clipboardData && window.clipboardData.getData) { // IE
pastedText = window.clipboardData.getData('Text');
} else if (e.clipboardData && e.clipboardData.getData) {
pastedText = e.clipboardData.getData('text/plain');
}
test(pastedText); // Process and handle text...
return false; // Prevent the default handler from running.
};
document.getElementById("text1").onpaste = handlePaste;
</script>
I also suggest you rename the test() function into something more meaningful to you.
Why dont you just do like that:
c = "ABC "+Chr(9);
document.getElementById("text1").value=c;
document.getElementById("text2").value= "DEF";
This should be inside test()
Hope this helps.

Categories