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.
Related
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>
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
I have a input field type="hidden" which is changed by javascript itself.
When this field changes i want an event/function to be triggered.
Tried this:
$(".product_id").on("change paste keyup input", function(event){alert('1');});
$(".product_id").blur(function(event){alert('1');});
$(".product_id").keypress(function(event){alert('1');});
But it does not seem to work as the value is changed by other JavaScript file itself.
I cannot change or add to the existing JavaScript.
I cannot add anything to the input field.
You can use jQuery's trigger method & change event.
Changes in value to hidden elements don't automatically fire the .change() event. So, as soon as you change the hidden inputs, you should tell jQuery to trigger it using .trigger('change') method.
You can do it like this:
$(function() {
$("#field").on('change', function(e) {
alert('hidden field changed!');
});
$("#btn").on('click', function(e) {
$("#field").val('hello!').trigger('change');
console.log('Hidden Filed Value: ' + $('#field').val());
});
console.log('Hidden Filed Value: ' + $('#field').val());
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input id="field" type="hidden" name="name">
<button id="btn">
Change Hidden Field Value
</button>
Hope this helps!
It's just a hack if you can't trigger change event from sources.
May not be a good solution with setInterval(). But helps in the cases where you can't trigger change event from sources which are changing the hidden input value.
$("#input")[0].oninput = function(){
$("#hidden").val($(this).val()); //setting hidden value
}
var oldVal = $("#hidden").val();
setInterval(function(){ //listening for changes
var newVal = $("#hidden").val();
if(newVal !== oldVal){
console.log(newVal);
oldVal = newVal;
}
}, 1000);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="hidden" id="hidden">
<input type="text" id="input">
var element = $(".product_id");
element.on("change", function(){
alert('hey');
}).triggerHandler('change');
and we need to trigger it programmatically like:
$('.product_id').val('abcd').triggerHandler('change');
I am trying to build a jQuery function that creates seven input fields when a button is clicked. This should be allowed only once, and not every time the button is pressed.
At the moment I have the below code that creates one text field, but the problem is that every time the button is pressed more text fields are added. By creating these text fields I can use them to add records in my database. For example by clicking the addbutton, the text fields will be created and the user could enter the information.
$("#addbutton").bind("click", function() {
var textarea = $('<input type="text" name="firstname">',);
$('#textfields').append(textarea);
});
Thanks
You can fire the event handler only once with one(), and just append the buttons you want, I'm using an array of names and $.map to create them
$("#addbutton").one("click", function() {
var buttons = [
'firstname',
'lastname',
..... etc
];
$('#textfields').append(
$.map(buttons, function(_name) {
return $('<input />', { name : _name })
})
);
});
FIDDLE
According to our chat in your comments, you want a button that:
On click, it creates seven input fields and appends them to your #textfields element.
After the fields are created, the button is not allowed to create any more input fields.
I devised the following solution based upon this interpretation:
$("#addbutton").click(function(){
for(var i = 0; i < 7; ++i){
$('#textfields').append('<input type="text" name="firstname">');
}
$(this).prop("disabled", true);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button id="addbutton">Click Me</button>
<div id="textfields"></div>
Long story short, the button is disabled after the first click. This prevents you or anyone from doing anything else with the button.
Alternatively you could create a global variable which will act as a flag, to help prevent further input fields from being created, by wrapping the input creation code with an if statement like so:
var inputFieldsCreated = false;
$("#addbutton").click(function(){
if(inputFieldsCreated === false){
for(var i = 0; i < 7; ++i){
$('#textfields').append('<input type="text" name="firstname">');
}
inputFieldsCreated = true;
}
});
Let me know if this does the job for you in the comments below.
Just because I don't like using JQuery for such easy/simple/short thing, here's the code with pure JavaScript :
document.getElementById("btn").addEventListener("click", onClick, false);
function onClick() {
var textfield, br;
for(var i=0 ; i<7 ; i++) {
textfield = document.createElement("input");
br = document.createElement("br");
textfield.id = "txt_"+i;
document.getElementById("textFields").appendChild(textfield);
document.getElementById("textFields").appendChild(br);
}
this.parentElement.removeChild(this);
}
cou can test it here :
https://jsfiddle.net/v91v7afa/
Of course, instead of deleting the button, you can disable it, but it would be really easy to re-enable it. Or you can remove the listener.
var numText=1;
$("#addbutton").on("click",function(e){
e.preventDefault();
numText++;
$('#textfields').append('<input type="text" name="firstname" />');
if (numText==7)
$(this).off('click')
});
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.