How do I select the last character of a string, using JavaScript? - javascript

I have a function that gets the last character of a string the user types in an input. But how do I select that single character, using execCommand()? The goal is to copy it into a different input.
I tried element.select(), but with no results.
The character to paste into the new input must be the character visible in the original input, and not the character correspondent to the keyboard key the user types, since the reason for all this is having an external JS library handling some CJK character conversion in one input, and moving the result to a different one..
I am going with a copy-paste approach. Hence, the need to select the character. But if there is a better way to achieve it, feel free to tell me about it.
I am open to both Vanilla JavaScript and jQuery approaches.
This is my code:
JSFiddle
function copyPaste () {
var i1 = document.getElementById('userInput');
var i2 = document.getElementById('input2');
var c = i1.value.substr(lol.length - 1);
c.select();
document.execCommand('copy');
i2.focus();
document.execCommand('paste');
i1.focus();
}
input {
width: 255px;
}
button {
display: block;
margin: 20px 0;
text-align: left;
}
<input type="text" id="userInput" placeholder="First, type something here.">
<button type="button" onclick="copyPaste"();>Then, click here to copy the last character<br>of the above input into the next input.</button>
<input type="text" id="input2" value="Some text...">

You should not use execCommand as it is obsolete. Moreover, you don't need to use the clipboard to transfer a (part of a) string to another input box. This can be done with standard string handling:
You can use slice(-1) to get the final character.
I would also prefer addEventListener instead of the onclick attribute (where you had a typo also).
With += you can append the extracted character:
var input = document.getElementById('userInput');
var output = document.getElementById('input2');
var btn = document.querySelector('button');
btn.addEventListener("click", function () {
output.value += input.value.slice(-1);
});
input {
width: 255px;
}
button {
display: block;
margin: 20px 0;
text-align: left;
}
<input type="text" id="userInput" placeholder="First, type something here.">
<button type="button">Then, click here</button>
<input type="text" id="input2" value="Some text...">

The following worked for me:
html:
<input type="text" id="userInput" placeholder="First, type something here.">
<button type="button" onclick="copyPaste()";>Then, click here to copy the last character<br>of the above input into the next input.</button>
<input type="text" id="input2" value="Some text...">
js:
function copyPaste () {
var i1 = document.getElementById('userInput');
var i2 = document.getElementById('input2');
var c = i1.value.slice(i1.value.length - 1);
i2.value = c;
}
Used slice() to get the last character of the string. Note I also fixed the onclick handler in your html.

Related

Clicking a button and getting the input from a user

