add an alert if div is empty - javascript

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>

Related

Change background of div based on value of div

Trying to get this javascript to read the value of the div "flow-hold" and change the background color based on the value.
I have a div named flow hold with a value of 132 for example, that I would like to see green because it is less than the 200 threshold. If the value exceeds the threshold, I would like it to be red.
<div class="flow-hold">132</div>
<script type="text/javascript">
$('.flow-hold'), function(){
if($(this).val()>=200){
$('.flow-hold').css({"background-color":"red"});
} else {
$('.flow-hold').css({"background-color":"green"});
}
});
</script>
try this simple and easy:
$('.flow-hold').each(function() {
if (parseInt($(this).text()) >= 200) {
$(this).css("background-color","red");
} else {
$(this).css("background-color","green");
}
});
If you want to do it on page load you could use your Back-End technology to assign a CSS class with demanded color according to the threshold.
For example, in PHP it would be:
<div class="flow-hold <?=($threshold>=200)?'bg-red':'bg-green'?>">132</div>
In your CSS file:
bg-red{
background-color: red;
}
bg-green:{
background-color: green;
}
However, if you want to do it on client-side, you have to allocate an exact action to it, for instance:
<div class="flow-hold">132</div>
<script type="text/javascript">
$('.flow-hold').on('hover', function(){
if($(this).val()>=200){
$('.flow-hold').css({"background-color":"red"});
} else {
$('.flow-hold').css({"background-color":"green"});
}
});
</script>
actually your problem are the accessors that you are using. check that if you use JQuery and get the items by class you will get an array with all the divs containing that class.
so here you have a working example of what you wanted to achieve taking into account what I told before.
NOTE: your code doesn't run by itself, next time please fix it.
NOTE2: note that I didn't do a lot of changes and it started to work.
function changeBackground() {
let div = $('.flow-hold')[0];
if (div.innerText >= 200) {
$('.flow-hold').css({
"background-color": "red"
});
} else {
$('.flow-hold').css({
"background-color": "green"
});
}
}
changeBackground();
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="flow-hold">132</div>
You can use the script below:
$(document).ready(function(){
var value = parseInt($('.flow-hold').html());
if(value >= 200){
$('.flow-hold').css("background-color","red");
}
else {
$('.flow-hold').css("background-color","green");
}
});
I believe you intended to use the .each( function ) jQuery method, where the function should only handle one element at a time, so it shouldn't lookup $('.flow-hold') again, since there can be more than one element with that class.
You should also use the .text() method, not the .val() method.
$('.flow-hold').each(function() {
if ($(this).text() >= 200) {
$(this).css({"background-color":"red"});
} else {
$(this).css({"background-color":"green"});
}
});
Since you are setting the same property in both cases, you can also use the implicit looping of the .css( propertyName, function ) method:
$('.flow-hold').css("background-color", function() {
return ($(this).text() >= 200 ? "red" : "green");
});

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! :)

jQuery Alert message looping

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.

Getting checkbox value and display a div using jquery or java script

I would like to display a div which is by default is hidden, if checkbox value is "Yes". here is my html code
<div class="bestsell_wrapper">
<div style="display:none;" itemprop="best-sell" class="best-sell"></div>
<input type="checkbox" class="bestsell_chkbox" name="bestsellchk_box"
value="<%=getCurrentAttribute('item','custitem_sumisho_overlay1')%>" style="display:none;" />
</div>
There are multiple items and for which the checkbox value is "Yes" i want to display div having class name "best-sell".This jquery code i have tried but its not working
<script type="text/javascript">
$(".bestsell_chkbox").each(function(){
if ($("this").val().trim() == "Yes")
{
$(".best-sell").css("display", "block");
}
});
</script>
Simply change your jQuery to:
$(".bestsell_chkbox").each(function(){
var $that = $(this);
if ($that.val().trim() == "Yes") {
$that.prev(".best-sell").css("display", "block");
}
})
Hi please do the following
if($(this).val().trim() == "Yes"){
Use this:
$("input.bestsell_chkbox[type='checkbox']").each(function () {
if ($(this).attr("checked") !== "checked") {// do your stuff here}
});
You have a few mistakes in your Script. If you want this to show only checkboxes on load this is the code that will get it done.
$(".bestsell_chkbox").each(function(){
if ($(this).val().trim() == "Yes"){
$(".bestsell_chkbox").css("display", "block");
}
});
Your code was trying to show div but your div is already visible. Your checkbox was hidden. That is why I changed the class inside if clause
Use This Code
<script type="text/javascript">
$(document).ready(function () {
$(".bestsell_chkbox").each(function(){
if ($(this).attr("checked"))
{
$(this).closest('.best-sell').css({'display':'block'});
}
});
});
</script>

jquery slide click link

First, Sorry if I don't speak good English.
My question is how do I make a div slide when I click a link using jQuery?
I have this:
<script type="text/javascript">
function slide(div) {
if($(div).css('display') === 'none'){
$(div).delay(300).slideUp(500);
return false;
} else {
$(div).delay(300).slideUp(500);
return false;
}
}
</script>
Click here
<div id="div1" style='display: none'>
this will show
</div>
Does anybody have any idea what the problem is? Thank You
jQuery's .slideUp() is specifically for hiding elements.
If you want to specifically SHOW the div, use .slideDown() to show.
You are also able to use .slideToggle() if you wanted to switch between showing / not showing.
Just change your .slideUp('s to .slideDown('s.
See this jsFiddle
This will fix your function, you're always using slideUp, this way the display will never change
function slide(div) {
if($(div).css('display') === 'none'){
$(div).delay(300).slideDown(500);
return false;
} else {
console.log('2');
$(div).delay(300).slideUp(500);
return false;
}
}
Use slideToggle instead.
Click here
<div id="div1" style='display: none'>
this will show
</div>
$('.handler').click(function() {
$('#div1').slideToggle(500);
});

Categories