Paste text into selected textbox use Javascript
I have 2 textBox buttons and 1! I want to insert text into one of these text boxes. When I click on textbox_1
and click the button, mytext will appear in textbox_1
. When I click on textbox_2
and click the button, mytext will appear in textbox_2
. How can I do this using JavaScript? Please help me! I'm new to JavaScript!
source to share
enter id from two text boxes like textbox_1
and textbox_2
and put onclick='onCLickButton();'
in tag <button>
and write following code in script
var text_to_be_inserted = "sample";
function onCLickButton(){
document.getElementById("textbox_1").value='';
document.getElementById("textbox_2").value='';
if(document.getElementById("textbox_1").focused){
document.getElementById("textbox_1").value=text_to_be_inserted;
}
else if(document.getElementById("textbox_2").focused){
document.getElementById("textbox_2").value=text_to_be_inserted;
}
else{
// do nothing
}
}
Edited
Please accept my apologies, in fact I am used to using these functions as I have my own js file that has these functions.
add onfocus='onFocusInput(this);'
in tags <input>
and add the following code to your script
function onFocusInput(object){
document.getElementById("textbox_1").focused=false;
document.getElementById("textbox_2").focused=false;
object.focused = true;
}
source to share
<html>
<head>
<script type="text/javascript">
var index = false;
var text = "This text shifts to text box when clicked the button";
function DisplayText(){
if(!index){
document.getElementById("txt1").value = text;
document.getElementById("txt2").value = "";
}
else{
document.getElementById("txt2").value = text;
document.getElementById("txt1").value = "";
}
index = index ? false : true;
}
</script>
</head>
<body>
<input type="text" id="txt1"/>
<input type="text" id="txt2"/>
<input type="button" value="Change Text" onclick="DisplayText()"/>
</body>
</html>
source to share
It's not the prettiest / most delicate solution, but it works and you can tailor it to suit your needs.
<script>
var field = 0;
function addText(txt){
if(field === 0) return false;
field.value = txt;
}
</script>
For a shape like
<form>
<input type="text" name="box1" id="box1" onfocus="field=this;" />
<input type="text" name="box2" id="box2" onfocus="field=this;" />
<input type="button" onclick="addText('Hello Thar!');" />
</form>
source to share