How to count dynamically div display block? - javascript

I have 3 div. 2 are hidden by default.
By clicking on a link "add" or a link "remove", I want the other div to be shown or hidden. And then, I would like to count dynamically div which are shown.
Here is my HTML :
<div id="clone1" class="billet">
<input type="text" /><span id="test"></span>
</div>
<div id="clone2" class="billet" >
<input type="text" />
</div>
<div id="clone3" class="billet" >
<input type="text" />
</div>
<div id="ajout-suppr">
<a href="javascript:;" class="ajoutBillet" >Ajouter un billet</a>
<span>-------------</span>
<a href="javascript:;" class="supprBillet" >Supprimer un billet</a>
</div>
jQuery :
$(document).ready(function () {
$(".supprBillet").hide();
$("#clone2").hide();
$("#clone3").hide();
$(".ajoutBillet").click(function (){
var nb = $('.billet:not([style*="display: none"])').size();
$('#test').html(nb);
if(nb < 2) {
$(".supprBillet").hide();
}
else {
$(".supprBillet").show("slow");
}
if($("#clone2").hide()) {
$("#clone2").show("slow");
}
if($("#clone3").hide() && $("#clone2").show()) {
$("#clone3").show();
}
if($("#clone3").show() && $("#clone2").show()) {
$(".ajoutBillet").hide("slow");
}
}); // fin du click function ajout billet
$(".supprBillet").click(function (){
var nb = $('.billet:not([style*="display: none"])').size();
if(nb < 2) {
$(".supprBillet").hide();
}
else {
$(".supprBillet").show();
}
if($("#clone2").show() && $("#clone3").hide()) {
$("#clone2").hide();
}
}); // fin du click function suppr billet
});
As you see nothing works.
Could you please show me an issue?
Thanks in advance.

you can try something like this:
jQuery('.ajoutBillet').on('click',function(){
var lengthDivs = jQuery('.billet:visible').length;
if(lengthDivs < 2 && jQuery('.supprBillet:visible').length > 0){
jQuery('.supprBillet').hide();
}
});

I made this into a fiddle. This does seem to do what is expected (by code). Are you referencing the jquery library?
I did make some changes to your count by checking on 1
if(nb < 1) {
$(".supprBillet").hide();
}

You need to check the visible div by jquery .is(':visible') function.
Like this way :
Replace this
var nb = $('.billet:not([style*="display: none"])').size();
With
var nb = $('.billet').is(":visible").length;

