Set cursor position in an input text field - javascript

After a lot of search I found the following threads:
define cursor position in form input field
jQuery Set Cursor Position in Text Area
Unfortunately in none of the posts a complete form embed code or a real example is given. Now I just don't know how to include nemisj's code (on the first link) or Mark's code (on the second link) into my form:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<script src="http://code.jquery.com/jquery-latest.js"></script>
<script type="text/javascript" src="http://dev.jquery.com/view/trunk/plugins/validate/jquery.validate.js"></script>
<script>
$(document).ready(function(){
$("#site").focus(function(){
if( this.value == this.defaultValue ) {
$(this).val("http://");
}
});
});
</script>
</head>
<body>
<form action="#" method="post">
<input id="name" type="text" name="name" value="Name" /><br />
<input id="site" type="text" name="mail" value="Website" /><br />
<input type="submit" value="Send">
</form>
</body>
</html>
I wonder if someone could kindly help me with this as I'm badly stuck!
Many thanks in advance!
Here's the edited code, but it still doesn't work:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<script src="http://code.jquery.com/jquery-latest.js"></script>
<script type="text/javascript" src="http://dev.jquery.com/view/trunk/plugins/validate/jquery.validate.js"></script>
<script>
function setCursor(node,pos){
var node = (typeof node == "string" || node instanceof String) ? document.getElementById(node) : node;
if(!node){
return false;
}else if(node.createTextRange){
var textRange = node.createTextRange();
textRange.collapse(true);
textRange.moveEnd(pos);
textRange.moveStart(pos);
textRange.select();
return true;
}else if(node.setSelectionRange){
node.setSelectionRange(pos,pos);
return true;
}
return false;
}
$(document).ready(function(){
$("#site").focus(function(){
if( this.value == this.defaultValue ) {
$(this).val("http://");
var node = $(this).get(0);
setCursor(node,node.value.length);
}
});
});
</script>
</head>
<body>
<form action="#" method="post">
<input id="name" type="text" name="name" value="Name" /><br />
<input id="site" type="text" name="mail" value="Website" /><br />
<input type="submit" value="Send">
</form>
</body>
</html>

Inside your <script></script> tag is where your JavaScript goes (although we prefer putting it in a separate file, so that no JavaScript lives on the HTML page itself).
Inside that, you have a call to $(document).ready(), which passes a function() { ... }. Inside that function is all the code that will be executed when your document has loaded.
Inside that function you have a call to $('#site').focus() which itself provides a function — this time one that will be called whenever the #site element gains focus. And presumably that's where you want to change the cursor position.
So, taking the setCursor function from Set cursor at a length of 14 onfocus of a textbox you can put that anywhere in your <script></script> and then inside that innermost function of yours you can write:
if( this.value == this.defaultValue ) {
$(this).val("http://");
var node = $(this).get(0);
setCursor(node,node.value.length);
}

I think I found the error in your setCursor method. The moveStart and moveEnd methods expect two arguments, the first being the unit it should use. Also, the end position appears to be relative to the start position. So I think instead of
textRange.moveEnd(pos);
textRange.moveStart(pos);
you want
textRange.moveStart('character', pos);
textRange.moveEnd('character', 0);
See: http://msdn.microsoft.com/en-us/library/ie/ms536623(v=vs.85).aspx

Oh, this one's easier done than said!
<script>
function setCursorInputPosition(e, pos) {
e.setSelectionRange(pos, pos);
}
</script>
<input onfocus="setCursorInputPosition(this, this.value.length);">

Related

Why can't set focus on element with nextElementSibling.focus() and parentNode.children[0].focus()?

