Occur if 3 button are clicked and disable other button - javascript

I have in a html page 5 button named 1,2,3,4 and 5.If 3 button are clicked the other button must be disabled.
var clicking=0;
$(document).ready(function(){
$('button').click(function(){
clicking++;
$(this).toggleClass("active");
if(clicking==3){
$('button').click(function(){
$(this).toggleClass("nothing");
})
}
})
})
I tried with this script but it don't work because all the button can be clicked.The if is ignored.
i want that only 3 of this 5 button can be clicked and the other must become disabled.

EDIT: shortened the code
I think this is what you want? Count the number of buttons with .active. If it's three or more, disable all buttons that don't have .active.
JS:
$('button').on('click', function() {
$(this).toggleClass('active');
$('button').prop('disabled',false);
if ($('.active').length >= 3) {
$('button:not(.active)').prop('disabled',true);
}
});
Here's a fiddle.

You should do something like this :
var clicking=0;
$(document).ready(function(){
$('button').click(function(){
clicking++;
$(this).toggleClass("active");
if(clicking==3){
$('button').each(function(){
if(!$(this).hasClass("active")){
$(this).addClass("inactive");
}
});
}
});
});
I didn't try it, but I think you like for something similar.

Ok i am not a master of jquery but i came up with a simple logic to implement what you want to achieve, that is disabling all the other buttons that haven't been clicked after three clicks. Here's my working code:
var count = 0;
var ids = new Array();
$(document).ready(function(){
$('button').click(function(){
ids[count] = this.id;
count++;
if(count == 3){ //three buttons clicked, now time to disable the remaining buttons
for(var i=0; i<$('button').length; i++){ //we'll check for all buttons
var id = $('button')[i].id;
var flag = true;
for(var j=0; j<ids.length; j++){ //checking all the buttons against the buttons that got clicked
if(id == ids[j])
flag = false; //button has been clicked (won't be disabled)
}
if(flag){
$("#"+id).attr("disabled", true); //disabling button
}
}
}
})
})
It's very self explanatory and i added lots of comments but still what i did is:
save the ids of buttons that got clicked, then after three clicks, disabling all the buttons who's ids don't match with the saved ids. Pretty simple.. but im sure you can make the code better as i'm not too good at jquery.
See the Working DEMO here

My sugestion is to use an array so you know witch buttons were clicked.
$(document).ready(function(){
var clickedbuttons = [];
$('button').click(function(){
$(this).toggleClass("active");
var idx = jQuery.inArray($(this).attr("id"), clickedbuttons );
if(idx == -1)
clickedbuttons.push($(this).attr("id"));
else clickedbuttons.splice(idx,1);
if(clickedbuttons.length == 3) {
$('button').each(function() {
var index = jQuery.inArray($(this).attr("id"), clickedbuttons );
if(index == -1)
$(this).attr("disabled", "disabled");
});
}
else {
$('button').each(function() {
$(this).removeAttr("disabled");
});
}
});
})
I'm assuming each button has an id. This will work as you want but you have to have an id in every button.
If you do not want to reenable change accordingly
$(document).ready(function(){
var clickedbuttons = [];
$('button').click(function() {
var idx = jQuery.inArray($(this).attr("id"), clickedbuttons );
if(idx == -1) {
clickedbuttons.push($(this).attr("id"));
$(this).toggleClass("active");
}
if(clickedbuttons.length == 3) {
$('button').each(function() {
var index = jQuery.inArray($(this).attr("id"), clickedbuttons );
if(index == -1)
$(this).attr("disabled", "disabled");
});
}
else {
$('button').each(function() {
$(this).removeAttr("disabled");
});
}
});
})

Related

Option to check all boxes and hide table row elements

I've created a simple table where I have the option to select all checkboxes. I would like to have the option to hide individual rows, or hide all the rows when using the select all function. I've managed to get the checkboxes working, but I can't figure out why the table isn't responding to the action. I appreciate any help or insight.
The full code is in this Fiddle. Here is a glance at the jquery and javascript:
<script>
$(document).ready(function() {
$('input[type="checkbox"]').change(function() {
var inputValue = $(this).attr("value");
$("." + inputValue).toggle();
});
});
</script>
<script>
function checkedAll() {
var elements = this.form.getElementsByTagName('input');
// iterate and change status
for (var i = elements.length; i--;) {
if (elements[i].type == 'checkbox') {
elements[i].checked = this.checked;
}
}
}
</script>
<script>
$(document).ready(function() {
$('input[type="checkbox"]').change(function() {
var inputValue = $(this).attr("value");
var checked = $(this)[0].checked;
$("tr").each(function() {
if($(this).find("td:eq(0)").html() === inputValue.toString()) { // this checks the first cell of each row of the table for a match
if(checked) { //instead of just toggling, you check the status and then show/hide
$(this).hide();
} else {
$(this).show();
}
}
});
});
});
</script>
<script>
function checkedAll() {
var elements = this.form.getElementsByTagName('input');
// iterate and change status
for (var i = elements.length; i--;) {
if (elements[i].type == 'checkbox') {
elements[i].checked = this.checked;
$(elements[i]).trigger("change"); // this triggers the function above
}
}
}
</script>
This should work for you. The .each loop will iterate through the rows and hide the ones where the first td is the value to be hidden.

