How to give autofocus to a element when another element has it? - javascript

I am trying to give a textarea (which is added when you click on a button) autofocus with the autofocus attribute, but when I do that it doesn't works and I get this message on the console:
Autofocus processing was blocked because a document already has a focused element.
So now the question is:
How can I get the focus to the textarea when some other element already has it?

Giving autofocus to a textarea is basically saying "When the page loads, this textarea should be focused"
So focusing another element isn't a problem:
If that error is occurring, just use the .blur() method on the textarea you want to lose focus on. Then do the .focus() method on the one you want focused
function focus1() {
document.getElementById('ele1').focus()
}
function focus2() {
document.getElementById('ele2').focus()
}
<textarea id="ele1"></textarea>
<textarea id="ele2"></textarea>
<button onclick="focus1()">Click to focus inp1</button>
<button onclick="focus2()">Click to focus inp2</button>

After adding the textarea control then set focus to that control.
I thing this will solve your problem.
On button click call addTextArea() function.
<script type="text/javascript">
var cntctrl = 0;
function addTextArea() {
try {
var s = document.createElement('textarea');
cntctrl = cntctrl + 1;
var id = 'txtarea' + cntctrl;
s.setAttribute('id', id);
s.setAttribute('class', "txtareaclass");
s.setAttribute('rows', "4");
s.setAttribute('cols', "100");
document.body.appendChild(s);
document.getElementById(id).focus();
}
catch (e) {
console.log('Adding Textarea failed!.');
console.log('Error: ' + e);
}
return false;
}
</script>

Related

HTML tag placeholder using JS

For the following HTML input tag:
<input id="search_bar" type="text" placeholder="search...">
I replace placeholder value with empty content using JS as below:
document.getElementById("search_bar").addEventListener("click", function(){
document.getElementById("search_bar").placeholder = "";
});
However, I am not able to revert the change back when clicking else where outside input tag. how can I replace the original placeholder value "search..." as it was before??
Use the blur event.
As a plus, my solution queries the DOM only once, and handling the focus event rather than click also hides the placeholder if you tab into the field:
var txt = document.getElementById("search_bar")
txt.addEventListener("focus", function(){
this.placeholder = "";
});
txt.addEventListener("blur", function(){
this.placeholder = "search...";
});
Change the event from click to focus
document.getElementById("search_bar").addEventListener("focus", function(){
document.getElementById("search_bar").placeholder = "";
});
Then set it back on blur event
document.getElementById("search_bar").addEventListener("blur", function(){
document.getElementById("search_bar").placeholder = "Search...";
});
However, I don't think this is necessary because by default, the placeholder is removed when user starts typing
Personally with something this basic I would just add another event listener for the "blur event" as such:
<input id="search_bar" type="text" placeholder="search..." >
document.getElementById("search_bar").addEventListener("click", function(){
document.getElementById("search_bar").placeholder = "";
});
document.getElementById("search_bar").addEventListener("blur", function(){
document.getElementById("search_bar").placeholder = "search...";
});
That did the trick for me when trying it out in a Codepen.

DOM equivalent to jQuery `.detach()`?

I’m trying to remove an input field by clicking an “X button”. After it is removed it will not post its value when the form is submitted. A “+ button” appears that allows the user to add said input again. The input has an onclick event that opens a calendar and after reattaching, the calendar does not open on click anymore. I can’t use jQuery.
adderBtn.onclick = function (e) {
var elem = that.hiddenElems.shift();
that.collectionItemContainer.append(elem);
}
removerBtn.onclick = function (e) {
collectionItemElem.remove();
that.hiddenElems.push(collectionItemElem);
}
The question is how do I remove and reattach DOM nodes without losing the Events.
When you remove an element, as long as you keep a reference to it, you can put it back. So:
var input = /*...code to get the input element*/;
input.parentNode.removeChild(input); // Or on modern browsers: `input.remove();`
later if you want to put it back
someParentElement.appendChild(input);
Unlike jQuery, the DOM doesn't distinguish between "remove" and "detach" — the DOM operation is always the equivalent of "detach," meaning if you add the element back, it still has its handlers:
Live Example:
var input = document.querySelector("input[type=text]");
input.addEventListener("input", function() {
console.log("input event: " + this.value);
});
input.focus();
var parent = input.parentNode;
document.querySelector("input[type=button]").addEventListener("click", function() {
if (input.parentNode) {
// Remove it
parent.removeChild(input);
} else {
// Put it back
parent.appendChild(input);
}
});
<form>
<div>
Type in the input to see events from it
</div>
<label>
Input:
<input type="text">
</label>
<div>
<input type="button" value="Toggle Field">
</div>
</form>
If you remove the element without keeping any reference to it, it is eligible for garbage collection, as are any handlers attached to it (provided nothing else refers to them, and ignoring some historic IE bugs in that regard...).
To detach an element in function form:
function detatch(elem) {
return elem.parentElement.removeChild(elem);
}
This will return the 'detached' element