I want to move mouse focus when keydown is enter,to emulate enter as tab.
function jump(event){
var ob = event.target;
if(event.keyCode == 13){
if(ob.nextElementSibling){
ob.nextElementSibling.focus();
}
else{
ob.parentNode.children[0].focus();
}
}
}
document.body.addEventListener("keydown",jump,true);
content:<input id="1th" type="text">
<br/>
content:<textarea id="2th" cols=6 rows=5></textarea>
<br/>
content:<input id="3th" type="text">
<br/>
content:<input id="4th" type="text">
My expectation:
When you type some characters ,for example test in the input whose id is "1th",and press enter,the mouse focus jump into the input whose id is "2th".
When you type some characters ,for example test in the input whose id is "4th",and press enter,the mouse focus jump into the input whose id is "1th".
I tested my code ,no error info occur,but it can't achieve my target.
How to fix it?
I have set breakpoint at the 23th line,still nothing found.
As per the chat discussion, your issue is that the nextElementSibling in the <br/>. If you dont want to use nextElementSibling.nextElementSibling, There are two options that can help you here:
Either:
Remove the <br> and use CSS to add the necessary margin-bottom.
Or:
Add a class to your input/textArea elements and use jQuery with the function .next('className'). There are equivalents in Javascript but it will add a lot of unnecessary code.
I definitely recommend the first option than loading a whole library if the only use would be that one function.
According to the chat with callback.
1.Format1:script is at the head ,add window.onload.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title></title>
<script>
window.onload = function(){
function jump(event){
var ob = event.target;
if(event.keyCode == 13){
if(ob.nextElementSibling != null){
ob.nextElementSibling.nextElementSibling.focus();
}
else {
ob.parentNode.children[0].focus();
}
}
}
document.body.addEventListener("keydown",jump,true);
}
</script>
</head>
<body>
content:<input id="1th" type="text">
<br/>
content:<textarea id="2th" cols=6 rows=5></textarea>
<br/>
content:<input id="3th" type="text">
<br/>
content:<input id="4th" type="text">
</body>
</html>
Format 2:script is put at the end of the last input whose id is 4th.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title></title>
</head>
<body>
content:<input id="1th" type="text">
<br/>
content:<textarea id="2th" cols=6 rows=5></textarea>
<br/>
content:<input id="3th" type="text">
<br/>
content:<input id="4th" type="text">
<script>
function jump(event){
var ob = event.target;
if(event.keyCode == 13){
console.log(ob.nextElementSibling.tagName);
if(ob.nextElementSibling.tagName == "BR"){
ob.nextElementSibling.nextElementSibling.focus();
}
else if(ob.nextElementSibling.tagName == "SCRIPT"){
ob.parentNode.children[0].focus();
}
}
}
document.body.addEventListener("keydown",jump,true);
</script>
</body>
</html>
The whole code is position-related,different position of script's content in the html file,you should write different js code for that.

Showing hidden input field with custom text

I have this text field hidden with HTML hidden code, now when the user enter an invalid input I use javascript to unhide the text field and display an error message, this is what is suppose to happen.
I have seen a lot of css style like
`style.visibility = 'visible';` and `style.display='block';`
But none of them are working for me what happens is that the error text shows for less than a second and then disappears, any one would like to share their thoughts.
This is the complete code for better understanding, it's still not working in firefox and Edge while IE and Chrome wont do anything, in Firefox, it just blinks once on each button press and that about it.
Javascript:
</script>
function validate(){
var firstname = document.getElementById("fn").value;
if (firstname == "") {
document.getElementById("fn").style.visibility = "visible";
document.getElementById("fn").text = "ERROR";
}
}
function init()
{
var formData = document.getElementById("enqForm");
formData.onsubmit = validate;
}
window.onload = init;
</script>
<!DOCTYPE html>
<html lang="en">
<head>
<script src="scripts.js"></script>
</head>
<body>
<form id="enqForm">
<input id="fn" type="text" placeholder="First Name *" />
<input id="sendbutton" type="submit" value="Enquire" />
</form>
</body>
</html>
Instead of changing the style, you can change the form's type attribute.
Using JavaScript - assuming you want to change lnspan to text:
document.getElementById('lnspan').type = 'text';
Style is not the same as the type attribute.
Also there's two id attributes in your <input>, you may want to change that.
**THAT IS THE ANSWER TO YOUR QUESTION**
<html>
<head>
<script>
function newDoc() {
document.getElementById("hid").type="text";
document.getElementById("hid").value="ERROR";
}
</script>
</head>
<body>
<input type="button" value="Load new document" onclick="newDoc()">
<input type="hidden" id="hid" value="">
</body>
</html>
<!--However this makes your error message as text field which is not good.
What you can do is make the Error into embedded into paragraph <p> so the
users cannot change it and it also looks more professional
<!DOCTYPE html>
<html>
<head>
<script>
function newDoc() {
document.getElementById("te").innerHTML="ERROR";
}
</script>
</head>
<body>
<input type="button" value="Load new document" onclick="newDoc()">
<p id="te">
</body>
</html>

