jQuery Alert message looping - javascript

I am using the following jQuery script. This is to alert user when they leave an empty input element.
function checkEmpty(elem){
$(elem).focusout(function (){
if(!$(elem).val() || $(elem).val()==" "){
alert("This Field can't be empty");
return true;
}
});
}
Calling in HTML like
onclick="checkEmpty(this);
If i left the input element blank at first time, it gives only one alert.
But when i leave same input element blank more than one time i am getting continues alert message .
I use the debugger to see what happens, it looping again and again.
Where i went wrong?

Try this code
<!DOCTYPE html>
<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
<script>
function checkEmpty(elem)
{
if(!$(elem).val() || $(elem).val()==" ")
{
alert("This Field can't be empty");
return true;
}
}
</script>
</head>
<body>
Enter your name: <input type="text" onblur="checkEmpty(this)">
<p>Write something in the input field, and then click outside the field to lose focus (blur).</p>
</body>
</html>

You are binding the focusout event each time the source element is clicked. The handlers keep on adding on each click and you need only once. Instead of binding click event handler bind onfocusout directly.
Binding
onfocusout="checkEmpty(this);
Handler function
function checkEmpty(elem){
if(!$(elem).val() || $(elem).val()==" "){
alert("This Field can't be empty");
return true;
}
}

You should probably bind the handler when the page loads.
Try this:
$(document).ready(
$(elem).focusout(function (){
if(!$(elem).val() || $(elem).val()==" "){
alert("This Field can't be empty");
}
});
);
EDIT: If you want to use it for multiple text fields, then you just have to modify your function like so:
function check(elem){
if(!elem.data.val() || elem.data.val()==" "){
alert("This Field can't be empty");
}
}
Then to use it:
$(document).ready(
// Input element 1
$(elem1).focusout($(elem1), check);
// Input element 2
$(elem2).focusout($(elem2), check);
);
Here's a JSFiddle example: https://jsfiddle.net/CgP2X/40/
NOTE: I am not proficient in jQuery, so I tried it first in fiddle. Sorry for the late edit.

Related

add an alert if div is empty