Toggle focus onclick of a button

I have a form inside a panel. The panel opens and closes when a button is clicked. When the panel is opened [i.e., with the click of the button], I want to focus on the first input text box in the form which is inside the panel. When I close the panel [i.e., again clicking on the same button], I want to loose the focus from that input box.
So, in simple words, I want to toggle the focus on the text input box when the onclick event happens on the button.
I gave the input text box an id and did the following:
<input type="text" id="code" placeholder="enter code">
Inside the script tag:
$('.button-element').click(function(){ $('#code').focus();});
This makes the focus on the input text box but I want to remove the focus when I click the button again.
Please help me with this.
Thank you.
You could use this snippet (tested on chrome):
var $code = $('#code');
$('.button-element').on('mousedown', function () {
$(this).data('inputFocused', $code.is(":focus"));
}).click(function () {
if ($(this).data('inputFocused')) {
$code.blur();
} else {
$code.focus();
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<input type="text" id="code" placeholder="enter code">
<button class="button-element">btn</button>
I know this is a very late answer, but here is a solution which adds a new jQuery method.
You can add this to top of your $.onready:
jQuery.fn.toggleFocus = function(){
if (this.is(":focus")) {
this.blur();
} else {
this.focus();
}
}
Usage:
$(".button-element").toggleFocus()
Try this:
var code = $('#code');
$('.button-element').click(function() {
if(code.is(":focus")) {
code.blur();
} else {
code.focus();
}
});
You can update your code to following
var focusInput = true;
$('.button-element').click(function(){
if(focusInput) {
$('#code').focus();
} else {
$('#code').blur();
}
focusInput = !focusInput;
});
Since you have not given any HTML,you need to change the code according to your need.
$('.button-element').click(function()
{
if($("#ID-of-panel").is(':visible'))
$('#code').blur();
else
$('#code').focus();
});

How to not clear textarea value when searching with Javascript onsearch Event

I'm using this method http://www.w3schools.com/jsref/event_onsearch.asp
What I want is the text that I searched with to stay in the textarea or at least get back to the textarea, not disappear because I click the enter button.
I understand that it clears the text because in the link they describe the function like this: "The onsearch event occurs when a user presses the "ENTER" key or clicks the "x" button in an element with type="search".
So it acts as if I click the x button, although, there must be a way to get the text back there after?
This is my current code html code
<form> <input type="search" name="search" id="searchid" onsearch="OnSearch(this)"/> </form>
This is my javasript/jquery
function OnSearch(input) {
alert("The current value of the search field is " + input.value);
$("#searchid").val(input.value);
}
What happens now is that it correctly alerts the value the textarea is holding, although it wont add back the textarea value.
EDIT: It seems like the page reloads, how can i insert code that runs after page reload?
Well I have an alternative. Since you cannot avoid the clear functionality you can store the text each time keypressed in a global variable and if x is pressed retain the value in textbox. Below is the code:
DEMO HERE
var text="";
function OnSearch(input) {
if(input.value == "") {
$("#searchid").val(text);
}
else {
alert("You searched for " + input.value);
}
}
$(document).on('keyup','#searchid', function (e) {
text=$(this).val();
console.log(text);
});
UPDATE
if your html is inside the form you can do as below:
Check in document.ready if it already had a text and if yes set it!!
$(document).ready(function()
{
if(localStorage.getItem("text")!="")
{
$("#searchid").val(localStorage.getItem("text"));
}
});
function OnSearch(input) {
if(input.value == "") {
$("#searchid").val(localStorage.getItem("text"));
}
else {
alert("You searched for " + input.value);
}
}
$(document).on('keyup','#searchid', function (e) {
localStorage.setItem("text",$(this).val());
});
I think this will help you to display the alert dialog symbol as that:
HTML:
<input type="search" name="search" id="searchid"/>
Javascript:
document.getElementById("searchid").onsearch = function() {yourfunctionname()};
/* Put this before the below function or in the top of the document */
function yourfunctionname(){
var x = document.getElementById("searchid").value;
alert("The current value of the search field is "+x);
/* Or do what ever you wish */
}
/*Remember to replace the yourfunctionname with your function's name */
OR If it is in a form try this:
Your form should look like this:
<form method="/* method */" action="/* action */" onSubmit="yourfunctionname()">
<input type="search" name="search" id="searchid"/>
/* Rest of your form*/
</form>
Javascript:
document.getElementById("searchid").value = localStorage.getItem("saved");
document.getElementById("searchid").onsearch = function() {yourfunctionname()};
/* Put this before the below function or in the top of the document */
function yourfunctionname(){
var x = document.getElementById("searchid").value;
alert("The current value of the search field is "+x);
/* Or do what ever you wish */
/* The below code does the trick*/
localStorage.setItem("saved", x);
location.reload();
return false;
}
/* Remember to replace the yourfunctionname with your function's name */
If you are having a different function to submit the form then replace your form's onsubmit attribute with that function's name and a word "return" before it's name and add the below javascript inside that function.
var x = document.getElementById("searchid").value
localStorage.setItem("saved", x);
location.reload();
return false;
If you wanted something else then please comment.
Please accept as if it solves your problem.
And thanks...
Lastly for more just comment

Javascript: select the text in the currently focussed input field

I would like to select the text of the input field which currently has focus, so when the user starts typing, the text which is currently in the input field is gone. Can I do this with javascript (or jquery)?
In case the field which currently has focus is not an input field, nothing has to happen.
thanks!
EDIT:
To all the answerers: you all misunderstood (so probably my question was not clear).
I don't want to select the text on the moment the input field gets the focus. I would like to have a javascript function which selects the text of the input field which has the focus at that moment.
Sorry I misunderstood what you were looking for I think that I have a better understanding of it now. Does this do more of what you were looking to acheive?
//If not using 1.7 for jquery you can use bind
$('input, textarea').on({
focusin: function(){
$(this).addClass("focused");
},
focusout: function(){
$(this).removeClass("focused");
}
});
function highlightText()
{
var focused = $('input.focused,textarea.focused');
if (focused.size()) {
focused.get(0).select();
}
}
http://jsfiddle.net/GXFpR/1/
This should work:
<html>
<head>
</head>
<body>
<input type="text" id="theTextBox" onfocus="selectText()" value="some value"></input>
<script type="text/javascript">
function selectText() {
document.getElementById("theTextBox").select();
};
</script>
</body>
</html>
You can check with onfocus and then use this.select() as inline
<input name="" type="text" value="test test" onfocus="this.select()" />
UPDATE: a more universal approach, will add focus to inputs of the text type also input text's that are not readonly
window.onload = setFocus();
or call beneth the last form input field
setFocus();
main
setFocus = function(){
var i = [];
i = document.getElementsByTagName("input");
for(var t=0; t < i.length; t++){
if(i.item(t).type == "text" && i.item(t).readOnly == false){
i.item(t).onfocus = function (){this.select()};
}
}
}
You can try something like this? http://jsfiddle.net/z55UZ/
$("input, textarea").focus(
function()
{
this.select();
}
)
EDIT:
here is an updated fiddle: http://jsfiddle.net/IrvinDominin/z55UZ/2/
In the example is selected the last focused element; but if you look at the code the var childInputHasFocus and whoHasFocus are never setted to false...when you want to stop the selecting feature?
Where you wanna call the function? Because the click event sets the active/focused element as is caller.

Categories

Resources