Get click character position inside an input (not coordinate) - javascript

I'm trying to get the character position of a click inside an input. Meaning that if my input has the text abcdef and I click between the b and the c my click listener (inside my input element) would return 2.

$(document).on("click", function() {
var $txt = $("#txt");
var caretPos = $txt[0].selectionStart;
var textAreaTxt = $txt.val();
console.log(caretPos);
console.log(textAreaTxt[caretPos]);
});
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width">
<title>JS Bin</title>
<script src="https://code.jquery.com/jquery-3.1.0.js"></script>
</head>
<body>
<input id="txt" rows="15" cols="70"/>
</body>
</html>
Something like this? this essentially builds off quik_silv anwser you get the index value of the cursor then get the value of the text field and retrieve a value by the index it's on a button click but could be easily changed
$("#btn").on('click', function() {
var $txt = $("#txt");
var caretPos = $txt[0].selectionStart;
var textAreaTxt = $txt.val();
console.log(caretPos);
console.log(textAreaTxt[caretPos]);
});

//Try this
<input id="text" type="text" value="EXAMPLE" size="20" />
<script type="text/javascript">
document.getElementById('text').addEventListener('click', function() {
var length = this.value.length;
var x =length-(length-this.selectionStart)
alert(x);
},
false);

Related

Removing part of a form input's value with jQuery/JavaScript

I have a hidden input on my page like so:
<input type="hidden" name="required" value="name,town,tel,email">
As people fill in it's associated form, certain other fields become required (i.e. State becomes required when choosing "USA" from a Country dropdown).
I have two functions, one named addToRequiredFields() and one named removeFromRequiredFields() which fire as USA is selected/de-selected, however the removal one doesn't seem to be working, and I can't figure out why.
function addToRequiredFields(string) {
var required = $('input[name=required]').val();
required += ',' + string;
$('input[name=required]').val(required);
}
function removeFromRequiredFields(string) {
var required = $('input[name=required]').val();
required.replace(',' + string, '');
$('input[name=required]').val(required);
}
The function is called at .on('change') of the Select dropdown.
Though Its not a proper way to validate controls based on input value , I made a script for you .
function addToRequiredFields(string) {
var required = $('input[name=required]').val();
fieldsArray = required.split(",")
fieldsArray.push(string)
$('input[name=required]').val(fieldsArray.join());
}
function removeFromRequiredFields(string) {
var required = $('input[name=required]').val();
fieldsArray = required.split(",")
fieldsArray = fieldsArray.filter(function(item) {
return item !== string
})
$('input[name=required]').val(fieldsArray.join());
}
console.log($('input[name=required]').val())
addToRequiredFields("age")
console.log($('input[name=required]').val())
removeFromRequiredFields("name")
console.log($('input[name=required]').val())
removeFromRequiredFields("tel")
console.log($('input[name=required]').val())
addToRequiredFields("name")
console.log($('input[name=required]').val())
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width">
<title>JS Bin</title>
</head>
<body>
<input type="hidden" name="required" value="name,town,tel,email">
<script src="https://code.jquery.com/jquery-3.1.0.js"></script>
</body>
</html>
Use the below login inside yourremove function.removeFromRequiredFields
//var requiredArr = $('input[name=required]').attr('value');
var requiredArr = "name,town,tel,email".split(',');
var rmvIndex = requiredArr.indexOf("tel")//"tel" is your string to be removed
var newArr = requiredArr.splice(rmvIndex, 1);
$('input').attr('value', newArr.join(','))// set value attribute after removing that string