I have this code and it works:
$(document).ready(function() {
$('#textDiv:empty').hide();
});
But I want to add a jquery function in case the div #textDiv is not empty. I want to add an alert if it is not empty. I tried this code without success.
$(document).ready(function(){
if ( $('#textDiv').text().length == 0 ){
alert ("please add players below");
}
});
What is the cleanest way to do this?
you need to use the text() text function to get the html/text inside the div
$(document).ready(function(){
if ($('#textDiv').text() == '') // Change the condition for emapty and not empty
{
alert ("please add players below");
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="textDiv"></div>
The result of the .text() method is a string containing the combined text of all matched elements. It is different from the .html() functions. Due to variations in the HTML parsers in different browsers, the text returned may vary in newlines and other white space.
You are better off with creating a function which checks if the div has any html or not and return true or false respectively.
(function($){
jQuery.fn.checkEmpty = function() {
return !$.trim(this.html()).length;
};
}(jQuery));
Use :
<div id="selector"></div>
On document ready, call this function with your div and it would alert according to the condition.
$(document).ready(function(){
if($("#selector").checkEmpty()){
alert("Empty");
}else{
alert("Not Empty");
}
});
You can use CSS Pseudo-Classes to access items in jQuery:
if ($('.textDiv:empty')) {
alert('First Empty');
}
if ($('.textDiv:not(:empty)')) {
alert ("Second not Empty\nplease add players below");
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="textDiv">Empty : No child elements</div>
<br>
<div class="textDiv">
<p>Not Empty : Has child elements</p>
</div>
Check length before hide else alert.
if ($('#textDiv:empty').length !== 0)
$('#textDiv:empty').hide();
else
alert ("please add players below");
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="textDiv">Test Contain For Alert</div>
Maybe like this:
$(document).ready(function(){
if (!$('#textDiv').text().length){
alert ("please add players below");
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<div id="textDiv"></div>

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

how to remove an element when textarea is empty?

I want to check if the textarea is empty and then remove the element prev() to it. How do I do so? My attempt was this:
if($(".inputs").val().length == 0){
$(this).prev().hide();
};
Do I have to check for "keypress"? The element I am trying to hide was show() after a "keypress" event. But I want to hide it immediately if the textarea is empty.
Edit: Question 2: I was using this code to show an element after first input:
$(".inputs").one("keypress", function(){
$(this).prev().show().addClass("animated slideInUp");
});
but now that I want to hide and show depending on the length of the textarea should I do something like this:
$(".inputs").on("input", function() {
if ($(".inputs").val().length == 0) {
$(this).prev().hide();
}
else if ($(".inputs").val().length == 1) {
$(this).prev().show().addClass("animated slideInUp");
}
If you want to hide the previous element when you delete content within the <textarea>, then .keyup is the way to go:
$(".inputs").on("input", function() {
if ($(".inputs").val().length == 0) {
$(this).prev().hide();
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="text">Hidden when all content is deleted, doesn't restore</div>
<textarea class="inputs"></textarea>
Keep in mind that this won't restore the previous element when you start typing again. If you'd like to do that, you'll need to extend the script a little to also .show() the previous element:
$(".inputs").on("input", function() {
if ($(".inputs").val().length == 0) {
$(this).prev().hide();
}
else {
$(this).prev().show();
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="text">Hidden when all content is deleted, restores</div>
<textarea class="inputs"></textarea>
Note that input is used over keyup in case the user edits the field without using the keyboard.
Hope this helps! :)

disable enable button on keypress

i want to enable button when there is some value in text box
this is working fine all most but for one value it will fail
like is enter 1 in text box
http://jsfiddle.net/akash4pj/YhQN4/
js
<script>
$(document).ready(function(){
$("#textbx").keypress(function(){
if ($("#textbx").val().length > 0) {
$("#btn").removeAttr('disabled');
}
});
$("#textbx").blur(function(){
if ($("#textbx").val().length ==0) {
$("#btn").attr('disabled','disabled');
}
});
});
</script>
html code
<input id="textbx" type="text" /><button id="btn" disabled="disabled">go</button>
Use keyup instead of keypress, like this:
$("#textbx").blur(function () {
if ($("#textbx").val().replace(/\s{1,}/g, "").length == 0) {
$("#btn").attr('disabled', 'disabled');
}
});
Also, I've added .replace(/\s{1,}/g, "") in the code as well. This ensures (indirectly) that if the user only types spaces, the button will still be disabled when the text input is blurred.
Fiddle.
The keypress event occurs before the browser processes the key, i.e. before the character is appended to the input value, so when the first key is pressed, the textbox is still empty when your functions checks the value length.
The keyup event occurs after the browser has appended the character to the input, so if you trigger on keyup instead of keypress your code should function the way you want.
I'd suggest:
$("#textbx").on('keyup blur', function() {
$("#btn").prop('disabled', $.trim(this.value).length === 0);
});
As mentioned in other answers you should use keyup, but you don't need to listen for blur as well:
$("#textbx").keyup(function(){
if ($("#textbx").val().trim().length > 0) {
$("#btn").removeAttr('disabled');
}
else
$("#btn").attr('disabled','disabled');
});
Fiddle

jQuery checkbox click shows input field - doesn't work

I use a jQuery function to show certain hidden text fields once you select something from a select box.
This works fine for select boxes but I can't get it to work for a checkbox.
Here is the stripped code I tried (in a nutshell) but it's not working: http://jsbin.com/uwane3/2/
Thanks for your help, I rarely use JS so my knowledge is small.
I have found 2 errors in your code:
your Checkbox has no value so you cant get more than an empty result form ".val()"
you have not bind a eventhandler to the checkbox.
http://jsbin.com/uwane3/3
$('#cf3_field_9').live('click', function(e){
if (e.target == $('#cf3_field_9')[0] && e.target.checked) {
alert('The following line could only work if the checkbox have a value.');
$.viewMapcf3_field_9[$(this).val()].show();
} else {
$.each($.viewMapcf3_field_9, function() { this.hide(); });
}
});
You have no events registered to your checkbox.
Register a click, or change handler like this:
$('#cf3_field_9').click(function(){
if ($(this).attr("checked")) {
$.viewMapcf3_field_9[$(this).val()].show();
} else {
$.each($.viewMapcf3_field_9, function() { this.hide(); });
}
});
http://api.jquery.com/category/events/

Categories