window.getSelection().toString() not working on IE 11 - javascript

I have an input field. I want to restrict the users to enter max ten characters. The below code is working on Chrome but not in IE 11. I want when someone highlights the text, they should be able to replace it. In IE11, when I'm highlighting a text, I'm unable to replace it, Possibly the getSelection().toString() is not working.
$('#demo').on('keydown', function(event) {
var selection = window.getSelection().toString();
alert(selection);
var value1 = document.getElementById("demo").value;
if (value1.length === 10 - selection && event.keyCode != 8) {
event.preventDefault();
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input contenteditable="true" value="mm/dd/yyyy" id="demo" style="border:none;width:80px;" />

$("#demo").keydown(function(event) {
var value = this.value;
// var sel = window.getSelection().toString();
var sel = value.substring(this.selectionStart, this.selectionEnd);
if (value.length === 10 - sel && event.keyCode != 8) {
event.preventDefault();
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input contenteditable="true" value="mm/dd/yyyy" id="demo" style="border:none;width:80px;" />

Related

When pressed 'Enter', sum the input and clear it

I'm in the begin fase of learning JS. I'm trying to make a page were the user can put numbers in a text field. The user can press enter to add another number. When the user pressed enter the input field need to be cleared
The amounts entered must be added together and their total must be shown in a second text box.
my HTML:
<input type="text" id="input">
<p>Uw totaal:</p>
<input type="text" id="output">
My JS:
input = document.getElementById("input");
input.onkeypress = function(event) {
ceckKey(event);
};
function ceckKey(e) {
// check for enter: e.key is for Firefox
// if true, make input empty
if (e.keyCode == 13 || e.key == 13) {
input.value = "";
}
var number = +input.value;
return number;
}
var total = 0
total += checkKey();
document.getElementById("output").value = total;
The keypress works in every browser. The problem is that i cannot sum the numbers. If i put it in the keypress function, the number will be cleared everytime you hit enter again.
I hope you guys can help!
Get the value before your clear it.
var input = document.getElementById("input");
var output = document.getElementById("output");
var total = 0;
input.onkeypress = function(e) {
if (e.keyCode == 13 ||  e.key == 13) {
total += +input.value;
output.value = total;
input.value = "";
}
};
<input type="number" id="input">
<p>Uw totaal:</p>
<input type="number" id="output">
Give this a shot -
var total = 0;
input = document.getElementById("input");
output = document.getElementById("output");
input.onkeypress = function(e) {
total = total + input.value * 1;
if(e.keyCode == 13) {
input.value = "";
}
output.value = total;
};
<input type="text" id="input">
<p>Uw totaal:</p>
<input type="text" id="output">
And hey, welcome to JS!
you clear your input field too early.
var number = 0
function ceckKey(e) {
// check for enter: e.key is for Firefox
// if true, make input empty
if (e.keyCode == 13 || e.key == 13) {
number += input.value;
input.value = "";
}
return number;
}
document.getElementById("output").value = number;
note that your number variable may not be declared inside of the checkKey function. Greetings
You are updating the output element outside of the ceckKey function.
This update IS not automatic. You must trigger it.
Also, check carefully that function. Callbacks can return a value but using the dame function for a callbacks and getting that output contents does not look good.
You are clearing the value of input before calculating the total. I have updated your code little bit to work as you intended.
input = document.getElementById("input");
output = document.getElementById("output");
input.onkeypress = function(event) {
checkKey(event);
};
function checkKey(e) {
// check for enter: e.key is for Firefox
// if true, make input empty
if (e.keyCode == 13 || e.key == 13) {
// Note : in the begining the output text box is empty, so while output is empty i have assign 0 as its value.
outputValue = (output.value == '') ? 0 : output.value;
total = parseInt(outputValue) + parseInt(input.value);
input.value = "";
// To update the total in output text box
document.getElementById("output").value = total;
}
}

I want to show error message beside my textbox rather than alert in onkeyup event

I want to show error message beside my textbox rather than alert in onkeyup event
HTML
<input type="textbox"
id="id_part_pay"
value="<?php echo $listing['part_pay'];?>"
name="part_pay"
/>
javascript
$("#id_part_pay").keyup(function()
{
var input = $('#id_part_pay').val();
var v =input % 10;
if (v!==0)
{
alert("Enter Percentage in multiple of 10");
}
if(input<20 || input>100)
{
alert("Value should be between 20 - 100");
return;
}
});`
Create a span beside input then change your code as
$(function() {
$("#id_part_pay").next('span').hide(); //Hide Initially
$("#id_part_pay").keyup(function() {
var input = $(this).val();
var v = input % 10;
var span = $(this).next('span'); //Get next span element
if (v !== 0) {
span.text("Enter Percentage in multiple of 10").show(); //Set Text and Show
return;
}
if (input < 20 || input > 100) {
span.text("Value should be between 20 - 100").show();//Set Text and Show
return;
}
span.text('').hide();//Clear Text and hide
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="textbox" id="id_part_pay" value="10" name="part_pay" />
<span></span>

Putting the data clicked by the user in the text field in the pop up using javascript [duplicate]

This question already has answers here:
How to get a word under cursor using JavaScript?
(12 answers)
Closed 7 years ago.
The problem that I am currently dealing with is that the user has to enter the text in a text area and after the entering of the text the user is free to click on any of the text that he entered, the clicked text than has to be displayed the popup .Following is the code that is not working as per the above problem stated.
<p id="msg">roli</p>
<form onload>
<center><label>Enter text:</label><br>
<textarea style="width:100px; height:100px" id="hello" >
</textarea>
</center>
</form>
<script>
var stopCharacters = [' ', '\n', '\r', '\t']
$(function() {
document.getElementById("msg").innerHTML="bhanu";
$('textarea').on('click', function() {
var text = $(this).html();
var start = $(this)[0].selectionStart;
var end = $(this)[0].selectionEnd;
while (start > 0) {
if (stopCharacters.indexOf(text[start]) == -1) {
--start;
} else {
break;
}
};
++start;
while (end < text.length) {
if (stopCharacters.indexOf(text[end]) == -1) {
++end;
} else {
break;
}
}
var currentWord = text.substr(start, end - start);
alert(currentWord);
});
});
</script>
Here you need to create a range for selection
var stopCharacters = [' ', '\n', '\r', '\t'];
$(function() {
document.getElementById("msg").innerHTML="bhanu";
$('textarea').on('click', function() {
var textComponent = document.getElementById('hello');
var currentWord;
// IE version
if (document.selection != undefined){
textComponent.focus();
var sel = document.selection.createRange();
currentWord = sel.text;
}
// Mozilla version
else if (textComponent.selectionStart != undefined){
var startPos = textComponent.selectionStart;
var endPos = textComponent.selectionEnd;
while(textComponent.value.charAt(startPos)!=' '){
if(startPos<=0)break;
startPos--;
console.log(startPos);
}
while(textComponent.value.charAt(endPos)!=' '){
if(endPos >= textComponent.value.length)break;
endPos++;
console.log(endPos);
}
currentWord = textComponent.value.substring(startPos, endPos);
}
alert(currentWord);
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<p id="msg">roli</p>
<form onload>
<center><label>Enter text:</label><br>
<textarea style="width:100px; height:100px" id="hello" ></textarea>
</center>
</form>
Did you mean like clicking on the same text box will alert the user with the contents of the text box? If so, you don't need any JavaScript or complex stuff which you have done. Click on the below snippet and click on the text box.
var stopCharacters = [' ', '\n', '\r', '\t'];
$(function() {
$("#msg").html("bhanu");
$('textarea').on('click', function() {
if ($(this).val().trim().length == 0)
return;
var textComponent = $(this)[0];
var currentWord;
// IE version
if (document.selection != undefined){
textComponent.focus();
var sel = document.selection.createRange();
currentWord = sel.text;
}
// Mozilla version
else if (textComponent.selectionStart != undefined){
var startPos = textComponent.selectionStart;
var endPos = textComponent.selectionEnd;
currentWord = textComponent.value.substring(startPos, endPos)
}
alert(currentWord);
});
});
textarea {display: block;}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<p id="msg">roli</p>
<form>
<label for="hello">Enter text:</label>
<textarea style="width:100px; height:100px" id="hello" ></textarea>
</form>

Getting the position of the caret in textarea on click

Suppose you have a textarea and a button, and that you wanted that button to get the position of the caret in a textarea, whenever that button was clicked. (I know, there would be a loss of focus from the text area to the button.)
Is there a way to recall where the caret was in the textarea? If so, how would one go about doing that (so that they could, for example, have said button write text to that area)?
Get the position of caret when it loses focus:
var caretStart, caretEnd;
$('#textarea').on('blur', function(e) {
caretStart = this.selectionStart;
caretEnd = this.selectionEnd;
});
To write text when a button was click:
$('#btnWriteText').on('click', function(e) {
var text = " Example ";
var $this = $('#textarea');
// set text area value to: text before caret + desired text + text after caret
$this.val($this.val().substring(0, caretStart)
+ text
+ $this.val().substring(caretEnd));
// put caret at right position again
this.selectionStart = this.selectionEnd = caretStart + text.length;
});
This solution may help you. You can try out,
<html>
<head>
<title>Get/Set Caret in Textarea Example</title>
<script>
function doGetCaretPosition (ctrl) {
var CaretPos = 0;
// IE Support
if (document.selection) {
ctrl.focus ();
var Sel = document.selection.createRange ();
Sel.moveStart ('character', -ctrl.value.length);
CaretPos = Sel.text.length;
}
// Firefox support
else if (ctrl.selectionStart || ctrl.selectionStart == '0')
CaretPos = ctrl.selectionStart;
return (CaretPos);
}
function setCaretPosition(ctrl, pos)
{
if(ctrl.setSelectionRange)
{
ctrl.focus();
ctrl.setSelectionRange(pos,pos);
}
else if (ctrl.createTextRange) {
var range = ctrl.createTextRange();
range.collapse(true);
range.moveEnd('character', pos);
range.moveStart('character', pos);
range.select();
}
}
function process()
{
var no = document.getElementById('no').value;
setCaretPosition(document.getElementById('get'),no);
}
</script>
</head>
<body>
<textarea id="get" name="get" rows="5" cols="31">Please write some integer in the textbox given below and press "Set Position" button. Press "Get Position" button to get the position of cursor.</textarea>
<br>
Enter Caret Position: <input type="text" id="no" size="1" /><input type="button" onclick="process();" value="Set Position">
<BR>
<input type="button" onclick="alert(doGetCaretPosition(document.getElementById('get')));"
value="Get Position">
</body>
</html>
Source: http://blog.vishalon.net/index.php/javascript-getting-and-setting-caret-position-in-textarea/

Using event.which to verify if the user pressed the spacebar doesn't work in Firefox

I want a script to verify if the key pressed is 'spacebar', keycode 32. I noticed that IE uses other function names.
I tried a lot of solutions found here and this:
event = event || window.event // IE does not pass event to the function
if(event == window.event){
code = event.keyCode;
}else{
code = event.which;
}
if(code == '32') {}
But it still didn't work in Firefox.
I think I'm calling the function wrongly in Firefox. Look at the entire script:
<textarea onkeydown="predicao(this);" cols="40" rows="10" id="test" onfocus="this.focus()"></textarea>
<input id="example" style="display: none;" onkeydown="javascript: insert(this);"/>
<script language="Javascript">
<!--
function predicao(objeto){
comprimento = objeto.value.length;
var antipenultimo = comprimento - 4;
var input = objeto.value.substring(antipenultimo,comprimento);
var output = "";
for(i=0; i<input.length; ++i){
if(output != "") output += ", ";
output += input.charCodeAt(i);
}
if (output == "91, 91, 103, 32"){
var preditor = document.getElementById('example');
preditor.value = '';
preditor.style.display = 'block';
preditor.focus();
preditor.select();
}
}
function insert(objeto){
event = event.which || window.event // IE does not pass event to the function
if(event == window.event){
code = event.keyCode;
}else{
code = event.charCode;
}
if(keynum == '32') {
var texto = document.getElementById('test').value;
texto += objeto.value+']]';
$('#test').focus();
document.getElementById('test').value = texto;
objeto.style.display = 'none';
}
}
$(document).ready(function(){
var data = "Ab Aco Ado Ala Mano Cata Ca Obo Olo Po Poq".split(" ");
$("#example").autocomplete(data);});
</script>
What I'm trying to do is - (I don't know the name) - a Prediction Help Inputter inside a textarea. It uses jQuery autocomplete.
When the user types '[[g ' inside textarea (id=test), a input with autocomplete is opened (id=example), so it search in 'data'. When the user find the desired data, he must press spacebar to insert the data into the textarea, closing with ']]' But it doesn't work in Firefox.
(And yes, I'm using JavaScript and jQuery to same elements in a totally wrong way because I'm not too good at this, I'll try to correct it after Firefox works.)
EDIT
HMTL:
<textarea onkeydown="predicao(this);" cols="40" rows="10" id="test" onfocus="this.focus()"></textarea>
<input id="example" style="display: none;" onkeydown="insert(this, event);"/>
JS:
function predicao(objeto){
var comprimento = objeto.value.length;
var antipenultimo = comprimento - 4;
var input = objeto.value.substring(antipenultimo,comprimento);
var output = "";
for(var i=0; i<input.length; ++i){
if(output != "") output += ", ";
output += input.charCodeAt(i);
}
if (output == "91, 91, 103, 32"){
var preditor = document.getElementById('example');
preditor.value = '';
preditor.style.display = 'block';
preditor.focus();
preditor.select();
}
}
function insert(objeto, evt){
var e = evt || event;
var code = e.keyCode || e.which;
if(code == '32') {
var texto = document.getElementById('test').value;
texto += objeto.value+']]';
$('#test').focus();
document.getElementById('test').value = texto;
objeto.style.display = 'none';
}
}
$(document).ready(function(){
var data = "Ab Aco Ado Ala Mano Cata Ca Obo Olo Po Poq".split(" ");
$("#example").autocomplete(data);});
I used here what Alexander Kahoun and pimvdb have posted.
I've never had any problems with the following and I've used it in IE6 through IE9, Firefox 3.5-5 and Chrome from at least 9-13
function captureSpace (evt) {
var e = evt || event;
var code = e.keyCode || e.which;
if (code === 32) {
// Do your thing...
}
}
This uses a logical OR to basically say if evt is a falsy value then use the window.event
var e = evt || event;
This uses a logical OR to assign the code for the key pressed in the same way
var code = e.keyCode || e.which;
This gives you a true or false value if the code is exactly equal to the integer value of 32
(code === 32)
I also suggest that you assign this to the key UP event.
In principle the way you do it should work. Check this out:
<html>
<head>
<script type="text/javascript">
function check(e){
var keynum
if(window.event)
{
keynum = e.keyCode
}
else if(e.which)
{
keynum = e.which
}
if(keynum=='32')
{
alert(keynum);}
}
</script>
</head>
<form>
<input type="text" onkeypress="check(event)" />
</form>
</body>
</html>
It seems that your lack of response is context dependent.
To display unicode of key pressed
<script type="text/javascript">
function displayunicode(e){
var unicode=e.keyCode? e.keyCode : e.charCode;
alert(unicode);
}
</script>
<form>
<input type="text" size="2" maxlength="1" onkeyup="displayunicode(event); this.select()" />
</form>
Determining which key was pressed

Categories