Deselect text with Javascript - javascript

I have two input tag with numeric id in a form in one html page. On focus, I would like to set value of the second input from first and second character of the first input. Then I want to deselect the selected text in second input. There is a way to do that?
I wrote this HTML code:
<label>Num. Fattura:
<input type="text" name="numfattura1" onkeypress="return event.keyCode != 13" id="1" />
</label>
<label>Importo:
<input type="text" name="importo1" onkeypress="return event.keyCode != 13" />
</label>
<br />
<label>Num. Fattura:
<input type="text" name="numfattura2" onkeypress="return event.keyCode != 13" id="2" onfocus="twoDigits(2)" />
</label>
<label>Importo:
<input type="text" name="importo2" onkeypress="return event.keyCode != 13" />
</label>
<br />
And this javascript function:
function twoDigits(id){
var previousId = id - 1;
var prevoiusValue = document.getElementById(previousId).value;
document.getElementById(id).value = prevoiusValue.substring(0,2);
document.selection.empty();
window.getSelection().removeAllRanges()
}
I can't find how to deselect the text that is selected automatically.

set selectionStart and selectionEnd using setTimeOut.
http://jsfiddle.net/enQvT/ works in firefox.
function twoDigits(id){
var previousId = id - 1;
var prevoiusValue = document.getElementById(previousId).value;
var elem = document.getElementById(id);
setTimeout(function() {
elem.selectionStart=0;
elem.selectionEnd=0;
}, 0);
elem.value = prevoiusValue.substring(0,2);
}

Call .focus() on a another form element.

You can also empty and refill the input.
If you want to test:
<input type="textfield" id="aaa" value="aaa" />
<input type="textfield" id="bbb" value="bbb" onmouseover="empty()" />
<script>
var empty = function() {
var ipt = document.getElementById('aaa');
var iptval = ipt.value;
ipt.value = "";
ipt.value = iptval;
}
</script>

Related

How to get last focused field?

This is my HTML code :
<input type="button" value="1000" onclick="myFunc(this.value)" />
<input type="button" value="2000" onclick="myFunc(this.value)" />
<input type="button" value="3000" onclick="myFunc(this.value)" />
<input type="button" value="4000" onclick="myFunc(this.value)" />
<input type="textbox" value="0" name="myTextbox1" />
<input type="textbox" value="0" name="myTextbox2" />
and here is JS :
function myFunc(value){
if($('[name=myTextbox1]').is(':focus')){
var prevVal = $('[name=myTextbox1]').val();
$('[name=myTextbox1]').val(parseInt(prevVal) + parseInt(value));
$('[name=myTextbox1]').focus();
}else if($('[name=myTextbox2]').is(':focus')){
var prevVal = $('[name=myTextbox2]').val();
$('[name=myTextbox2]').val(parseInt(prevVal) + parseInt(value));
$('[name=myTextbox2]').focus();
}
}
I need to add clicked buttons value to focused textbox value.
When i click button the focus is on button, so can i get last focused textbox?
Thank you ..
var lastFocused = null;
<input type="textbox"
value="0"
name="myTextbox2"
onfocus="lastFocused=this;"/>
I apologize if there are syntax errors, I'm submitting this from my phone, so I do not have a good way to test it.
Create a variable for lastFocused and set it in an onFocus event handler for each text box
<input type="textbox" value="1" class="is_focus"/>
<input type="textbox" value="2" class="is_focus"/>
<input type="textbox" value="3" class="is_focus"/>
<button class="get_data">Click</button>
$(function() {
var focus_variable = null;
$('body').on('focus', '.is_focus', function(e) {
focus_variable = $(this);
});
$('body').on('click', '.get_data', function(e) {
var focus_data = focus_variable.val();
console.log(focus_data);
});
});

How to chang all <input> to its value by clicking a button and change it back later?