Now shows and hides the inputs:
$(document).ready(function() {
$(".billet input:nth-child(1)").hide();
$(".billet input:nth-child(2)").hide();
$("#new").click(function() {
var count = 0;
$(".billet input").each(function() {
if ($(this).is(":visible")) {
count++;
}
});
$(".billet input:nth-child("+count+")").show();
if ($("#total-divs").html() < 3) {
$("#total-divs").html(count+1);
}
});
$("#delete").click(function() {
var count = -1;
$(".billet input").each(function() {
if ($(this).is(":visible")) {
count++;
}
});
if (count > 0) {
$(".billet input:nth-child("+count+")").hide();
$("#total-divs").html(count);
}
});
});
input {
margin: 4px 0;
width: 100%;
}
.actions {
display: block;
text-align: center;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="billet" >
<input type="text" />
<input type="text" />
<input type="text" />
</div>
<div class="actions">
New | Delete
</div>
Total: <span id="total-divs">1</span>

Related

How to show and hide div elements using vanilla js

Below is code where i tried to show and hide div elements using pure js. Since when i click button it take three click to hide the div elemnts and after that it run smoothly. I was trying to find how to show elemnts in first click.
var count = 0;
function showMee() {
var buttonHome = document.querySelector("#showMe");
count += 1;
buttonHome.addEventListener("click", function() {
if (count == 1) {
document.querySelector('#linkMeOne').style.display = 'none';
document.querySelector('#linkMeTwo').style.display = 'none';
} else if (count == 2) {
document.querySelector('#linkMeOne').style.display = 'block';
document.querySelector('#linkMeTwo').style.display = 'block';
count = 0;
}
});
}
#linkMeOne {
display: block;
}
#linkMeTwo {
display: block;
}
<div id="linkMeOne">
Hiding me As first time....
</div>
<div id="linkMeTwo">
Hiding me as well as...
</div>
<input type="button" value="Check Me" id="showMe" onclick="showMee()" />
Just toggle hidden.
If you want them to start out hidden, add the hidden attribute to the divs
const div1 = document.getElementById("linkMeOne");
const div2 = document.getElementById("linkMeTwo")
document.querySelector("#showMe").addEventListener("click",function() {
div1.hidden = !div1.hidden;
div2.hidden = !div2.hidden;
})
<div id="linkMeOne">
Hiding me As first time....
</div>
<div id="linkMeTwo">
Hiding me as well as...
</div>
<input type="button" value="Check Me" id="showMe" />
Just remove the addEventlistener and the code will start working.
var count = 0;
function showMee() {
var buttonHome = document.querySelector("#showMe");
count += 1;
//buttonHome.addEventListener("click", function() {
if (count == 1) {
document.querySelector('#linkMeOne').style.display = 'none';
document.querySelector('#linkMeTwo').style.display = 'none';
} else if (count == 2) {
document.querySelector('#linkMeOne').style.display = 'block';
document.querySelector('#linkMeTwo').style.display = 'block';
count = 0;
}
//});
}
#linkMeOne {
display: block;
}
#linkMeTwo {
display: block;
}
<div id="linkMeOne">
Hiding me As first time....
</div>
<div id="linkMeTwo">
Hiding me as well as...
</div>
<input type="button" value="Check Me" id="showMe" onclick="showMee()" />
Instead of using a variable, use a class to set the display to none.
function showMee() {
document.querySelector('#linkMeOne').classList.toggle('hidden');
document.querySelector('#linkMeTwo').classList.toggle('hidden')
}
#linkMeOne {
display: block;
}
#linkMeTwo {
display: block;
}
.hidden {
display: none !important;
}
<div id="linkMeOne">
Hiding me As first time....
</div>
<div id="linkMeTwo">
Hiding me as well as...
</div>
<input type="button" value="Check Me" id="showMe" onclick="showMee()" />
While there are many correct answers, all of them lack simplicity.
The easiest of all solution is to add an eventListener to the button and toggle a class to all elements with a certain class. That way you don't have to list every single element:
document.querySelector('#showMe').addEventListener('click', function() {
document.querySelectorAll('.linkMe').forEach(el =>
el.classList.toggle('d-block')
);
})
.linkMe {
display: none;
}
.d-block {
display: block;
}
<div class="linkMe">
Hiding me As first time....
</div>
<div class="linkMe">
Hiding me as well as...
</div>
<input type="button" value="Check Me" id="showMe" />
You could just toggle using a data attribute and some CSS. Here is a verbose version of that:
document.querySelector("#showMe")
.addEventListener("click", (event) => {
const t = event.target;
const showem = t.dataset.show;
document.querySelectorAll('.can-toggle').forEach((element) => {
element.dataset.show = showem;
});
t.dataset.show = showem == "show" ? "hide" : "show";
});
.can-toggle[data-show="hide"] {
display: none;
}
<div class="can-toggle">
Hiding me As first time....
</div>
<div class="can-toggle">
Hiding me as well as...
</div>
<input type="button" value="Check Me" id="showMe" data-show="hide" />
OR even independently with an initial state:
document.querySelector("#showMe")
.addEventListener("click", (event) => {
document.querySelectorAll('.can-toggle').forEach((element) => {
element.dataset.show = element.dataset.show == "hide" ? "show" : "hide";
});
});
.can-toggle[data-show="hide"] {
display: none;
}
<div class="can-toggle" data-show="hide">
Hiding me As first time....
</div>
<div class="can-toggle">
Hiding me as well as...
</div>
<div class="can-toggle" data-show="Ishow">
What am I?
</div>
<input type="button" value="Check Me" id="showMe" data-show="hide" />

show a div message if a value is less than another value in javascript

i want to make a div shows if a value of an input less than 1000
and hide this div if the value is greater or equal 1000 in a real time in JavaScript
let input = document.querySelector("#number")
let box = document.querySelector(".box")
update = () => {
let value = input.value
if(parseInt(value) < 1000){
box.style.display = "none"
} else {
box.style.display = "block"
}
setTimeout(update, 1000);
}
update()
.box {
height: 100px;
width: 100px;
background-color: lime;
}
<input type="text" id="number" />
<div class="box">
</div>
Maybe this can help:
<input type="text" id="myinput">
<button onclick="checkValue()">Enter</button>
<div id="divmsg">
</div>
<script>
function checkValue()
{
var num = parseInt($("#myinput").val());
if (num > 1000)
{
$("#divmsg").hide();
}
else
{
$("#divmsg").text(num);
}
}
</script>