Why is my script not showing input characters dynamically in a div

I want to create a TextField in which when I give any input it show on div and this script is showing inputs but not properly...
I don't know where I am making mistakes and I request that please give your answers only in JavaScript please don't use jquery. Thank you .
<!DOCTYPE html>
<html>
<head>
<meta charset=utf-8 />
<title>JS Bin</title>
</head>
<body>
<form name="form">
<input name="t" value="" onkeypress="printvalues();">
</form>
<div id="divId"></div>
</body>
</html>
script
function printvalues() {
var div = document.getElementById("divId");
div.innerHTML += form.t.value;
}
Here is my code with output
function printvalues() {
var div = document.getElementById("divId");
div.innerHTML = document.form.t.value;
}
EDIT:The keypress event executes before the value of textbox is changed so use keyup() event which triggers when the key is released instead like
<input name="t" value="" onkeyup="printvalues();">
Your solution is here....
Just change onkeypress to onkeyup
Made below changes and enjoy..
function printvalues(a) {
var div = document.getElementById("divId");
div.innerHTML=a;
}
<input type="text" name="t" onkeyup="printvalues(this.value);">

Why does this give "undefined" error?

I am trying to get the user to put something into the text area and the output should be what he wrote repeapiting x amount of times, but I get an error "document.forme is undefined".
Can you please help me understand why it is undefined?
My code:
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<title>input home work</title>
<script type="text/javascript">
var help= document.forme.tryout.value;
for (x=1; x<=10;x++){
function numberCheak (){
document.write("this is"+" "+help++);
}
}
</script>
</head>
<body>
<form name="forme">
<input name="tryout" type="text" />
<input type="button" value="click me" onClick="numberCheak();"/>
</form>
</body>
</html>
Ok, you have a few problems. The first is that you are trying to access a form element that doesn't exist yet: the script is above the form element, so the form doesn't exist when you try to get it. If you move the script to the bottom of the page it will work better.
Second, the loop should be inside the function, not wrapped around the function.
Third, document.write has weird side effects and causes the document to be rewritten and will stop the script from continuing correctly.
Here's my revised script
function numberCheak() {
var help = document.forme.tryout.value;
for (var x = 1; x <= 10; x++) {
document.getElementById("output").innerHTML += help;
}
}
and the HTML form that goes with it
<form name="forme" id="forme">
<input name="tryout" type="text" />
<input type="button" value="click me" onclick="numberCheak();" />
<span id="output"></span>
</form>
You can see it in action on jsFiddle.
Forms are stored in collection and can be accessed like this:
var form = document.forms[i];
or
var form = document.forms[name];
In your case, i is 0 and name is forme.

jQuery: Count Number of Inputs with a Specific Value

I need to count the number of text inputs with a value of 1.
I have tried the following but with no luck.
$('.class[value="1"]').length
$('.class:contains("1")').length
Using $('.class[value="1"]') technically works, however, if the values in the text input are changed after load, it still counts it as its default load value.
I took a long shot by using the .live click event to get the current value but still no luck.
I had no luck at all using $('.class:contains("1")')
It seems very simple, but has so far eluded me.
This example demonstrates that this works:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html>
<head>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js"></script>
<script type="text/javascript">
$(function() {
$("#btn").click(function() {
alert($(":input[value='1']").length);
});
});
</script>
</head>
<body>
<input type="text">
<input type="text">
<input type="text">
<input type="button" id="btn" value="How many?">
</body>
</html>
Alternatively you can just loop:
var matches = 0;
$(":input.class").each(function(i, val) {
if ($(this).val() == '1') {
matches++;
}
});
You need to iterate with $.each() if you want current val() values:
k=0;
$('.class').each(function(i, e) {
if ($(e).val() == "1") k++;
});
$(':input.class').filter(function() {
return $(this).val() == '1'
})

Categories

Resources