onBlur event on composed component (input + Button) - javascript

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

Related

Replace class on clicking outside div

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">

Handle dialog-close event on input type='color'

Here is a default(html5) color selector:
<input id='color-picker' type=color value='#ff0000'>
By click on the element, a default color-picker dialog opens.
I can easily track the color change event:
$('#color-picker').on('change', function() {
console.log($(this).val());
});
How dialog window close event can be handled? For example, when user clicks Cancel button?
Here is jsfiddle additionally.
Unfortunately, the exact functionality is not possible. I even read through the stack link, it seems that file calls the change event regardless of change, whereas color does not... So, I added the code to the blur event instead. When the user click off the value after editing color for any reason, it will check for cancel. I added a phony submit button to force the user to do it.
$('#color-picker').on('blur', function() {
if ($(this).data("prevColor") == $(this).val()) {
console.log('cancelled');
} else {
//value changed
}
updateData.bind(this)();
});
function updateData() {
$(this).data("prevColor", $(this).val());
}
updateData.bind($("#color-picker"))();
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input id='color-picker' type=color value='#ff0000'><button>Submit</button>
I've used this for the Cancel and Close Events.
var prevColor;
$('#color-picker').onchange = function(){
if (this.value != prevColor){
prevColor = this.value;
}
};
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input id='color-picker' type=color value='#ff0000'><button>Submit</button>

Detect when html input required true is working

I have a form
<form id="newRecord">
<input type="text" required/>
</form>
<button form="newRecord" type="submit">Submit</button>
http://codepen.io/anon/pen/EZwRjK
When the field is empty, and you click the button, you get a "Please fill out this field." pop up next to the field. Is there a way to detect if that pop up appears with JavaScript?
In HTML5, the pseudo-class :invalid is applied to any input that triggers the "This field is required" dialog box.
If you put the listener on your button, you could find out if the dialog box appeared or not by checking to see if there were any inputs marked :invalid...
$("#newRecord input[type=submit]").click(function() {
if ($("#newRecord input:invalid").length) {
//The popup appeared
} else {
//The popup did not appear
}
});
JSFiddle demo
In fact you can. You can use checkValidity() method. It returns true if the element contains a valid data.
$(function() {
$("#submit-button").click(function () {
// using jquery
console.log($("#input-text")[0].checkValidity());
// using javascript
var input = document.getElementById("input-text");
console.log(input.checkValidity());
});
});
Fiddle
Update
Seems the pop up is not showing when using type="button".
A work around I found is to use $("input").on("blur", function () { instead.
So it should be now:
$(function() {
$("input").on("blur", function () {
console.log($("#input-text")[0].checkValidity());
var input = document.getElementById("input-text");
console.log(input.checkValidity());
// checking as a whole
console.log("Form - ", $("#newRecord")[0].checkValidity());
});
});
Fiddle
REACT / NEXT.JS
In my case, it was because the 'input' tags were required and were not in the viewport (not visible) when submitting on my form.
The form was hidden when a useState was false const [isOpen, setIsOpen] = useState(false), then it was necessary to change the state to true so that the form would appear and the "fill these fields" message.
Solution was with onInvalid() property
<input onInvalid={() => setIsOpen(true)} type='radio' required />

Prevent function execution twice within two triggered events

I have the following code:
myInput.change(function (e) { // this triggers first
triggerProcess();
});
myButton.click(function (e) { // this triggers second
triggerProcess();
});
The problem with the above is when I click myButton both events are triggered and triggerProcess() is fired twice which is not desired.
I only need triggerProcess() to fire once. How can I do that?
Small demo
You can have a static flag that disables any more triggers once the first trigger has occurred. Might look something like this:
var hasTriggered = false;
myInput.change(function (e) { // this triggers first
triggerProcess();
});
myButton.click(function (e) { // this triggers second
triggerProcess();
});
function triggerProcess () {
// If this process has already been triggered,
// don't execute the function
if (hasTriggered) return;
// Set the flag to signal that we've already triggered
hasTriggered = true;
// ...
}
For resetting the hasTriggered flag, that's entirely up to you and how this program works. Maybe after a certain event occurring in the program you'd want to reenable the ability to trigger this event again — all you'd need to do it set the hasTriggered flag back to true.
You can use the mousedown event, which will fire before the input is blurred, and then check if the input has focus by checking if it's the activeElement, and if it does have focus, don't fire the mousedown event, as the change event will fire instead.
Additionally, if you want a mousedown event to occur when the value hasn't changed, and the change event doesn't fire, you'll need a check for that as well
var myInput = $('#test1'),
myButton = $('#test2'),
i = 0;
myInput.change(function(e) { // this triggers first
$(this).data('prev', this.value);
triggerProcess();
});
myButton.mousedown(function(e) { // this triggers second
var inp = myInput.get(0);
if (document.activeElement !== inp || inp.value === myInput.data('prev'))
triggerProcess();
});
function triggerProcess() {
console.log('triggered : ' + (++i))
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input id="test1">
<br />
<br />
<button id="test2">
Click
</button>
In a fairly typical scenario where you have an input with a button next to ie, eg quick search.
You want to fire when the input changes (ie onblur) but also if the user clicks the button.
In the case where the user changes the input then clicks the button without changing input focus (ie no blur), the change event fires because the text has changed and the click event fires because the button has been clicked.
One option is to debounce the desired event handler.
You can use a plugin or a simple setTimeout/clearTimeout, eg:
$('#inp').change(debounceProcess)
$('#btn').click(debounceProcess);
function debounceProcess() {
if (debounceProcess.timeout != null)
clearTimeout(debounceProcess.timeout);
debounceProcess.timeout = setTimeout(triggerProcess, 100)
}
function triggerProcess() {
console.log('process')
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<input id="inp">
<button id="btn">Click</button>
Use a real <button>BUTTON</button>. If you click on input text, alert is triggered, then once you leave the input text to click anywhere else, that unfocuses the input text which triggers the change event, so now 2 events have been triggered from the text input.
This is an assumption since the code provided is far from sufficient to give a complete and accurate answer. The HTML is needed as well as more jQuery/JavaScript. What is myInput and myButton actually referring to, etc.?
So I bet if you change...
var myButton = $('{whatever this is}'); and <input type='button'>
...TO:
var myButton = $("button"); and <button></button>
...you should no longer have an event trigger twice for an element.
This is assuming that triggerProcess() is a function that does something that doesn't manipulate the event chain or anything else involving events. This is an entirely different ballgame if instead of click() and change() methods you are using .trigger() or triggerHandler(), but it isn't. I'm not certain why such complex answers are derived from a question with very little info...?
BTW, if myInput is a search box and myButton is the button for myInput, as freedomn-m has mentioned, simply remove:
myButton.click(...
Leave myButton as a dummy. The change event is sufficient in that circumstance.
SNIPPET
var xInput = $('input');
var xButton = $('button'); //«———Add
xInput.on('change', alarm);
xInput.on('click', alarm);
xButton.on('click', alarm);
function alarm() {
return alert('Activated')
}
/* For demo it's not required */
[type='text'] {
width: 5ex;
}
b {
font-size: 20px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form id='f1' name='f1'>
<input type='text'>
<input type='button' value='BUTTON TYPE'>
<label><b>⇦</b>Remove this button</label>
<button>BUTTON TAG</button>
<label><b>⇦</b>Replace it with this button</label>
</form>

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

Categories