How can i replace a { with {}

I am trying to develop a braces auto completion feature in a text box. I tried the javascript replace function on the textbox. But i am getting a weird output from the function. Here's the code i am work on.
HTML:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>JS Bin</title>
</head>
<body>
<input type ="text" id="textbox">
</body>
</html>
Javascript:
var element = document.getElementById('textbox');
element.oninput = function(){
var code = (function(){
var val = element.value;
element.value = val.replace(/\{/ , "{}");
})();
};
When i type a single { brace i am getting {} , when i type more than 1 i am getting {}}}{{ and it goes on .. sometimes my browser freezes when i try to clear the braces.
Here's the js bin link JSBIN
The problem is that you are always replacing { with {}, even if the bracket has already been matched. You should instead ensure it was not with negative lookahead: /\{(?!\})/
To fix the backspace issue, you should instead be using an event which can tell you which key was pressed like onkeyup and add a guard clause. Expanding on #Andi's idea, I also added exclusion for the arrow keys so you won't be forced to the end of the textbox when you want to navigate through the text:
var element = document.getElementById('textbox');
element.onkeyup = function(){
if([8, 37, 39].indexOf(event.which) != -1)
return false;
var code = (function(){
var val = element.value;
element.value = val.replace(/\{(?!\})/g, "{}");
})();
};
Your regex matches '{', you should exclude all '{}':
Snippet: [regex : /(?!{})\{/ ]
var element = document.getElementById('textbox');
element.oninput = function() {
var code = (function() {
var val = element.value;
element.value = val.replace(/(?!{})\{/, "{}");
})();
};
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>JS Bin</title>
</head>
<body>
<input type="text" id="textbox">
</body>
</html>
Update (With Backspace working):
Need to use keyboard event so that we can get keycode of the key pressed. Use onkeyup
var element = document.getElementById('textbox');
element.onkeyup = function(e) {
if (e.which != 8) {
var val = element.value;
element.value = val.replace(/(?!{})\{/, "{}");
}
};
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>JS Bin</title>
</head>
<body>
<input type="text" id="textbox">
</body>
</html>
Regexs may become heavy for an autocompletion tool, especially with negative lookaheads.
Actually, you do not have to look for braces at each input, just test the character typed with onkeypress event.
And you should also put the caret into the braces, otherwise you have still one keystroke because you have to move back :)
var element = document.getElementById('textbox');
element.onkeypress = function(evt){
switch(String.fromCharCode(evt.which)){
case "{":
var currentCaretPosition= this.selectionStart;
var text= this.value;
this.value= text.slice(0, currentCaretPosition)+
"{\n\t\n}"+
text.slice(currentCaretPosition,text.length );
this.setSelectionRange( currentCaretPosition+3, currentCaretPosition+3 );
evt.preventDefault();
}
};
#textbox{
border:inset 1px #aaa;
width:80vw;
height:80vw;
margin:2vw;
padding:0.5vw
}
<textarea id="textbox">
function test()
</textarea>
The whole sting is evaluated each time the function is called.
{ -> {}
if you now add another } you get {}}{}
use val.replace(/\{$/ , "{}");
The $ only evaluates the last character. Here you can try to build regex queries:
https://regex101.com/r/iU4xT9/1
PS: Maybe it gets weirds when you delete the last } you could only call the function, when you add characters and ignore the delete key.
var element = document.getElementById('textbox');
element.onkeyup = function(event){
if(event.which == 8)
return false
var code = (function(){
var val = element.value;
element.value = val.replace(/\{$/ , "{}");
})();
};

dynamically adding form elements in javascript in IE/Mozilla

So, I have tried bunch of things but didn't founded a workaround with this
I have this code this works fine on Chrome. But it does't work on mozilla or IE, In the console it doesn't shows up any error. It just doesn't work.
<?php
echo"<script>alert('okay');</script>";
?>
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en">
<head>
<meta charset="UTF-8" />
</head>
<script type="text/javascript" LANGUAGE="JavaScript1.3">
function name3() {
var abc = document.createElement("FORM");
//abc.setAttribute("method","POST");
abc.method = "POST";
abc.action = "http://localhost/2.php";
var a = document.createElement("INPUT");
/*a.setAttribute("type","text");
a.setAttribute("name","a");
a.setAttribute("value","abc");*/
a.name = 'a';
a.value = "abc";
abc.appendChild(a);
abc.submit();
}
</script>
<input type = "button" onclick = "name3();" value = "click">
</html>
Instead of a.name, I have also tried using a.setAttribute but still didn't work
Please help!!! Thanks :)
You should append form to body and then latter removed it once posted. Currently you are not adding your form to DOM. it actually need to be in the DOM to be sent in a page load.
Complete Code
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en">
<head>
<meta charset="UTF-8" />
<script type="text/javascript">
function name3() {
var form = document.createElement("FORM");
form.method = "POST";
form.action = "http://localhost/2.php";
var a = document.createElement("INPUT");
a.name = 'a';
a.value = "abc";
form.appendChild(a);
//Apend form to body
document.getElementsByTagName('body')[0].appendChild(form);
//Submit form
form.submit();
// But once the form is sent, it's useless to keep it.
document.getElementsByTagName('body')[0].removeChild(form);
}
</script>
</head>
<body>
<input type="button" onclick="name3();" value="click" />
</body>
</html>
You should add the new element to the DOM tree first and then submit the form. If you do not want display them you can add styles to hide the elements.
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en">
<head>
<meta charset="UTF-8" />
</head>
<script type="text/javascript">
function name3() {
var abc = document.createElement("FORM");
//abc.setAttribute("method","POST");
abc.method = "POST";
abc.action = "http://localhost/2.php";
var a = document.createElement("INPUT");
/*a.setAttribute("type","text");
a.setAttribute("name","a");
a.setAttribute("value","abc");*/
a.name = 'a';
a.value = "abc";
abc.appendChild(a);
document.getElementById("body").appendChild(abc);
abc.submit();
}
</script>
<body id="body">
<input type = "button" onclick = "name3();" value = "click">
</body>

Getting value of textarea returns undefined

I have an html form and a js script that gets the value of a textarea. However, when I'm getting the value of the textarea with javascript it return "undefined".
I have the following:
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<meta name="viewport" content="width=device-width, initial-scale=1">
<script src="js/jquery/jquery-1.9.1.min.js"></script>
<script src="contentForm.js"></script>
</head>
<body>
<form method="post" >
<textarea name ="editor" id="editBox" rows="5" cols="2">type</textarea>
<p><input type="submit" id="submit" value="Submit"></p>
</form>
</body>
</html>
JS
function add() {
$("#submit").click(function() {
document.write("hello motto");
var message = "start js";
console.log(message);
var contents = $("#editBox");
var a = contents.val();
if(a === undefined) {
console.log("contents undefined");
}
console.log(contents);
var item = {"id":"12", "content": contents};
var obj = JSON.stringify(item);
var obj2 = JSON.parse(obj);
console.log("you have arrived");
document.write(obj2.id);
});
}
$(document).ready(function () {
add();
});
I tried the following to get the value of the textarea:
var content = $("#editBox").val();
and
var contents = $("textarea#editBox").val();
The val of the textarea is always undefined, with each of the methods I tried.
Is there another method for retrieving the value of a textarea?
Running document.write on a closed document will open a new document and destroy the DOM of the existing one.
This destroys the textarea, so when you try to retrieve it to get the value, it does not exist.
Remove the line document.write("hello motto");.
Use DOM manipulation to edit the existing document, instead of writing a new one.

Creating paragraphs based on user input

I'm having trouble, grabbing the user input, and having the onclick operator create additional paragraphs with each click.
Here is my HTML code.
<!DOCTYPE html>
<html lang='en'>
<head>
<title>Add Paragraph </title>
<meta charset='utf-8' >
<script src="../js/addPara.js" type="text/javascript"></script>
</head>
<body>
<div>
<input type='text' id='userParagraph' size='20'>
</div>
<div id="par">
<button id='heading'> Add your paragraph</button>
</div>
</body>
</html>
Here is Javascript code:
window.onload = function() {
document.getElementById("addheading").onclick = pCreate;
};
function pCreate() {
var userPar= document.createElement("p");
var parNew = document.getElementById('userParagraph').value;
userPar.innerHTML = par;
var area = document.getElementById("par");
area.appendChild(userPar);
}
userPar.innerHTML = par;
should be
userPar.innerHTML = parNew;
In your code:
> window.onload = function() {
> document.getElementById("addheading").onclick = pCreate;
> };
Where it is possible (perhaps likely) that an element doesn't exist, best to check before calling methods:
var addButton = document.getElementById("addheading");
if (addButton) {
addButton.onclick = pCreate;
}
Also, there is no element with id "addheading", there is a button with id "heading" though.
> function pCreate() {
> var userPar= document.createElement("p");
> var parNew = document.getElementById('userParagraph').value;
> userPar.innerHTML = par;
I think you mean:
userPar.innerHTML = parNew;
if you don't want users inserting random HTML into your page (perhaps you do), you can treat the input as text:
userPar.appendChild(document.createTextNode(parNew));
.
> var area = document.getElementById("par");
> area.appendChild(userPar);
> }
Your variable names and element ids don't make a lot of sense, you might wish to name them after the data or function they represent.
I did it and it worked.
<html lang='en'>
<head>
<title>Add Paragraph </title>
<meta charset='utf-8' >
<script>
window.onload = function() {
document.getElementById("heading").onclick = pCreate;
}
function pCreate() {
var userPar= document.createElement("p");
var parNew = document.getElementById('userParagraph').value;
userPar.innerHTML = parNew;
var area = document.getElementById("par");
area.appendChild(userPar);
}
</script>
</head>
<body>
<div>
<input type='text' id='userParagraph' size='20'>
</div>
<div id="par">
<button id='heading'> Add your paragraph</button>
</div>
</body>
</html>```

Categories

Resources