How to select text on click input box in JavaScript? [duplicate] - javascript

This question already has answers here:
Selecting all text in HTML text input when clicked
(29 answers)
Closed 2 years ago.
I am new to JavaScript and building an application in which, using plain JavaScript, I would like to select the text (similar to right clicking and select all) upon click of an element on a web page if the element is of type input. Can this be done? If so how would I go about doing this. Any info would be appreciated.

You can add this script at the bottom of your body tag
<script>
document.querySelectorAll('.js-select-input').forEach(input => {
input.addEventListener('click', (e) => e.currentTarget.select())
})
</script>
and for every input that you would like to have this autoselect functionality add the class "js-select-input" as in this example:
<input class="js-select-input" value="foo">

Use select method to achieve this.
Use select method in the callback function of input's onfocus event.
For better understanding, see the following example:
function testFunc(focusedInput) {
focusedInput.select();
}
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<input id="test-input" type="text" name="test-input" value="default-value" onfocus="testFunc(this)">
<script>
function testFunc(focusedInput) {
focusedInput.select();
}
</script>
</body>
</html>

Related

onchange javascript wont firing when inside a form tag [duplicate]

This question already has answers here:
Do DOM tree elements with IDs become global properties?
(5 answers)
Why are inline event handler attributes a bad idea in modern semantic HTML?
(3 answers)
Closed 11 months ago.
I got a problem, I want to add onchange javascript on the selection tag. It is working if the selection tag puts without the form tag, but after I put the selection tag inside the form tag it's stop working,
If I put the selection tag without the form tag it would be okay but when I put the selection tag inside the form tag it's not working anymore
<form>
<select id="selection1" onchange="selection1();">
<option value="1.1">1.1</option>
<option value="1.2">1.2</option>
<option value="1.3">1.3</option>
</select>
<input type="text" id="selectionval" />
</form>
<script type="text/javascript">
function selection1() {
var id = document.getElementById("selection1");
var displayedText = id.options[id.selectedIndex].text;
document.getElementById("selectionval").value = displayedText;
}
</script>

How can I get the current text box the user is typing in (Chrome Extension) [duplicate]