disable anchor link '<a>' if one of my six checkboxes are not checked

How can I disable a anchor link if one(1) of my six(6) checkbox is not check?
var first_option = $('#pid-1590083, #pid-1590090, #pid-1590091, #pid-1590092, #pid-1590093, #pid-1590094');
$("a").click(function(e) {
if($("first_option").prop("checked") === false) {
e.preventDefault(); return false;
} else {return true;};
});
Your current logic doesn't work as you're only looking at the checked property of the first element you select, not all of them.
To achieve what you require, you can use the :checked selector to get all the checked elements within the selectors you provide, then check the length property of the result to see if there aren't any. Try this:
var $first_option = $('#pid-1590083, #pid-1590090, #pid-1590091, #pid-1590092, #pid-1590093, #pid-1590094');
$("#tmp_button-99035").click(function(e) {
if ($first_option.filter(':checked').length === 0) {
e.preventDefault();
alert('Please Choose Collar Colour To Continue');
};
});
first_option.prop("checked") will always check for first element. What you have to do is loop over all elements to check
Like this
$("#tmp_button-99035").click(function(e) {
var isChecked = false;
for (var i = 0; i < first_option.length; i++) {
if (first_option.eq(i).prop("checked")) {
isChecked = true;
break;
}
}
if (!isChecked) {
alert('Please Choose Collar Colour To Continue');
e.preventDefault();
}
return isChecked;
});
Well, the js snippet of yours is only checking the first element. So, you have to track other checkboxes as well for correct result.
var first_option = $('#pid-1590083, #pid-1590090, #pid-1590091, #pid-1590092, #pid-1590093, #pid-1590094')
$(document).on('click', '#tmp_button-99035', function (e) {
if ($(first_option).filter(":checked").length == 0) {
e.preventDefault();
}
});

button continually only fire once

