Replace class on clicking outside div - javascript

I have some javascript which essentially removes a class which has a background image on focus, i.e clicking in the input box (which has the background image).
The code is as follows:
$(function(){
$("#ets_gp_height").focus(function(){
if(!$(this).hasClass("minbox")) {
} else {
$(this).removeClass("minbox");
}
});
});
This works well, and removes .minbox when the user clicks within the input field, however what i want to do is if the user makes no changes to the input field, it should add the class back in as per at the beginning. At the moment, once the user clicks once, the class is gone for good, i would like it to come back if the user makes no changes to the input box, so for example clicks the input field but then clicks back out again without entering anything.
Any help? Possible?

I'm assuming you don't want the class .minBox to be added if the user has entered a value, but only if they decided not to enter anything, or chose to erase what they had entered.
To do this, you can use the blur event and check if there's anything entered:
$("#ets_gp_height").blur(function()=> {
if($(this).val().length < 1) $(this).addClass('minBox');
});
This will work for TABing out of the input and CLICKing out of it.

$(document).on("blur", "#ets_gp_height", function(){
if($(this).val() == '') {
$(this).addClass('minBox');
}
});
This code will add class 'minBox' when ever user goes out of input field without entering any value.

A working example, with and without jQuery:
Note: with onblur solution, method is called each time the field is blured, even when the value hasn't changed. with onchange solution, method is called only when the value has changed. That why onchange is a better solution.
WITHOUT JQUERY
function onChange(input){
input.value.length > 0 || setClassName(input, 'minbox') ;
}
function onFocus(input){
if(input.className == 'minbox')
{
input.className = '' ;
}
}
function setClassName(o, c){ o.className = c; }
input.minbox {background-color:red;}
<input type="text" id="ets_gp_height" class="minbox" onchange="onChange(this)" onfocus="onFocus(this)">
WITH JQUERY:
$(function(){
$("#ets_gp_height").change(function(){
$(this).val().length > 0 || $(this).addClass("minbox");
})
$("#ets_gp_height").focus(function(){
if(!$(this).hasClass("minbox")) {
} else {
$(this).removeClass("minbox");
}
});
});
input.minbox {background-color:red;}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" id="ets_gp_height" class="minbox">

Related

Check if textbox goes empty after having a value without submitting form or pressing outside of the textbox

I have a currency exchange in my backend, I post data from my textbox to the currency exchange using ajax and view the exchanged value in a label, which is otherwise hidden.
The problem is, if I enter a value in the textbox, and then erase the value from the textbox, the latest value is still there ( I want to hide the label again when the textbox is empty )
This is the code I've tried so far:
$('#transferAmount').on('change',function () {
var amount = $('#transferAmount').val();
if (amount.length < 1 || amount === ""){
$('#amountExchangedHidden').hide();
}
});
I've tried with "on-input" aswell, but it didn't work. Does anyone have a good solution to this?
Use input event instead of change event as change event handler will only be invoked once focus in the input field is lost.
The DOM input event is fired synchronously when the value of an <input> or <textarea> element is changed.
$('#transferAmount').on('input', function() {
var amount = $(this).val();
$('#amountExchangedHidden').toggle(!!amount.length);
}).trigger('input'); //`.trigger` to invoke the handler initially
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<input type="text" id='transferAmount'>
<input type="text" id='amountExchangedHidden'>
Use blur Event instead of Change
$(function) {
$('#transferAmount').on('blur',function () {
var amount = $('#transferAmount').val();
if (amount.length < 1 || amount === ""){
$('#amountExchangedHidden').hide();}
});
});

onBlur event on composed component (input + Button)