This question already has answers here:
How to access the webpage DOM/HTML from an extension popup or background script?
(2 answers)
Closed 2 years ago.
I am teaching myself how to build Chrome Extensions. The first thing I want to build is a simple word predictor that takes in your last few words, predicts the next word, and allows you to autocomplete the word by pressing tab.
The first thing I need to do is figure out how to access the text box the user is currently typing in. For example, Grammarly seems to do this well. I've searched through StackOverflow, but can't seem to find an answer (forgive me, I'm a beginner). Any help would be amazing!
First you need to get permission for your extension to access a user's tabs, as I understand it.
Then you need to access the current tab with chrome.tabs.getCurrent()
Then I think you'll need to do something like let focusedElement = chrome.tabs.getCurrent(() => document.activeElement)
I've developed an extension, but I've never accessed tabs so I'm not entirely sure about the last part. If that doesn't work, let me know!
I think I see what you mean by access now..
Just add this function to your content script and it will attach a event listener too all inputs on the page that returns the current input field.
All it does is uses a for loop to loop through all inputs on the page, then add a click addEventListener to each input, and have it return the current input
<!DOCTYPE html>
<html>
<head>
<title>Test</title>
</head>
<body>
<input type="text" name="text" id="input1" placeholder="Click me">
<input type="text" name="text" id="input2" placeholder="Click me">
<input type="text" name="text" id="input3" placeholder="Click me">
<br><br><br>
<div id="display"></div>
</body>
<script>
function inputs(){
for(let i = 0; i < document.querySelectorAll('input').length; i++){
document.querySelectorAll('input')[i].addEventListener('click', ()=>{
//Get the DOM element of whatever input user clicks on
var currentInput = document.querySelectorAll('input')[i];
console.log(currentInput);
//Just for example purposes
document.getElementById('display').innerText = 'You clicked on input...' + (i+1);
});
}
}
inputs();
</script>
</html>
Now that you have the exact input field the user is typing in.. you should be able to add the predicted words, by setting the input field equal to the current value of it + your predicted text.

Javascript: How to copy content from a <p> element to hidden <input> element? [duplicate]

This question already has answers here:
contenteditable change events
(21 answers)
Closed 7 years ago.
Basically I have a element as is demonstrated here:
<!DOCTYPE html>
<html>
<body>
<p contenteditable="true">This is a paragraph. It is editable. Try to change this text.</p>
</body>
</html>
The user can paste data into that field and therefore change the contents between the tags. The reason to do this is to get the metadata (like hyperlinks, etc.) that would be lost with a simple <textarea> element.
How can you copy this data into an <input type=hidden> element, if the content is changed by the user?
This question is unlike this question where there is no output of the data (a static text is shown, which does not indicate how to access the real data that the User has entered) and the input is of a different type (<div> vs. <p>)
HTML:
<p id="input" contenteditable="true" onKeyup="myFunction()">This is a paragraph. It is editable. Try to change this text.</p>
<input type="text" id="output">
Javascript:
function myFunction() {
document.getElementById("output").value = document.getElementById("input").innerHTML;
}
JSfiddle: http://jsfiddle.net/qw2oveuo/1/
You can combine the input event with the innerHTML to grab the data:
document.querySelector("p").addEventListener("input", function(e) {
document.querySelector("input[type=hidden]").value = e.target.innerHTML;
});
Working Example
This will update the hidden input any time the user changes the content of the p either by keypress or copy/paste.
You can use the jQuery .html() method to get the content of the p tag
<p id="my-contenteditable-p" contenteditable="true">This is a paragraph. It is editable. Try to change this text.</p>
<input type="hidden" id="hidden-in"/>
like
var content = $('#my-contenteditable-p').html();
and after checking if the content is changed by the user, You can use jQuery .val() method to set the value to hidden field.
$("#hidden-in").val(content);
Just add a listener that gets your text and put it somewhere else:
var get = document.getElementById('getcontenthere');
var put = document.getElementById('putcontenthere');
var updateInput = function() {
put.value = get.innerText;
}
get.oninput = updateInput;
updateInput();
<!DOCTYPE html>
<html>
<body>
<p id="getcontenthere" contenteditable="true">This is a paragraph. It is editable. Try to change this text.</p>
<p>This is type=text so you can see it, but it could be hidden as well</p>
<input id="putcontenthere" type="text">
</body>
</html>

Removed DOM element still appears on the page [duplicate]

This question already has answers here:
How to remove an HTML element using Javascript?
(11 answers)
Closed 8 years ago.
I'm trying to add/remove a DOM element (id ="result") dynamically. The addition seems to work fine but after removal the element still appears on the page.
What's happening here? What am I doing wrong?
Here is my code:
<!DOCTYPE html>
<html>
<body>
<script>
function clearResult() {
if (document.getElementById("result") != null){
alert("remove #result");
$("#result").remove();
if (document.getElementById("result") != null) {
alert("#result still exists");
}
}
alert("Exiting clearResult");
}
function search() {
clearResult();
if (document.getElementById("result") == null) {
alert("add #result");
$('<table id="result"><tr>I am a table</tr></table>').appendTo('#ex');
}
}
</script>
<div>
<button id="search" onclick="search()" value="Send">Search</button>
</div>
<div id="ex">
#*Add result table here dynamically*#
</div>
</body>
</html>
Your HTML is invalid. Content within a table needs to be in td tags. Without those, your code is being rendered as:
I am a table
<table id="result"><tr></tr></table>
You can see that then removing the #result element appears to do nothing, because the text does not disappear. If you change your code to include the td elements, it works fine:
$('<table id="result"><tr><td>I am a table</td></tr></table>').appendTo('#ex');
Example fiddle
Note that you can also massively simplify your code. You don't need to check for the existance of an element before removing it in jQuery. Also, you should use jQuerys event handlers, instead of outdated on attributes. Try this:
<div>
<button id="search" value="Send">Search</button>
</div>
<div id="ex"></div>
$('#search').click(function() {
$('#ex').empty().append('<table id="result"><tr><td>I am a table</td></tr></table>');
});
Updated fiddle
I use empty() here on the #ex element to save a selector, it has the same behaviour as remove(), except is performed on the children of an element, not the element itself.

Showing one text box value in another text box while user type the value to the text box

Is there a way to get the value from one text box and add it to another using jQuery dynamically when user is typing the value to the text box? can someone please explain the method if there is any such thing?
regrds,
Rangana
You mean something like http://jsfiddle.net/ZLr9N/?
$('#first').keyup(function(){
$('#second').val(this.value);
});
Its really simple, actually. First we attach a keyup event handler on the first input. This means that whenever somebody types something into the first input, the function inside the keyup() function is called. Then we copy over the value of the first input into the second input, with the val() function. That's it!
$('#textbox1').keypress(function(event) {
$('#textbox2').val($('#textbox1').val() + String.fromCharCode(event.keyCode));
});
This will ensure that textbox2 always matches the value of textbox1.
Note: You can use the keyup event as others have suggested but there will be a slight lag possibly. Test both solutions and this one should 'look' better. Test them both and hold down a key or type real fast and you will notice a significant lag using keyup since keypress triggers before the keyup event even happens.
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN"
"http://www.w3.org/TR/html4/strict.dtd"
>
<html lang="en">
<head>
<title><!-- Insert your title here --></title>
<script type="text/javascript"
src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function() {
$('#from').keyup(function(event) {
$('#to').text($('#from').val());
});
});
</script>
</head>
<body>
<textarea id="from" rows=10 cols=10></textarea>
<textarea id="to" rows=10 cols=10></textarea>
</body>
</html>
$(document).ready(function(){
$("#textbox1").blur(function(){$('#textbox2').val($('#textbox1').val()});
}
Action will perform on blur of textbox1.

Categories

Resources