Add a limit to the class selector "dog"

I want this code to change the class of 3 divs maximum using jQuery.
$(".cat, .dog").click(function() {
var el = $(this);
if(el.hasClass('cat')) {
el.removeClass('cat');
el.addClass('dog');
} else {
el.removeClass('dog');
el.addClass('cat');
}
});
// I tried with this code but it does not work, since I can keep dialing more than 3
$(document).ready(function () {
$(".cat").change(function () {
var maxAllowed = 3;
var cnt = $(".dog").length;
if (cnt > maxAllowed) {
addClass('cat');
}
});
});
.cat {
background-color: #dadada;
}
.dog {
background-color: red;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="cat">jQuery</div>
<br/>
<div class="cat">JavaScript</div>
<br/>
<div class="cat">Prototype</div>
<br/>
<div class="cat">Dojo</div>
<br/>
<div class="cat">Mootools</div>
<br/>
To achieve that, you have to add one more check: the amount of elements with class dog should be less than maxAllowed value. The condition should look something like that:
el.hasClass('cat') && activeDogs < maxAllowed // activeDogs - the amount of elements with class "dog"
And finally you will get something close to that:
var maxAllowed = 3;
$(".cat, .dog").click(function() {
var el = $(this);
var activeDogs = $('.dog').length;
if (el.hasClass('cat') && activeDogs < maxAllowed) {
el.removeClass('cat');
el.addClass('dog');
} else {
el.removeClass('dog');
el.addClass('cat');
}
});
.cat {
background-color: #dadada;
}
.dog {
background-color: red;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="cat">jQuery</div>
<br/>
<div class="cat">JavaScript</div>
<br/>
<div class="cat">Prototype</div>
<br/>
<div class="cat">Dojo</div>
<br/>
<div class="cat">Mootools</div>
<br/>
I get $('.dog').length every time, because I guess, that classes can be added/removed not only through this function. But if so, you can simply use a counter to achieve that and compare the counter with maxAllowed variable, this operation will take less resources.
var maxAllowed = 3;
var activeDogs = 0;
$(".cat, .dog").click(function() {
var el = $(this);
if (el.hasClass('cat') && activeDogs < maxAllowed) {
el.removeClass('cat');
el.addClass('dog');
activeDogs++;
} else if (el.hasClass('dog')) {
el.removeClass('dog');
el.addClass('cat');
activeDogs--;
}
});
.cat {
background-color: #dadada;
}
.dog {
background-color: red;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="cat">jQuery</div>
<br/>
<div class="cat">JavaScript</div>
<br/>
<div class="cat">Prototype</div>
<br/>
<div class="cat">Dojo</div>
<br/>
<div class="cat">Mootools</div>
<br/>
Try to increment the count after you add the cat class:
$(document).ready(function () {
var count = 0;
$(".cat").change(function () {
if (count < 3) {
addClass('cat');
count++;
}
});
});
You can just check if you have less than 3 "dogs" (red colored rows) before allowing the class change:
$(".cat, .dog").click(function() {
var el = $(this);
if(el.hasClass('cat') && $('.dog').length < 3) {
el.removeClass('cat');
el.addClass('dog');
} else {
el.removeClass('dog');
el.addClass('cat');
}
});
// I tried with this code but it does not work, since I can keep dialing more than 3
.cat {
background-color: #dadada;
}
.dog {
background-color: red;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="cat">jQuery</div>
<br/>
<div class="cat">JavaScript</div>
<br/>
<div class="cat">Prototype</div>
<br/>
<div class="cat">Dojo</div>
<br/>
<div class="cat">Mootools</div>
<br/>

swap div's position from top div's

I am trying to swap a div's position from top on and when I click another div then top div can be swap.
HTML
<div class="wrap top">
<input type="text" value="div1" class="textbox " />
</div>
<div class="wrap">
<input type="text" value="div2" class="textbox " />
</div>
<div class="wrap">
<input type="text" value="div3" class="textbox " />
</div>
jQuery
(function ($) {
$(".wrap").on("click", function () {
if ($(this).index() == 0) {
} else {
$(this).insertBefore($(this).prev());
}
});
}(jQuery));
The fact is I don't want to remove the div which I click instead want to swap the positions around.
How Can I do this using jQuery itself?
I would suggest using css to position the top div and just swap the class as follows:
(function ($) {
$(".wrap").on("click", function () {
if ($(this).index() == 0) {
} else {
$(".wrap").removeClass("top");
$(this).addClass("top");
}
});
}(jQuery));
this will swap whatever you click with the first element.
$(".wrap").on("click", function () {
var $this = $(this);
if ($this.index() == 0) {
} else {
var first = $this.siblings('.wrap').first();
first.insertBefore($this);
$this.prependTo($this.parent());
}
});
if you just want to move the clicked element to the top, you can simply do
$this.prependTo($this.parent());
To swap the two DOM elements using jQuery, you could use something like this: -
(function($) {
$(".wrap").on("click", function(event) {
var index = $(event.target).index();
var first = $(".wrap").first();
if (index > 0) {
$(first).swapWith(this);
}
});
}(jQuery));
jQuery.fn.swapWith = function(to) {
return this.each(function() {
var copy_to = $(to).clone(true);
var copy_from = $(this).clone(true);
$(to).replaceWith(copy_from);
$(this).replaceWith(copy_to);
});
};
.wrap {
height: 100px;
width: 200px;
margin: 10px 10px 10px 10px;
background-color: #2d8cd0;
}
h2 {
color: white;
text-align: center;
padding-top: 20px;
pointer-events: none;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script>
<div class="wrap">
<h2>1</h2>
</div>
<div class="wrap">
<h2>2</h2>
</div>
<div class="wrap">
<h2>3</h2>
</div>
<div class="wrap">
<h2>4</h2>
</div>

Select concrete DOM element without ID

When I'm typing a login or password, tooltip appears with one or more sentences.
Every tooltip has the same z-index, but I want to change it to higher when I'm focused at adequate input and bring it back at blur event, but I might have 10 inputs with many options in tooltip. Is it possible to write function without using ID of tooltip?
$(document).ready(function() {
$('input').focus(function() {
$('div.tooltip').addClass("active");
});
$('input').blur(function() {
$('div.tooltip').removeClass("active");
});
$('#login').keyup(function() {
var th = document.getElementById('login').value;
if (th.length < 6) {
$('#result').css('display', 'inline');
var ex = $("#too_short").text();
if (!ex) {
$('#result').append('<p id="too_short">Too short password.</p>');
}
} else {
$("#too_short").remove();
}
if (th.contains('\'') || th.contains('\"') || th.contains('\\') || th.contains('\/')) {
$('#result').css('display', 'inline');
var en = $("#forb_char").text();
if (!en) {
$('#result').append('<p id="forb_char">Forbidden characters</p>');
}
} else {
$("#forb_char").remove();
}
});
$('#pwd').keyup(function() {
var th = document.getElementById('pwd').value;
if (th.length < 6) {
$('#result1').css('display', 'inline');
var ex = $("#too_short1").text();
if (!ex) {
$('#result1').append('<p id="too_short1">Too short password.</p>');
}
} else {
$("#too_short1").remove();
}
if (th.contains('\'') || th.contains('\"') || th.contains('\\') || th.contains('\/')) {
$('#result1').css('display', 'inline');
var en = $("#forb_char1").text();
if (!en) {
$('#result1').append('<p id="forb_char1">Forbidden characters</p>');
}
} else {
$("#forb_char1").remove();
}
});
});
.tooltip {
position: absolute;
border: 2px solid red;
display: none;
margin-left: 250px;
background: blue;
z-index: 1;
color: white;
}
.active
}
z-index:999;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script>
<form name="form" id="form" method="post">
<div id="result" class="tooltip"></div>
<span> Write login: </span>
<input id="login" name="login" type="text" />
<br/>
<div id="result1" class="tooltip"></div>
<span> Write pwd: </span>
<input id="pwd" name="pwd" type="text" />
</form>
<!-- How to addClass active to proper div.tooltip? -->
Something like this? :
http://jsfiddle.net/9n2db67u/22/
Your code is very messy. Try to use TidyUp when posting jsfiddle links..
$('input').on('click', function () {
$('.active').removeClass('active');
$(this).prevAll('div').addClass('active'); //.css('z-index', '20000');
});

Categories

Resources