Here is a picture. I have done css and html on my own and now don't know how to add javascript here.
What I want is:
a user writes something
then he clicks on button (for example uppercase) and his text appears at the bottom, instead of words "Here will be you text". How can I add such a function? I am confused.
If you want it in pure Javascript, you can do the code in the snippet.
I will assume that you know HTML and CSS, end explains only the javascript code.
The idea is:
You attach an event listener to handle de user click in each button. Each button has it's own class name, you can use it as a parameter of the document.getElementsByClassName to get an array of objects with this class name. Next you attach the event handler, you can do this with addEventListener.
Inside the click event function, you put the action that will be triggered after any click at the button.
The snippet below has commented code to clear things.
//Get input field with text before any operation
var textField = document.getElementsByClassName("text-field")[0];
//Get button that will trigger the Upper Case function
var upperBtn = document.getElementsByClassName("to-upper-btn")[0];
//Get button that will trigger the Lower Case function
var lowerBtn = document.getElementsByClassName("to-lower-btn")[0];
//Get div that will show the result
var resultContainer = document.getElementsByClassName("text-result")[0];
//Attach a click event listener to the Upper Case button
upperBtn.addEventListener("click", function(){
//Set the inner html of the result container with te value of the input field in uppercase;
resultContainer.innerHTML = textField.value.toUpperCase();
});
//Attach a click event listener to the Lower Case button
document.getElementsByClassName("to-lower-btn")[0].addEventListener("click", function(){
//Set the inner html of the result container with te value of the input field in lowecase;
resultContainer.innerHTML = textField.value.toLowerCase();
});
.text-field {
width:300px;
}
.container {
margin-top:50px;
border:1px solid #e4e4e4;
border-radius:5px;
background:#000;
color:#FFF;
padding:10px;
}
<h1>Write something</h1>
<input type="text" class="text-field"/>
<button type="button" class="to-upper-btn">To Upper Case</button>
<button type="button" class="to-lower-btn">To Lower Case</button>
<div class="container">
<div class="text-result">Just write what you want to make Upper Case or Lower Case, the result will be displayer here</div>
</div>
For more details about the javascript methods used in this code:
getElementByClassName
addEventListener
toUpperCase
toLowerCase
The combination of onclick, toUpperCase and toLowerCase can be used to obtain the required result.
Here is a working example:
<!DOCTYPE html>
<html>
<body>
<h2>Write something</h2>
<input id="inputText" type="text" placeholder="write something" style="width: 300px;">
<br>
<button onclick="upperCaseButtonClicked()">Upper case</button>
<button onclick="lowerCaseButtonClicked()">Lower case</button>
<button onclick="doNothingButtonClicked()">Do nothing</button>
<br>
<textarea id="outputArea" rows="5" cols="35"></textarea>
<script>
function upperCaseButtonClicked() {
var input = document.getElementById("inputText").value
var output = input.toUpperCase()
document.getElementById("outputArea").innerHTML = input.toUpperCase()
}
function lowerCaseButtonClicked() {
var input = document.getElementById("inputText").value
var output = input.toUpperCase()
document.getElementById("outputArea").innerHTML = input.toLowerCase()
}
function doNothingButtonClicked() {
var input = document.getElementById("inputText").value
document.getElementById("outputArea").innerHTML = input
}
</script>
</body>
</html>
const nameNode = document.getElementById("Name");
const nameCopyNode = document.getElementById("NameCopy");
if(nameNode){
nameNode.addEventListener('input',function(){
if(nameCopyNode){
nameCopyNode.value = this.value
}
})
}
<input type = "text" placeholder = "type your name" id="Name"/>
<br>
<br>
<input type = "text" placeholder = "you are typing" disabled id="NameCopy"/>
In the simplest form, using jQuery:
$(document).ready(function() {
$('#uppercase-btn').click(function() {
$('#myoutput').val($("#textid").val().toUpperCase());
});
$('#lowercase-btn').click(function() {
$('#myoutput').val($("#textid").val().toLowerCase());
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="text" name="myinput" id="textid" />
<button id="uppercase-btn">Uppercase</button>
<button id="lowercase-btn">lowercase</button>
<textarea id="myoutput" disabled></textarea>

Select Multiple Input Text Using this.select() — Don't Deselect When Selecting the Next One

I can easily select the text of a textbox for copying to clipboard using:
<input type="text" onclick="this.select();" value="This is my Text">
(i.e. highlight the text so I can click CMD+C to copy to clipboard)
But what I'm trying to do is highlight more than 1 textbox. As soon as I click on another textbox, the previous one gets unselected.
If this is not possible; an alternative approach might be to have a checkbox next to each line of text (in a div or textbox), then click each checkbox I want to select (i.e. highlight the text as if with a mouse), then click CMD+C to copy all of those items to clipboard.
Any ideas?
You can do the following:
Instead of selecting the input, try to toggle a specific class on the input as a response to some user action i.e click, doubleclick etc.
On the above events, add/remove the classes on input.
Add css rules to this specific class such that it appears that it has been selected. Maybe give some border, outline or different background colour.
When you need the text of these inputs, iterate on that specific class and get their value and store them in a textarea which will be hidden from user and then execute the copy command on it.
Here is a quick demo: http://jsfiddle.net/lotusgodkk/GCu2D/2200/
CSS:
.selected {
background: #f0f0f0;
border: 1px solid green
}
textarea {
height: 0;
width: 0;
opacity: 0;
}
HTML:
<input type="text" value="This is my Text">
<input type="text" value="This is my Text">
<input type="text" value="This is my Text">
<input type="text" value="This is my Text">
<input type="text" value="This is my Text">
<input type="text" value="This is my Text">
<input type="text" value="This is my Text">
<input type="text" value="This is my Text">
<button>
Get Values
</button>
<textarea class="result">
</textarea>
JS:
$(document).ready(function() {
$("input").click(function() {
$(this).toggleClass("selected");
});
$("button").click(function() {
var result = '';
$(".selected").each(function() {
result += $(this).val();
});
$("textarea").val(result);
$("textarea").select();
try {
var text = document.execCommand('copy');//text in clipboard
} catch (err) {
console.log('Error');
}
});
});
The solution from #KK is a good one. Before I saw it, I came up with this other solution so I figured I would post, maybe it helps someone out.
I used a generic html multi-select dropdown for the list of data instead of a series of inputs.
Then I used a JavaScript function found in this question Copy values from html <select multiple> to clipboard which grab the multi-selected values from the select and put them into a with line breaks instead of concatenated like the example.
Then I use clipboard.js to copy the values from the to my clipboard. The default example on the website shows how to do this.
JS
function changeClipboardValue(selectBox) {
var clipboard = document.getElementById("clipboard");
var text = "";
for (i = 0; i < selectBox.length; i++) {
if(selectBox.options[i].selected) text += selectBox.options[i].value + "\r\n";
}
clipboard.value = text;
}
function keydown(e) {
if(e.keyCode === 17) {
var clipboard = document.getElementById("clipboard");
clipboard.select();
}
}
function keyup(e) {
if(e.keyCode === 17) {
var selectBox = document.getElementById("selection");
selectBox.focus();
}
}
HTML for Multi-Select
<select multiple="multiple" size="10" id="selection" onkeydown="keydown(event)" onchange="changeClipboardValue(this)" style="width: 100%; height: 400px;">
HTML for empty Textarea
<textarea id="clipboard" onkeyup="keyup(event)"></textarea>

Clear a single form field in HTML

I am creating a simple HTML login page, but if I enter data into the fields it stays there when I refresh the page. I have tried
function pageInit(ID) {
this.browserbot.getCurrentWindow().document.getElementById(ID).value = '';
}
but this doesn't do anything (I placed it into onLoad on the inputs of the login.)
HTML:
`
<title>Login</title>
</head>
<body>
<form>
<fieldset>
<legend><h3>Please Login:</h3></legend>
<input type="text" placeholder="Username" name="userId" id="userId" onLoad="pageInit('userId');"><br>
<input type="password" placeholder="Password" name="passwd" id="passwd" onLoad="pageInit('passwd');"><br>
</fieldset>
</form>
</body>
CSS:
<style>
html {
font-family: sans-serif;
text-align: center;
}
a {
font-weight: normal;
}
a:hover {
font-weight: bold;
}
#userId, #passwd {
width: 30%;
height: 40px;
text-align: center;
}
</style>
JS:
<script>
function pageInit(ID) {
this.browserbot.getCurrentWindow().document.getElementById(ID).value = '';
}
</script>
As far as I can tell, the previous answers to not cover the full extent of the question. The original question requests a function to be called to clear the field. However, I'm going to address this in several different ways.
This can be achieved with no JavaScript at all, but simply setting the value attribute as below:
<input type="text" placeholder="Username" name="userId" id="userId" value="" />
<input type="password" placeholder="Password" name="passwd" id="passwd" value="" />
The above will ensure that the fields are clear when the page is loaded, but using only HTML. To do this via JavaScript, multiple things have to be taken into consideration. First, a function should be defined, which needs to be called when the page is loaded.
function clearValue(id) {
document.getElementById(id).value = "";
}
This will simply set the value to blank. However, this gets us back to the original issue. Setting onload for each element does not work, instead we must use window.onload.
window.onload = function() {
clearValue("userID");
clearValue("passwd");
}
This will clear each value one-by-one. However, there is an even better way to do this. JavaScript has built-in functions that make it easy to clear the entire form, or access the elements of the form by their name, even if they are the child of another element within the form. However, keep in mind that only valid input (includes textarea, etc...) fields can be accessed in this way.
So, assuming that the form's ID is myform, this would clear the entire form, no matter how many fields:
document.getElementById("myform").reset();
It's that simple. Using the form element, you can also access the fields by name, as mentioned above.
var f = document.getElementById("myform").elements;
f["userId"].value = "";
f["passwd"].value = "";
Using the above code makes it much quicker, especially if you have more fields.
Putting the JS together, it might look like this:
window.onload = function() {
// using function
clearValue("userID");
clearValue("passwd");
// or, reset entire form
document.getElementById("myform").reset();
// or, clear each field one-by-one
var f = document.getElementById("myform").elements;
f["userId"].value = "";
f["passwd"].value = "";
}
May be it will help you.
<input type="text" value="initial" id="field">
<button id="reset">reset</button>
<script type="text/javascript">
document.getElementById('reset').onclick= function() {
var field= document.getElementById('field');
field.value= field.defaultValue;
};
</script>
Set the input value to " " - in other words, nothing.
This way, the value will be cleared when the page loads.
Implment this like so:
<input value="">
If you'd rather use JS, add this to your onload event:
window.onload = myOnloadFunc;
function myOnloadFunc() {
document.getElementById('userId').value = ''
}

JavaScript generate new input field on click

I am in the process of making an HTML form where users have different options. I am trying to make a button that infinitely generates a new set op input fields with increasements in the name, like:
The first generated input should have a name of input1. The next with a name of input2 and so on.
Here is a visual example: https://webmshare.com/ZBvw0
How can this be accomplished?
You can solve this problem by creating your form elements dynamically and appending them to your form element.
Below a simplified example, just to show the main idea.
Main points here are:
Document.createElement() - Which creates a specified HTML element (your form elements in this instance).
Node.appendChild() - Which adds a node to the end of the list of children of a specified parent node (your form element in this instance).
(function() {
var counter = 0;
var btn = document.getElementById('btn');
var form = document.getElementById('form');
var addInput = function() {
counter++;
var input = document.createElement("input");
input.id = 'input-' + counter;
input.type = 'text';
input.name = 'name';
input.placeholder = 'Input number ' + counter;
form.appendChild(input);
};
btn.addEventListener('click', function() {
addInput();
}.bind(this));
})();
input{
display: block;
}
<form id="form" action="">
</form>
<button id="btn" type="button">Click Me!</button>
You can use jquery to fetch the name of the last item.
Then you can use the javascript string replace method and replace 'input' with '' in order to get the number of the last item.
Then just increment it by 1. You will have to parse it as an integer before adding 1 to it.
Then with the incremented number, create a new input field and append it to your container.
Try this
HTML
<div id="demo">
</div>
<input type="button" id="add" value="Add input"/>
Javascript
var num = 1;
document.getElementById('add').addEventListener("click",addInput);
function addInput(){
var demo = document.getElementById('demo');
demo.insertAdjacentHTML('beforeend','<div class="form-holder" style="width: 30%;"><a class="form-label">Billet type</a> <br><select name="ttype'+num+'"><option value="normal">Standard Billet</option><option value="add-on">Tilkøbs Billet</option></select></div><div class="form-holder" style="width: 31%; margin-left: 0.6%;"><a class="form-label">Billet navn</a> <br><input name="tname'+num+'" type="text" placeholder="F.eks. Entré Billet" style="width: 100%;" /></div><div class="form-holder" style="float: right; width: 18%; margin-left: 1%;"><a class="form-label">Antal</a> <br><input name="tquan'+num+'" type="text" placeholder="F.eks. 500" style="width: 100%;" /></div><div class="form-holder" style="float: right; width: 18%;"><a class="form-label">Pris (DKK)</a> <br><input name="tprice'+num+'" type="text" placeholder="F.eks. 100" style="width: 100%;" /></div> <br>');
num++;
}
Check out jsFiddle example

How to prevent a user from removing the first three characters in a text input?

I have a text input, which has three dynamically-generated characters On when page-load; what I want is that when a user enters data in that fieLd the user should be unable to remove that first three characters from the input.
The text input can contain 10 characters in total, three which we generate and 7 entered by the user.
Currently if the user presses backspace he can delete all characters, but I don't want to allow them to delete the first three characters.
On page-load the script sets three characters in the Lab text input:
<input id="Lab" maxlength="10" name="LabWareId" type="text" value="" class="valid">
$('#Lab').keyup(function () {
if ($(this).val().length == $(this).attr('maxlength'))
$('#DateReceived').focus();
});
Option 1 : Put the 3 character prefix outside of the input. This is the best from a user experience perspective.
<p>abc <input id="Lab" maxlength="10" name="LabWareId" type="text" class="valid"></p>
Option 2 : Check for backspace keypress and prevent the delete accordingly.
$(document).on('keydown', function (e) {
if (e.keyCode == 8 && $('#Lab').is(":focus") && $('#Lab').val().length < 4) {
e.preventDefault();
}
});
Try this (it's not the best solution but it works):
Fiddle
$(document).ready(function() {
$("#tb").on("keyup", function() {
var value = $(this).val();
$(this).val($(this).data("initial") + value.substring(3));
});
});
Mind you that if I use my mouse to highlight the first 3 characters and move them at the end of the other texts, it won't complain and allow it which is not what you want.
I would probably put the 3 generated characters to the left of the input, so the user doesn't think those are editable. You can make this look kinda nice using bootstrap like so.
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" rel="stylesheet" />
<label for="basic-url">Enter thingy:</label>
<div class="input-group">
<span class="input-group-addon" id="basic-addon3">ABC</span>
<input type="text" class="form-control" id="basic-url" aria-describedby="basic-addon3" maxlength="7" placeholder="Enter 7 characters">
</div>
Putting the 3 characters outside the editable area is the simplest/best approach.
However, my vanilla pure JavaScript approach for the case that the 3 characters must be in the input tag also handles the case that a user presses the delete key or tries to delete the first characters. In case pressing the delete key with the current selection means that less than 4 characters would remain or characters at the beginning would be deleted (removing the selection or pressing backspace), this user action is suppressed.
The script adds to all input tags of class=="valid" an keydown event handler calling function keepLeadingChars(e), which first ensures that pressing backspaces leaves 3 characters at the beginning and then ensures that deleting a selection leaves at least 3 characters at the beginning (or any other number specfied in the function call).
// add keydown event to input tags
var inputs = document.getElementsByTagName("input");
for (var i=0;i<inputs.length;i++) {
var ClassAttr = inputs[i].getAttribute("class");
if (ClassAttr=="valid") {
inputs[i].addEventListener("keydown", function(e) { keepLeadingChars(e,3); } );
}
}
function keepLeadingChars(e,count) {
// if backspace key (8) pressed and ...
if (e.keyCode==8) {
// ... content length < 4 then prevent user action
if (e.target.value.length<count+1) {
e.preventDefault();
}
// ... cursor is within first characters at beginning then prevent user action
var start = e.target.selectionStart;
if (start<count+1) {
e.preventDefault();
}
}
// if delete key (46) pressed and ...
if (e.keyCode==46) {
var start = e.target.selectionStart;
var end = e.target.selectionEnd;
var selLength = end-start; // length of selection
var totalLength = e.target.value.length;
//console.log(totalLength-selLength);
// ... remaining length < 3 then prevent user action
if (totalLength-selLength<count) {
e.preventDefault();
}
// ... selection is within first characters at beginning then prevent user action
if (start<count) {
e.preventDefault();
}
}
}
intput 1: <input id="Lab1" maxlength="10" name="LabWareId" type="text" value="1234567" class="valid"><br />
intput 2: <input id="Lab2" maxlength="10" name="LabWareId" type="text" value="1234567" class="valid">
I'm adding this solution as another alternative that might be useful to someone.
It uses the jQuery before() method. It works similar to CSS before, but also with input elements. However, you have to add some extra styling to make the prefix appear to be inside the input.
Also see: Can I use the :after pseudo-element on an input field?
Run the code snippet to try
$('#Lab').before('<span class="prefix">' + $('#Lab').data('prefix') + '</span>');
form {
background-color: lightgray;
padding: 2em;
}
#Lab {
border: 1px solid gray;
border-left: none;
width: 10em;
}
.prefix {
color: dimgray;
background-color: white;
border: 1px solid gray;
border-right: none;
font-family: monospace;
font-size: 16px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<form>
<input id="Lab" maxlength="10" name="LabWareId" type="text" data-prefix="123">
</form>
Add inputs and make them look like single input.
<span>
<input type="text" value="abc" readonly style="border-right: none;outline: none;width:25px"/>
</span>
<input type="text" style="border-left: none;outline: none;"/>

Categories