I'm not getting autofocus on the input when it shows up.
The autofocus property works intermitently on Chrome.
On IE11... well it does not even try to add it.
Do I need to validate the existence of the input element on the DOM before apply the autofocus with jQuery?
HTML5
<input type="text" class="form-control" autofocus placeholder="Filter">
JS
function iboxHistorySearch() {
var header = $('.client-history .ibox-title_replace'),
searchbar = $('.client-history .client-history-searchbar'),
closeBtn = $('.client-history .btn-dismiss');
header.on('click', function (e) {
e.preventDefault();
if (searchbar.hasClass('hidden')) {
searchbar.removeClass('hidden')find('form-control:first').focus();
$(this).addClass('hidden');
}
});
closeBtn.on('click', function (e) {
e.preventDefault();
if (header.hasClass('hidden')) {
header.removeClass('hidden');
searchbar.addClass('hidden');
}
});
}
iboxHistorySearch();
UPDATE
searchbar.removeClass('hidden')find('form-control:first').focus();
From the (unedited) question:
var searchbar = $('.client-history .client-history-searchbar')
if (searchbar.hasClass('hidden')) {
searchbar.removeClass('hidden').focus();
make sure that searchbar is an input control that can receive focus. If not, add a .find to get an input, either the first or a specific element, eg:
searchbar.removeClass('hidden')
.find('.form-control:first')
.focus();
or
searchbar.removeClass('hidden')
.find('input:first')
.focus();
(but with input you may also need to add checkbox/select etc, eg)
searchbar.removeClass('hidden')
.find('input,select,textarea')
.first()
.focus();
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 have a very simple jQuery UI spinner as follows:
<input value="2" class="form-control ui-spinner-input" id="spinner" aria-valuemin="2" aria-valuemax="24" aria-valuenow="2" autocomplete="off" role="spinbutton" type="text">
Using jQuery I set the above text box readonly true/false. The readonly and value is set based on the checkbox a user selects and that function looks like
function checkBoxes() {
var $targetCheckBoxes = $("#BoxFailure,#InstallationFailure");
$targetCheckBoxes.change(function () {
var isChecked = this.checked;
var currentElement = this;
var $radioButton = $('.usage-failure-type-radio');
$targetCheckBoxes.filter(function () {
return this.id !== currentElement.id;
}).prop('disabled', isChecked);
$('#spinner').val(isChecked ? this.value : '').prop('readonly', isChecked);
$radioButton.first().prop('checked', isChecked);
$radioButton.not(':checked').toggle(!isChecked).parent('label').toggle(!isChecked);
$('.usage-before-failure > div > span.ui-spinner > a').toggle(!isChecked);
});
}
Now what I'm trying to achieve is when the #spinner input is readonly and if the user presses the back space I want to prevent the default behaviour e.g. do navigate away from the page. For this I thought I'd do the following:
$('.prevent-default').keydown(function (e) {
e.preventDefault();
});
Which works fine if the input has the class prevent-default on page load. However, if I add it in my checkBoxes function in the following line
$('#spinner').val(isChecked ? this.value : '').prop('readonly', isChecked).toggleClass('prevent-default')
Then I press the backspace it ignores e.prevenDefault();
But if I do
$('#spinner').val(isChecked ? this.value : '').prop('readonly', isChecked).keydown(function (e) { e.preventDefault(); });
Then it works absolutely fine.
Can someone tell me why this is happening please.
The reason I want to use a separate function with a class name is because I have various inputs which get set to read only based on different check/radio values.
Can someone tell me why this is happening please
This is because of the DOM parser and the timing when JavaScript is executed.
If you already have an element with a class prevent-default in your DOM before JS is executed, then the JavaScript will recognise and handle it correctly. If you instead add the class afterwards with JS, then you have to re-initialise the keydown-event again to make it work.
To re-initialise you will need something like this:
function checkBoxes() {
var $targetCheckBoxes = $("#BoxFailure,#InstallationFailure");
$targetCheckBoxes.change(function () {
...
$('#spinner').val(isChecked ? this.value : '').prop('readonly', isChecked).toggleClass('prevent-default');
// assign new keydown events
handleKeyDown();
...
});
}
function handleKeyDown() {
// release all keydown events
$('#spinner').off( "keydown", "**" );
$('.prevent-default').keydown(function (e) {
e.preventDefault();
// do more stuff...
});
}
I am trying to clear two input fields with classes assigned, and one textarea with a class assigned of their default values on blur and return it to default only if the field is blank when the field is exited. If the user has included their own text I require that to stay.
This is what I have thus far:
$("input, textarea").focus(function() {
this.value = "";
});
$(".namefield").on("blur", function() {
$(this).val("Name");
});
$(".emailfield").on("blur", function() {
$(this).val("Email");
});
$(".messagefield").on("blur", function() {
$(this).val("Message");
});
First a quick note, the HTML placeholder attribute will do exactly what you describe natively. I'd encourage that as a first choice if possible. The implementation would simply be:
<input type="text" class="namefield" placeholder="Name" />
More reading on it is here: http://www.w3schools.com/tags/att_input_placeholder.asp
If you can't add attributes to the elements, but you have the value set, you can add the attributes dynamically using jQuery. You could use the jQuery method we talked about originally, or you could just add the placeholder attribute.
Here are both examples, I've also updated the JS Fiddle with a working example.
Using Placeholder
$(document).ready(function() {
$("input, textarea").each(function() {
$(this).attr('placeholder',$(this).val());
$(this).val('');
})
})
Using data-default in conjunction with the original answer
$(document).ready(function() {
$("input, textarea").each(function() {
$(this).data('default',$(this).val());
})
})
Original Answer:
If you still need to use jQuery, you can set and check the state and compare it against a default value. Something like this would work:
HTML
<input type="text" class="namefield" data-default="Name" value="Name" />
<input type="text" class="emailfield" data-default="Email" value="Email" />
JavaScript
$(document).ready(function() {
$("input, textarea").focus(function() {
if($(this).data('default') == $(this).val()) {
$(this).val('');
}
});
$("input, textarea").blur(function() {
if($(this).val() == '') {
$(this).val($(this).data('default'));
}
});
})
You can see it working in this JS Fiddle: https://jsfiddle.net/77Lk4kep/1/
Hope that helps!
Update
It appears that the input is locked until I input a well formatted email address and then and only then is the element able to be unlock/unfocus. That is just weird, because if I can't focus any other element then how can the unfocus event get trigger when the current element is still focus. Do you suppose it has to do with something on the server side then?
So I have this piece of code that has an input html generated by the server so I can not directly do the onblur=function() in the tag. Instead I use the onclick event of the td to bind an event handler to the input.
<td id="emailInput" class="label" onclick="emailValidation(event);">
#Html.EditorFor(model => Model.EmailAddress, new { Class = "ignore"})
</td>
<td id="emailValidate" style="display: none">
<label>Please enter a valid email address</label>
</td>
in the Javascript file I bind the event handler like so:
function emailValidation(e) {
$(e.target).on("blur", function () {
console.log("what target e is");
console.log(e.target);
var inputVal = $(e.target).val();
var re = /[A-z0-9]*[\.?[\w+]+[A-z0-9]+#[A-z0-9][\.?[\w+]+\.[A-z][A-z][A-z]/;
if (!re.test(inputVal)) {
$(e.target).focus();
$("#emailValidate").css("display", "inline-block");
} else {
$("#emailValidate").css("display", "none");
}
});
}
I check the dev console and e.target is the input element I want. What is happening is that the onblur event in being trigger after it has been appended and the input is unfocus even though the input element is no longer focus, and I am just clicking random area in the screen. Am I mis-understanding something? Is there a better definition that I can get than the w3school, the developer.mozilla, and this weird one
EDIT
I was trying to create a JSfiddle (w/o server stuff) to demonstrate and it worked fine so upon closer inspection I see the the input element is not being unfocus. It does not matter where I click the cursor remains in the text area, and no other element can be focus now.
Edit 2
As requested the JSFiddle, but it works here but not on the one with server side stuff
Here is a working fiddle:
http://jsfiddle.net/Mn5E4/1/
$("#emailMe").on("blur", function () {
var inputVal = $(this).val();
var re = /[A-z0-9]*[\.?[\w+]+[A-z0-9]+#[A-z0-9][\.?[\w+]+\.[A-z][A-z][A-z]/;
if (!re.test(inputVal)) {
$("#emailMe").focus();
$("#emailValidate").css("display", "inline-block");
} else {
$("#emailValidate").css("display", "none");
}
});
You don't need to bother with using the click event to attach the handler since you know the id of the input you want to bind to.
Edit: Note that this is a fork of your jsFiddle. Based on the code in your question, I would expect the id of the desired input element to be "EmailAddress", in which case you would replace $("#emailMe") with $("#EmailAddress").
Edit2: You can take out any guesswork by doing this:
<td id="emailInput" class="label">
#Html.EditorFor(model => Model.EmailAddress, new { #class = "ignore validateEmail"})
</td>
<td id="emailValidate" style="display: none">
<label>Please enter a valid email address</label>
</td>
<script type='text/javascript'>
$(".validateEmail").on("blur", function () {
var inputVal = $(this).val();
var re = /[A-z0-9]*[\.?[\w+]+[A-z0-9]+#[A-z0-9][\.?[\w+]+\.[A-z][A-z][A-z]/;
if (!re.test(inputVal)) {
$(".validateEmail").focus();
$("#emailValidate").css("display", "inline-block");
} else {
$("#emailValidate").css("display", "none");
}
});
</script>
Note that I passed another class into the EditorFor helper and changed how the class attribute was named to use # to escape the lower case name "class".
Please try this aproach:
<td id="emailInput" class="label" onclick="emailValidation(event);">
#Html.EditorFor(model => Model.EmailAddress, new { Class = "ignore"})
</td>
$("#emailInput").on('focusin', "input", function (e) {
var inputobj = $(this);
var inputVal = inputobj.val();
var re = /[A-z0-9]*[\.?[\w+]+[A-z0-9]+#[A-z0-9][\.?[\w+]+\.[A-z][A-z][A-z]/;
if (!re.test(inputVal)) {
inputobj.focus();
$("#emailValidate").css("display", "inline-block");
} else {
$("#emailValidate").css("display", "none");
}
})
Note: Not tested
You should use $(this)
var inputVal = $(this).val();
I use VS2010,C# to develop an ASP.NET web app, I'm going to implement a search box like the one used in Stackoverflow (or other sites), initially there is a phrase (for instance "search") in the search text box, when user click in text box, its text is emptied and user can type his phrase, but if he leaves the text box (lost focus) empty, again the phrase "search" is displayed, how can I implement this nice effect?
thanks
This is the textbox watermark plugin which I use:
http://code.google.com/p/jquery-watermark/
I then created the following code which uses the title attribute for the watermark text for all elements with the .textbox_watermark class
var Textbox_Watermark =
{
init: function () {
var textboxWatermarks = $(".textbox_watermark");
for (var i = 0, ii = textboxWatermarks.length; i < ii; i++) {
$(textboxWatermarks[i]).watermark(textboxWatermarks[i].title);
}
}
}
Textbox_Watermark.init();
Then when focus is on the textbox, the watermark is removed.
You will need the jQuery framework for this to work
Here is a little script I use for just this purpose. It does required JQuery though, but if that is an option for you then give it a try. (there is probably a javascript alternative for this too, but I dont know it)
function addInputBlur(selector, text) {
var element = $(selector);
element.blur(function () {
if ($(this).val() == "") {
$(this).val(text);
$(this).addClass("InputBlur");
}
else {
$(this).removeClass("InputBlur");
}
});
element.focus(function () {
if ($(this).val() == text) {
$(this).removeClass("InputBlur");
$(this).val("");
}
});
element.blur();
}
Note: the "selector" param should be a JQuery selector value (i.e. "#MyTextbox")
Also, the "InputBlur" CSS class is just the style I use for the grey/italic font
I have seen the view source for stack overflow and what i notice is that they have a attribute named placeholder
<div id="hsearch">
<form id="search" action="/search" method="get" autocomplete="off">
<div>
<input autocomplete="off" name="q" class="textbox" **placeholder="search"** tabindex="1" type="text" maxlength="140" size="28" value="">
</div>
</form>
</div>
try this it works for mozilla ,, check for others
hope it helps
<input type="text"
onblur="javascript:if(this.value=='') this.value= this.defaultValue;"
onfocus="javascript:if(this.value==this.defaultValue) this.value='';"
id="txtSearch"
value="search"
name="txtSearch" />
You can do this in JavaScript using a function similar to this one:
/*
* applyDefaultValue() - Takes a DOM object and it's string value as paramters, when the element
* is focussed, the 'value' is blanked out, ready for user entry. When the item is blurred, if nothing was typed
* then the original value is restored.
*/
function applyDefaultValue(elem, val) {
elem.value = val;
elem.onfocus = function() {
if (this.value === val) {
this.value = ''; //On focus, make blank
}
}
elem.onblur = function() {
if (this.value === '') {
this.value = val; //If it's not in focus, use declared value
}
}
}
You can then apply this to items like this:
/*
* Onload function to set the default 'email address'/'search' value and blank out the password field
*/
window.onload = function() {
applyDefaultValue(document.getElementById('email'), 'Email Address');
}