Clear input, textarea on blur and default if field is blank - javascript

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!

Related

Autofocus not working ok when elem shows up

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();

Specifiy input targeted blur function

My function works as it should. is there a way to remove the function from a specific input? Because it changes all inputs.. i have 2 check boxes and 1 input that i need to not have this function on.
$('input').blur(function(){
$('input').parent().removeClass("gray");
})
.focus(function() {
$(this).parent().addClass("gray")
});
Try adding a class to the input and checkbox that you don't want the onblur functions, then update the code as below
Add the class to the three inputs that you don't want this feature
$('input').not( ".class" ).blur(function() {
$(this).parent().removeClass("gray");
})
.focus(function() {
$(this).parent().addClass("gray")
});
Hope this helps what you need.
Use this context, $('input') will select all the <input> elements, this in the callback will hold the element on which event is invoked!
$('input').blur(function() {
$(this).parent().removeClass("gray");
})
.focus(function() {
$(this).parent().addClass("gray")
});
.gray {
background: gray;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<div>
<input type="text">
</div>
<div>
<input type="text">
</div>
If you have id's for those three inputs you can use this code snippet.
$('input').blur(function(){
$(this).parent().removeClass("gray");
})
.focus(function() {
$(this).parent().not( "#id1, #id2, #id3" ).addClass("gray")
});
It will add class to those inputs which do not match the selector.

Grey out and make text box read only using jquery

Hi i want to make a text box turn grey and be made read only when a checkbox is ticked. Currently i am able to get the text box to be made read only but will not turn grey. I would usually use the disabled attribute, however i need the value of the text box still to be sent so the disabled attribute can not be used here as it returns a null value.
jQuery(document).ready(function () {
$("#redflag2").click(function () {
$('#new_contracted_support_hours').attr("readonly", $(this).is(":checked"));
$('#new_contracted_support_hours').addclass("greyba", $(this).is(":checked"));
});
});
css
.greyba{
background-color:rgba(178,178,178,1.00);
}
It should be addClass() not addclass() thus class was not added.
You should use .prop() to set properties and toggleClass(),
As of jQuery 1.6, the .prop() method provides a way to explicitly retrieve property values, while .attr() retrieves attributes.
jQuery(document).ready(function () {
$("#redflag2").change(function () {
$('#new_contracted_support_hours')
.prop("readonly", this.checked)
.toggleClass("greyba", this.checked);
});
});
A good read .prop() vs .attr()
jQuery(document).ready(function () {
$("#redflag2").click(function () {
$('#new_contracted_support_hours').attr("readonly", $(this).is(":checked"));
if($(this).is(":checked")){
$('#new_contracted_support_hours').addClass("greyba");
}
});
$("#redflag2").click(function () {
$('#new_contracted_support_hours').attr("readonly", $(this).is(":checked"));
if ($(this).is(":checked")) {
$('#new_contracted_support_hours').addClass("greyba");
}
else{
$('#new_contracted_support_hours').removeClass("greyba");
}
});
.greyba{
background-color:rgba(178,178,178,1.00);
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input id="new_contracted_support_hours" type="text"></input>
<input id="redflag2" type="checkbox"></input>
Why not separate your concerns more clearly, leaving JS for functionality and CSS for styling? As you are usilising the readonly attribute, zero styling intervention is required in your Javascript.
nb. Implementation is indicative only
function setState(){
document.getElementById('field').readOnly = document.getElementById('checkbox').checked;
}
$('#checkbox').on('change', setState); // set state on checkbox change
setState(); // set state on initial load
#field[readonly] {
background: grey;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input id="checkbox" type="checkbox" />
<input id="field" type="text" value="value.." />
<input type="text" id="viewers" name=""/>
You can make readonly by this by using:
$('#viewers').attr('readonly', true);
$('#viewers').css('background-color' , '#DEDEDE');

ASP.NET implementing a search box like stackoverflow search box

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');
}

checkbox property using jquery

i m a beginner.
i want that when a checkbox is checked then it should allow user to write something in a txtbox. initially the txtbox is disabled. what i should write inside the function using jquery
<input type="checkbox" id="cb" />
<label for="cb">label for checkbox</label>
<input type="text" id="txt" disabled="disabled" />
<script type="text/javascript">
$(document).ready(function() {
var checkbox = $('#cb');
var textfield = $('#txt');
checkbox.click(function() {
if (checkbox.is(':checked')) {
textfield.removeAttr('disabled');
}
else {
textfield.attr('disabled', 'disabled');
}
});
});
</script>
working example with visibilty
working example with disabled-state
additionally:
as you are working with asp.net, your assignments should look like, eg:
var checkbox = $('#<%= this.cb.ClientID %>');
you should be aware of the way how the server-controls get rendered either (to choose an appropriate selector).
furthermore: you should also be aware of the fact, that disabled-inputs won't get posted, whereas readonly-inputs are no problem to handle...
$('#mycheckbox').click(function()
{
$("#mytextbox").attr('disabled','');
}
);
$(document).ready(function()
{
//To Disable the Check box on page Load
$('#TextBox').attr('disabled', 'disabled');
//On Click of the Check Box
$('#CheckBoz').click(function()
{
if($('#CheckBoz').is(':checked'))
{
$('#TextBox').removeAttr('disabled');
}
else
{
$('#TextBox').attr('disabled', 'disabled');
}
});
});
I Hope this code works perfectly for you and u jst need to paste it in your page and check the Component name according to it.

Categories

Resources