The problem: I have a page with many <input> fields (just say all are text fields)
I would like to have a button, when click on it, all input fields will become plaintext only.
e.g. <input type="text" value="123" /> becomes 123
and if I click on another button, the text will change back to
e.g. 123 becomes <input type="text" value="123" />
Is there an automatic way to scan for all the <input>s and change them all at once using javascript and jquery.
Thank you!
Edited
Seems you guys are getting the wrong idea.
Read what I have written again: e.g. <input type="text" value="123" /> becomes 123
I have value="123" already, why would I want to set the value again???
What I want is e.g.
<body><input type="text" value="123" /><input type="text" value="456" /></body> becomes <body>123456</body> and later <body>123456</body> back to <body><input type="text" value="123" /><input type="text" value="456" /></body>
Use this to go one way,
$('input').replaceWith(function(){
return $('<div />').text(this.value).addClass('plain-text');
});​​​
and this to go the other.
$('.plain-text').replaceWith(function(){
return $('<input />').val($(this).text());
});
​
Check this link http://jsfiddle.net/Evmkf/2/
HTML:
<div id='divInput'>
<input type="text" value='123' />
<br/>
<input type="text" value='456' />
<br/>
<input type="text" value='789' />
</div>
<div id='plainText' style='display:none'></div>
<div>
<input type="button" id='btnPlain' value='Make It Plain' />
<input type="button" id='btnInput' value='Make It Text' />
</div>​
Javascript:
$("#btnPlain").bind('click',function(){
$("#plainText").html('');
$("#divInput input[type=text]").each(function(index){
$("#plainText").append('<span>'+$(this).val()+'</span>');
$("#divInput").hide();
$("#plainText").show();
});
});
$("#btnInput").bind('click',function(){
$("#divInput").html('');
$("#plainText span").each(function(index){
$("#divInput").append('<input type="text" value="'+$(this).text()+'"/><br/>');
$("#plainText").hide();
$("#divInput").show();
});
});
​
Try this FIDDLE
$(function() {
var arr = [];
$('#btn').on('click', function() {
var $text = $('#inp input[type="text"]');
if( $text.length > 0){
$text.each(function(i) {
arr[i] = this.value;
});
$('#inp').html(arr.join());
}
else{
if(arr.length <= 0){
}
else{ // Add Inputs here
var html = '';
$.each(arr, function(i){
html += '<input type="text" value="' + arr[i]+ '"/>'
});
$('#inp').html(html);
}
}
});
});
​
You need to create a hidden element for each input, then use jquery to hide the input, show the hidden element and give it the inputs value.
<input type="text" value="123" id="input_1" />
<div id="div_1" style="display:none;"></div>
$("#div_1").html($("input_1").val());
$("#input_1").hide();
$("#div_1").show();

How to force "enter key" to act as "tab key" using javascript?