I am trying to make a "composed component" which consists of an input field and a button.
I have the following jsfiddle as example:
http://jsfiddle.net/stt0waj0/
<div id="myComponent">
<input type="text" onBlur="this.style.border='1px solid red';">
<button type="button" onClick="alert('Hello World');">ClickMe</button>
</div>
The behavior I want is that when I leave the input field without writing any content, I get a validation error (red border in this case). This already works in the fiddle (content validation is not the scope of the question).
However, when I leave the input field by pressing the button, I will open a dialog which allows to select values for the input field, so in that case, I don't want the validation to run.
So, the concrete question about the fiddle: Can I click the input field, and then click the button and not have a red border? But, if I click the input field, and then click somewhere else, I want the red border (any onBlur except when button was clicked).
Is this possible without dirty tricks?
Things I want to avoid:
Set a timer on the first event to wait for the second (Reason: performance)
Make the onClick event always reset the red border on the text field (Reason: gui glitches)
Just to make it clear on what I'm looking for and why this question is interesting: the onBlur event is fired before the onClick event. However, I normally would need the onBlur to know that the onClick comes next, which is not possible. That's the point of the question.
Imagine a date picker which validates on empty field, when the field has focus and you press the calendar, you will get a validation error even though you're selecting a date. I want to know if there is an elegant way to handle such cases.
To make this work, you can postpone your validation function if user pressed the button.
Below is sample code and fiddle to show what i mean.
* Updated the fiddle to use select dropdown instead of a button *
Fiddle Demo
input.error {color: red; border: 1px solid red;}
<div id="myComponent">
<input id="btn" type="text" onBlur="inputBlur()">
<select type="button" data-btn="btn" onclick="inputButtonClick()" onchange="selectChange()" onblur="selectBlur()">
<option value="">choose</option>
<option value="item1">item1</option>
<option value="item2">item2</option>
<option value="item3">item3</option>
</select>
</div>
window.validate = function(input) {
//do your validation
var val;
console.log("Validating");
val = input.val();
if ( !val || !val.length) {
input.addClass("error");
console.log("Something is invalid");
} else {
//all good
console.log("All valid");
}
//clear error after x time to retry
setTimeout(function() {
$(".error").removeClass("error");
$("input").removeAttr("data-btn-active") ;
}, 3000);
}
window.selectBlur = function() {
var input = $("#" + $(event.target).attr("data-btn"));
validate(input);
}
window.selectChange = function() {
var input = $("#" + $(event.target).attr("data-btn"));
console.log("change", $(event.target).val() );
input.val( $(event.target).val() );
validate(input);
}
window.inputButtonClick = function() {
var input = $("#" + $(event.target).attr("data-btn"));
input.attr("data-btn-active", "true");
console.log("inputButtonClick",input );
}
window.inputBlur = function() {
var input = $(event.target);
//give a bit of time for user to click on the button
setTimeout(function() {
if (!input.attr("data-btn-active" ) ) {validate(input);}
}, 100);
}
$(document).ready(function() {
});

stop input clearing onFocus