If keep clicking the same buttons then only fire once. sample: https://jsfiddle.net/h4wgxofh/, For example, if click1 clicked then 2nd time or more times clicks should stop firing, the same as click2 however, if I click the same button, it always fires. Also I want links only trigger once but becomes available if other buttons being clicked. (considering if more buttons) Thanks
HTML
<div class="wrap">
Click1
Click2
</div>
Script
var clicked = false;
$('.wrap').on('click', 'a', function(){
var $this = $(this);
clicked = true;
if(clicked = true){
console.log($this.text());
clicked = false;
}
});
I'm probably missing something here, but why not just bind the event to every link in .wrap and unbind it on click like this :
$('.wrap a').on('click', function(){
console.log($(this).text());
$(this).unbind('click');
});
See this fiddle
Edit : after your comment on wanting one link to be rebound after cliking on another, even though it might not be the cleanest solution, this does the job :
var onclick = function(){
var $el = $(this);
console.log($el.text());
$('.wrap a').off('click', onclick);
$('.wrap a').each(function(id, link){
if($el.text() != $(link).text())
$(link).on('click', onclick);
});
}
$('.wrap a').on('click', onclick);
Fiddle again
See the following code
var clicked1 = false;
var clicked2 = false;
$('.wrap').on('click', 'a', function(){
var $this = $(this);
var clickOrigin = $(this).text();
if(clickOrigin == 'Click1' && clicked1==false){
console.log("Click 1 clicked");
clicked1 = true;
}
if(clickOrigin == 'Click2' && clicked2==false){
console.log("Click 2 clicked");
clicked2 = true;
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="wrap">
Click1
Click2
</div>
Also you can find the jsFiddle.
You need to Distinguish between two links(i used text here you may put whatever scenario ) see this example it may help:-
var clicked1 = 0;
var clicked2 = 0;
$('.wrap').on('click', 'a', function() {
var $this = $(this);
var $text = $(this).text();
//Click2
if ($text == 'Click1') {
clicked1 += 1;
if (clicked1 == 1) {
console.log($text);
} else {
return;
}
}
//Click2
if ($text == 'Click2') {
clicked2 += 1;
if (clicked2 == 1) {
console.log($text);
} else {
return;
}
}
});
Full Demo
To disable both buttons after first click, try:
var clicked = false;
$('.wrap').on('click', 'a', function(){
let $this = $(this);
if( !clicked ){
console.log($this.text());
clicked = true;
};
});
To disable each button after first click, try:
$('.wrap a').each(function() {
let $this = $(this);
$this.disabled = false;
$this.on('click', function() {
if ( !$this.disabled ) {
console.log($this.text());
$this.disabled = true;
};
});
});
Every time someone clicks one of the buttons, your script is setting clicked from false to true, checking if the value is true, then setting it to false again. You need to format it like this if you only want the buttons to fire once (obviously you'd have to duplicate this specifically for each button with different IDs):
var clicked = false;
$('.wrap').on('click', 'a', function(){
var $this = $(this);
if(clicked == false){
console.log($this.text());
clicked = true;
}
});
try this ,much simpler and this will be more useful if you have multiple click buttons
if you had implemented some other way ,this will worth a try
<div class="wrap">
Click1
Click2
</div>
$('.wrap').on('click', 'a', function(){
var $this = $(this);
if($this.attr("data-value") == ""){
console.log($this.text());
$this.attr("data-value","clicked")
}
else{
console.log("Already clicked")
}
});
Fiddle
Instead of putting code on click just on first click disable anchor tag this serve the same thing you wants just find below snippet for more information using this we can reduces round trips to the click functions as well
$('.wrap').on('click', 'a', function(){
$(this).addClass("disableClick");
});
.disableClick{
pointer-events: none;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="wrap">
Click1
Click2
</div>
I think you can disable anchor link after one click like this
<div class="wrap">
Click1
Click2
</div>
I think you can disable anchor link after one click like this
<div class="wrap">
Click1
Click2
</div>
$(function () {
$('#click1').on("click", function (e) {
$('#click1').on("click", function (e){
e.preventDefault();
e.preventDefault();
});
});
I think its help you.
Just use $(".wrap").one('click', ....
Read the jquery API documentation.

Show a number of additional divs on every click

I want to have a sequential list display, where initially all the lis except the first one are hidden, and when the user clicks a button, the lis appear by groups of 3. Eventually I would like to hide the button when the list gets to the end.
The code is something like this, but it shows only one per click, every third - but I want to show also the in-between elements until the third
jQuery(".event-holder:gt(0)").hide();
var i = 0;
var numbofelem = jQuery(".event-holder").length;
jQuery("#allevents").on('click', function(e){
e.preventDefault();
i+=3;
jQuery(".event-holder").eq(i).fadeIn();
if ( i == numbofelem ) { jQuery(this).hide(); }
});
Probably the .eq(i) is not the function I need, but couldn't find the correct one...
You can use :hidden with use of .each() loop:
jQuery("#allevents").on('click', function(e){
e.preventDefault();
jQuery(".event-holder:hidden").each(function(i){
if(i <= 2){
jQuery(this).fadeIn();
}
});
});
Working fiddle
If you have just three you could use :
jQuery(".event-holder:gt(0)").hide();
var i = 0;
var numbofelem = jQuery(".event-holder").length;
var li = jQuery(".event-holder");
jQuery("#allevents").on('click', function(e){
e.preventDefault();
li.eq(i+1).fadeIn();
li.eq(i+2).fadeIn();
li.eq(i+3).fadeIn();
i+=3;
if ( i == numbofelem ) { jQuery(this).hide(); }
});
If you have several lis to show you could use a loop, e.g :
var step = 10; //Define it outside of the event
for(var j=0;j<step;j++){
li.eq(i+j).fadeIn();
}
i+=step;
Hope this helps.
You eq(i) needs to be looped.
jQuery(".event-holder:gt(0)").hide();
var i = 0;
var numbofelem = jQuery(".event-holder").length;
jQuery("#allevents").on('click', function(e){
e.preventDefault();
//i+=3;
//jQuery(".event-holder").eq(i).fadeIn();//You are showing only the third element. Loop this
//Something like this
for(var j=i;j<i+3;j++){
jQuery(".event-holder").eq(i).fadeIn();
if ( i == numbofelem ) { jQuery(this).hide(); }
}
i = j;
});
An alternative approach would be to buffer all the items, and keep adding them until empty:
var holders = $('.event-holder').hide();
$("#allevents").click( function(e){
e.preventDefault();
holders = holders.not(holders.slice(0, 3).fadeIn());
if(holders.length === 0) $(this).hide();
});
Fiddle

jquery clone not working if user select other from the drop down the current text field disabled false

Working on jquery clone with my current code everthing works fine.
first scenario if user select other from the drop down the text
field gets enabled
Second scenario if user click addmore button div gets clone
perfectly with id when user select other both Original and clone
textfield gets enabled actually it should be only the cloned should
get enabled not the enabled
Here is the current Jquery code
var i=1;
$(document).on("click", ".edu_add_button", function () {
var i=$('.cloned-row1').length;
$(".cloned-row1:last").clone(true).insertAfter(".cloned-row1:last").attr({
'id': function(_, id) { return id + i },
'name': function(_, name) { return name + i }
}).end().find('[id]').val('').attr({ 'id': function(_, id) { return id + i }
});
$(".cloned-row1:last").find(".school_Name").attr('disabled', true).val('');
if(i < $('.cloned-row1').length){
$(this).closest(".edu_add_button").removeClass('btn_more edu_add_button').addClass('btn_less btn_less1');
}
i++;
return false;
});
$(document).on('click', ".btn_less1", function (){
var len = $('.cloned-row1').length;
if(len>1){
$(this).closest(".cloned-row1").remove();
}
});
$(document).on('change', '.txt_schName', function (){
var cur = $('.txt_schName').index($(this));
$('.school_Name').eq(cur).val($(this).val())
if ($(this).val() == "other") {
$(".school_Name").prop('disabled', false);
$(".school_Name").val('');
}else{
$(".school_Name").prop('disabled', true);
}
});
$(document).on('change', '.txt_degreName', function (){
var cur = $('.txt_degreName').index($(this));
$('.degree_Description').eq(cur).val($(this).val())
if ($(this).val() == "other") {
$("#degree_Description").prop('disabled', false);
$("#degree_Description").val('');
}else{
$("#degree_Description").prop('disabled', true);
}
});
Here is the fiddle link
Kindly suggest me
thanks & regards
Mahadevan
DEMO
The issue comes be cause you are using class selector directly. You need apply value only to the text box which belongs in the same container. Use closest() to find the parent.
$(document).on('change', '.txt_schName', function (){
var cur = $('.txt_schName').index($(this));
var container = $(this).closest('.container-fluid');
$('.school_Name').eq(cur).val($(this).val())
if ($(this).val() == "other") {
$(".school_Name", container).prop('disabled', false);
$(".school_Name", container).val('');
}else{
$(".school_Name", container).prop('disabled', true);
}
});
DEMO HERE
You need to refer proper element that has to be disabled and enabled.
Take the sibling of select's parent and find the input element to be disabled as below:
$(document).on('change', '.txt_schName', function (){
var cur = $('.txt_schName').index($(this));
$(this).closest('.col-xs-6').next('.col-xs-6').find('.school_Name').eq(cur).val($(this).val())
if ($(this).val() == "other") {
$(this).closest('.col-xs-6').next('.col-xs-6').find(".school_Name").prop('disabled', false);
$(this).closest('.col-xs-6').next('.col-xs-6').find(".school_Name").val('');
}else{
$(this).closest('.col-xs-6').next('.col-xs-6').find(".school_Name").prop('disabled', true);
}
});
From what you did, you actually change every fields with class .school_Name, to achieve what you want you can add $(this).parents(".row").find(".class_name") so it only change the current div.
$(document).on('change', '.txt_schName', function (){
var cur = $('.txt_schName').index($(this));
$('.school_Name').eq(cur).val($(this).val())
if ($(this).val() == "other") {
$(this).parents(".row").find(".school_Name").prop('disabled', false);
$(this).parents(".row").find(".school_Name").val('');
}else{
$(this).parents(".row").find(".school_Name").prop('disabled', true);
}
});
DEMO HERE
You can do it this way with targeting specific item using parent() and next() selector and also i prefer to access specific field instead of index(such as eq) for input.
var schoolObj = $(this).parent().next().find(".school_Name");
schoolObj.val($(this).val());
if ($(this).val() == "other") {
schoolObj.prop('disabled', false);
schoolObj.val('');
} else {
schoolObj.prop('disabled', true);
}
Here is the Fiddle
You can have a look for jquery traversing:
parent: https://api.jquery.com/parent/
Next: https://api.jquery.com/next/
Find: https://api.jquery.com/find/
and for full traversing: https://api.jquery.com/category/traversing/

Categories

Resources