I'm working on a site that is full of forms to be filled and I it's required that when escape button is pressed focus move to the next input control, just as pressing "tab" do.
I found code to move focus when keypressed is 13 but this need to take the ID of element to focus on
<input id="Text1" type="text" onkeydown="return noNumbers(event)" />
<input id="Text2" type="text" />
<script type="text/javascript">
function noNumbers(e) {
keynum = e.which;
if (keynum == 13)
document.getElementById("Text2").focus();
}
</script>
I need a generalized function that when key pressed code is 13 "that is enter" fire the default event of pressing 9 "that is tab", of course in Javascript
This will handle multiple input fields.
Here is the jQuery version:
http://jsfiddle.net/TnEB5/3/
$('input').keypress(function(e) {
if (e.which == 13) {
$(this).next('input').focus();
e.preventDefault();
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input id="Text1" type="text" />
<input id="Text2" type="text" />
<input id="Text3" type="text" />
Here is the pure javascript version:
http://jsfiddle.net/TnEB5/5/
(you probably want to get the sibling differently)
function tab(e) {
if (e.which == 13) {
e.target.nextSibling.nextSibling.focus();
e.preventDefault();
}
}
var inputs = document.getElementsByTagName('input');
for (var x = 0; x < inputs.length; x++)
{
var input = inputs[x];
input.onkeypress = tab;
}
<input id="Text1" type="text" />
<input id="Text2" type="text" />
<input id="Text3" type="text" />
handle keypress instead and return false back to the browser:
http://jsfiddle.net/EeyTL/
<input id="Text1" type="text" />
<input id="Text2" type="text" />
<script type="text/javascript">
document.getElementById('Text1').onkeypress = function (e) {
if (e.which === 13) {
document.getElementById("Text2").focus();
return false;
}
};
</script>
You'll need to explicitly set the tabindex property of the input fields for a generic solution. Something like
<input id="Text1" type="text" tabindex="1" />
<input id="Text2" type="text" tabindex="2" />
<script type="text/javascript">
$('input').keypress(function(e){
if(e.which==13){
$("[tabindex='"+($(this).attr("tabindex")+1)+"']").focus();
e.preventDefault();
}
});
</script>
this solution uses jquery to assign the event handler for all input type elements on the page, sets focus to the element with the next highest tabindex property, and prevents the form from submitting when enter is pressed using e.preventDefault(). Here's a jfiddle
<input type="text" value="" onkeyup="doNext(this);"> a <br>
<input type="text" value="" onkeyup="doNext(this);"> b <br>
<input type="text" value="" onkeyup="doNext(this);"> c <br>
function doNext(el){
if(event.keyCode=='13'){
var nextEl = el.form.elements[el.tabIndex+1];
if (nextEl && nextEl.focus) nextEl.focus();
}
}
Althought the post is old, I hope my answer can help someone in need. I have a smilar situation:
I have a very large form for an employee scheduler application with different types of input fields. Some of the input fields are hidden sometimes and not other times. I was asked to make the enter key behave as the tab key so the users of the form could use the 10-key when creating thier employees schedule.
Here is how I solved my problem:
$(document).ready(function () {
var allInputs = $(':text:visible'); //(1)collection of all the inputs I want (not all the inputs on my form)
$(":text").on("keydown", function () {//(2)When an input field detects a keydown event
if (event.keyCode == 13) {
event.preventDefault();
var nextInput = allInputs.get(allInputs.index(this) + 1);//(3)The next input in my collection of all inputs
if (nextInput) {
nextInput.focus(); //(4)focus that next input if the input is not null
}
}
});
});
What I had to do was:
Create a collection of all the inputs I want to consider when tabbing. in my case it is text inputs that are visible.
Listen for a keydown event on the inputs in question, in my case all text field inputs
When the enter is pressed on my text input, determine what input is next to be focused.
If that input is valid, bring it into focus.
I am using this code for advancing to next input field. I hate to press TAB key. And this solution works in IE & Firefox:
<script type="text/javascript">
function tabE(obj,e){
var e=(typeof event!='undefined')?window.event:e;// IE : Moz
if(e.keyCode==13){
var ele = document.forms[0].elements;
for(var i=0;i<ele.length;i++){
var q=(i==ele.length-1)?0:i+1;// if last element : if any other
if(obj==ele[i]){ele[q].focus();break}
}
return false;
}
}
</script>
HTML Content
<form id="main">
<input name="" type="text" onkeypress="return tabE(this,event)">
<input type="submit" value="Ok">
</form>
Here is a easy solution for you.
Basically you include the enter2tab.js file and then add the enter2tab class on each object where you want enter to be treated as js.
https://github.com/AndreasGrip/enter2tab
You can obviously look at the code to understand what it does and how..
I believe using e.preventDefault(); is safer than returning false.

Prevent tab text highlight / disable tab text selection

Here's a sample form:
<form action="#" method="post">
Name:<br />
<input type="text" name="name" value="your name" /><br />
E-mail:<br />
<input type="text" name="mail" value="your email" /><br />
<input type="submit" value="Send">
</form>
When you tab to a text input, the value gets highlighted. How can it be disabled?
Any help is appreciated!
Mike
var $yourInput;
$yourInput = $("#your_input");
setTimeout(function() {
return $yourInput.selectRange($yourInput.val().length, $yourInput.val().length);
}, 10);
selectRange function you can find here: jQuery Set Cursor Position in Text Area
Hello here is the solution. Dirty one:
html:
<input type="text" id="a" />
<input type="text" id="b" />
Javascript:
$("input").focus(function(){
if($(this).val() != ""){
var elm = $(this);
var val = elm.val();
setTimeout(function(){elm.val(val);},1);
}
});
Demo: http://jsfiddle.net/naveed_ahmad/S2UPs/
This is working, at least in Firefox. It triggers the "End" key:
$('input[type=text]').bind('focus',function(){
var e = jQuery.Event("keydown");
e.which = 35; // # key code for end key
$("input[type=text]").trigger(e);
return false;
});

Add textbox when button is pressed

I know this can be accomplished in Javascript (I hope!) I have a couple of forms on my page, but I cannot guess how many the user will need, so is there some magic which can be done in javascript which when a button is pressed this:
<input name="userfile[]" type="file" /><br />
<input type="text" value="Description goes here." name="imagedescription2" maxlength="20" onfocus="this.value = '';" /><br />
Is added to a designated area? Keeping in mind adding a number onto the name if the button is pressed eg name="imagedescription3" next name="imagedescription4" and so forth
This may be posted around the internet, I know it would be, I just don't know how to thorougly phrase my question
If possible, I recommend adding jQuery to your project. It makes DOM manipulation easy.
http://api.jquery.com/category/manipulation/
An example might look like this
Add Item
<div id="#wrapper">
<input type="text" value="Description goes here." name="imagedescription1" maxlength="20" onfocus="this.value = '';" /><br />
<input type="text" value="Description goes here." name="imagedescription2" maxlength="20" onfocus="this.value = '';" /><br />
</div>
<script>
$(function(){
var i = 3; // i would be incremented with each add.
$("#myButton").click(function(){
$('<input type="text" value="Description goes here." name="imagedescription' + i + '" maxlength="20" onfocus="this.value = '';" /><br />').appendTo('#wrapper');
});
return false;
});
</script>
You can write a JS function for adding textboxes and call the function when the button is pressed.
The function should go along these lines....
var count;
function functionName()
{
count++;
document.Write('<input type="text" value="..." name="imagedescriptor'+count+'" max..');
}
Hopefully it works.
Try this:
var i = 2;
var sourceTextNode = document.getElementsByName("imagedescription2")[0];
function createTextBox(){
var newNode = sourceTextNode.cloneNode(false);
newNode.setAttribute("name", ++i);
var parent = sourceTextNode.parentNode;
if(parent.lastchild == sourceTextNode) {
parent.appendChild(newNode);
} else {
parent.insertBefore(newNode, sourceTextNode.nextSibling);
}
}
function btnClicked(){
createTextBox();
}
another jQuery solution:
Live Demo
$("#f_add").click(function(e) {
var field = document.createElement('input');
$(field).attr('type', 'text');
$(field).attr('name', 'field[]');
$("#thenewhotness").append(field);
e.preventDefault();
});
<form id="thenewhotness">
<button id="f_add">Add Extra Field</button>
<input type="text" name="field[]">
</form>

Categories