I have this auto-suggestion application for emails. it all works well, except when I click outside the input field and then click back in it clears what was there 'onFocus'. any Ideas how I can stop this from happening?
function suggest(inputString){
if(inputString.length == 0) {
$('#suggestions').fadeOut();
} else {
$('#email').addClass('load');
$.post("auto.php", {queryString: ""+inputString+""}, function(data){
if(data.length >0) {
$('#suggestions').fadeIn();
$('#suggestionsList').html(data);
$('#email').removeClass('load');
}
});
}
}
function fill(thisValue) {
$('#email').val(thisValue);
setTimeout("$('#suggestions').fadeOut();", 600);
}
<input type="text" id="email" onKeyUp="suggest(this.value);" onClick="fill();" />
The onClick="fill();" call on your element is executing fill(undefined) whenever you click on the input box.
The first thing this does is sets the value of the input box to thisValue (currently holding undefined) which would effectively erase your input box.
This has nothing to do with focus, try clicking the box, entering a value then clicking on the box again, it'll likely wipe the value too without clicking off first.
For what it's worth, you're probably over-complicating this. I imagine the requirement for the clearing of the box is to remove placeholder text. If you're designing for a remotely new browser use the HTML5 placeholder="E-Mail" to have the browser display that in a lighter text (or whatever) when the user hasn't entered anything.
If you have to support older browsers there's ways around this too, this is a simple but not perfect way (you can generalize this and make a jQuery plugin or go find one out there that exists already too):
HTML:
<input type="text" id="email" class="placeholder" value="E-Mail" />
CSS:
.placeholder { color: #ccc; }
Javascript:
;(function($) {
$(document).ready(function() {
$("#email").on('focus', function() {
var $this = $(this);
if ($this.hasClass('placeholder')) {
$this.removeClass('placeholder');
$this.val('');
}
});
$("#email").on('keyUp', function() {
// this is where your key-up code goes
});
});
})(jQuery);

Clearing a text input (if it's empty) when another text box is clicked - jQuery

I have an email text box that contains the text '(Not Required)' until a user clicks on it, at which point it turns blank. I'm trying to make it to where if the user clicks another text box without entering an email address (or entering anything), the text box will revert to containing (Not Required).
Here's what I have:
$(document).ready(function () {
$('#email').val("(Not Required)");
// this part works fine
$('#email').click(function(){
if ($(this).val() == '(Not Required)'){
$(this).val('');
}
});
// this isn't working
$(':text').click(function(){
var em = $('#email').val().length();
if (em<3){
$('#email').val('(Not Required)');
}
});
});
I can't figure out why the second part isn't working correctly. Any help would be rewarded with a lifetime's devotion to yourself from myself in a very big way. Forever.
var em = $('#email').text().length();
Should be
var em = $('#email').val().length;
And I show you a better way do this by chain method:
$(document).ready(function () {
$('#email').val("(Not Required)").foucs(function() {
$(this).val('');
}).blur(function() {
if ($(this).val().length < 3 ){
$(this).val('(Not Required)');
}
});
});
You have to use $('#email').val().length instead of $('#email').text().length()
Change
$('#email').text().length();
to
$('#email').val().length;
And just a suggestion, why not use the blur() event of the email input to return the 'Not Required' text instead of waiting for a click on another input box?
click isn't the event you should catch. focus is the one to go. never forget keyboard navigation.
Don't query the DOM twice, save the DOM element and work with it.
use val() instead of text and length instead od length()
:text isn't a good selector. it implies the global selector $('*')
$(document).ready(function () {
var $email = $('#email');
$email.val("(Not Required)");
// this part works fine
$email.focus(function(){
if (this.value == '(Not Required)'){
this.value ='';
}
});
$('#otherTextBoxId').focus(function(){
if ($email.val().length <3 ){
$email.val('(Not Required)');
}
});
});

How can I clear a textarea on focus?

Im using a simple form with a textarea, when the users clicks onto the textarea I want the contents of the textarea to be cleared.
Is this possible?
$('textarea#someTextarea').focus(function() {
$(this).val('');
});
If you only want to delete the default text (if it exists), try this:
$("textarea").focus(function() {
if( $(this).val() == "Default Text" ) {
$(this).val("");
}
});
By testing for the default text, you will not clear user entered text if they return to the textarea.
If you want to reinsert the default text after they leave (if they do not input any text), do this:
$("textarea").blur(function() {
if( $(this).val() == "" ) {
$(this).val("Default Text");
}
});
Of course, the above examples assume you begin with the following markup:
<textarea>Default Text</textarea>
If you want to use placeholder text semantically you can use the new HTML5 property:
<textarea placeholder="Default Text"></textarea>
Although this will only be supported in capable browsers. But it has the added advantage of not submitting the placeholder text on form submission.
My suggestion is that you only remove the initial default content on the first focus. On subsequent focuses, you risk removing user content. To achieve this, simply .unbind() the focus handler after the first click:
$("textarea").focus(function(event) {
// Erase text from inside textarea
$(this).text("");
// Disable text erase
$(this).unbind(event);
});
jsFiddle example
As a note, since you are using a textarea which has open and closing tags, you can can use $(this).text(""); or $(this).html("");... and, since the text inside a textarea is its value you can also use $(this).val(""); and $(this).attr("value", ""); or even this.value = "";.
HTML5 offers a more elegant solution to this problem: the "placeholder" attribute.
It'll create a text in background of your textarea which will appear only when the textarea is empty.
<textarea placeholder="Enter some text !"></textarea>
There are a couple of issues here that are only partially addressed in the current answers:
You need to clear the text when the user focuses the field
You only want to clear it the first time the user clicks on the field
You do not want the user to be able to submit the default text before it's been cleared
You might want to allow the user to submit the default text if they decide to type it back in. I have no idea why they'd want to do this, but if they insist on typing it back in, then I lean toward letting them do it.
With these details in mind, I'd add a class named "placeholder" to the field and use something like the following:
$("form textarea.placeholder").focus(function(e) {
$(this).text("");
$(this).removeClass("placeholder");
$(this).unbind(e);
});
Validate that the "placeholder" class name was removed when the form is submitted to guarantee that the user really, really wants to submit some stupid placeholder text.
If you're using the jQuery Validation Plugin, then you can put it all together like this:
$.validator.addMethod("isCustom", function(value, element) {
return !$(element).hasClass("placeholder");
});
$(form).validate({
rules: {
message: {
required: true,
isCustom: true
}
},
messages: {
message: "Message required, fool!"
},
submitHandler: function(form) {
$(form).find(":submit").attr("disabled", "disabled");
form.submit();
}
});
jQuery(function($){
$("textarea").focus(function(){
$(this).val("");
});
});
Something like this?
$('textarea#myTextarea').focus(function() {
if ($(this).val() == 'default text') {
$(this).val('');
}
});
<textarea type="text" onblur="if ($(this).attr('value') == '') {$(this).val('The Default Text');}" onfocus="if ($(this).attr('value') == 'The Default Text') {$(this).val('');}">The Default Text</textarea>
I found that simply
$('#myForm textarea').val('');
clears the form in Chrome but this did not work for Firefox (6.x). The value was empty in Firebug but the previous text still showed in the textarea. To get around this I select and rebuild the textareas one at a time:
$('#' + formId + ' textarea').each(function(i){
textareaVal = $(this).parent().html();
$(this).parent().html(textareaVal);
});
This finishes the job in Firefox and does not break Chrome. It will go through all of the textareas in a form one by one. Works in all other browsers (Opera, Safari, even IE).
This is possible and i think you are going for a code that can do this for more textareas than one...
This is what i use for my site:
Javascript:
<script type='text/javascript'>
function RemoveText(NameEle)
{
if ($('#' + NameEle) == 'default')
{
$('#' + NameEle).val('');
$('#' + NameEle).text('');
$('#' + NameEle).html('');
}
}
function AddText(NameEle)
{
if ($('#' + NameEle) == '')
{
$('#' + NameEle).val('default');
$('#' + NameEle).text('default');
$('#' + NameEle).html('default');
}
}
</script>
HTML:
<textarea cols='50' rows='3' onfocus='RemoveText(this)' onblur='AddText(this)' name='name' id='id'>default</textarea>

Categories