JavaScript all On/Off button - javascript

I have 6 buttons and I wish to create a master button which will turn all the other buttons on or off. I managed to do that but ran into a problem when the master button would turn a button off if it was already on. I need this button to turn all the buttons on or off regardless of its previous state.Button 7 will be acting as master button. Thank you for taking the time to read this, any help would be much appreciated.
//master button
function button7(){
currentvalue = document.getElementById('button7').value;
if(currentvalue == "Off"){
document.getElementById("button7").value="On";
}else{
document.getElementById("button7").value="Off";
}
}
$(document).ready(function(){
$('#button7').on('click', function(){
$('#button7').toggleClass('on');
$('#button1').toggleClass('on');
$('#button2').toggleClass('on');
$('#button3').toggleClass('on');
$('#button4').toggleClass('on');
$('#button5').toggleClass('on');
$('#button6').toggleClass('on');
if(currentvalue == "Off"){
alert("off")
}
else{
alert("on")
}
});
});
//regular button
function button1(){
currentvalue = document.getElementById('button1').value;
if(currentvalue == "Off"){
document.getElementById("button1").value="On";
}else{
document.getElementById("button1").value="Off";
}
}
$(document).ready(function(){
$('#button1').on('click', function(){
$(this).toggleClass('on');
if(currentvalue == "Off"){
alert("off")
}
else{
alert("on")
}
});
});

If you want to set all the buttons to a specific state, don't use toggleClass() which, as the name itself suggests, is used to toggle class-names. Instead:
$('#button7').on('click', function(){
// select all the elements by their id:
$('#button1,#button2,#button3')
// remove both classes:
.removeClass('on off')
// add the class that the clicked-button currently represents:
.addClass(this.value)
// whatever Boolean the button currently represents,
// switch to the other option:
.val(this.value === 'On' ? 'Off' : 'On');
});
References:
addClass().
removeClass().
val().

Toggle the class on the button, the check if it has that class and use that to add or remove the class on all the other buttons. Using a boolean value as the second parameter to toggleClass will add or remove the class according to the boolean, not the presence of the class.
$(document).ready(function(){
$('#button7').on('click', function(){
$('#button7').toggleClass('on');
var currentvalue = $('#button7').hasClass('on');
$('#button1').toggleClass('on', curentvalue);
$('#button2').toggleClass('on', curentvalue);
$('#button3').toggleClass('on', curentvalue);
$('#button4').toggleClass('on', curentvalue);
$('#button5').toggleClass('on', curentvalue);
$('#button6').toggleClass('on', curentvalue);
if (currentvalue){
alert("on")
} else {
alert("off")
}
});
});

Related

Change and change back text in button jquery

I would like to have a jquery button event where the first time a button is clicked a div (with class .explanation) appears and the text changes and the second time it is clicked the div is hidden and the text changes back to the original text. I can do the first part but the second part does not work. In the below changing - (toggleClass("hidden") - to - .fadeOut... - doesn't work either so I think I have got something wrong with if and else. Thanks in advance
$("button:nth-of-type(1)").click(function() {
if (this.text = "Read Explanation") {
$(".explanation").fadeIn("slow", function() {});
$(this).text("Hide Explanation");
} else {
$(this).text("Read Explanation");
$(".explanation").toggleClass("hidden");
}
});
change
if(this.text = "Read Explanation") {
to
if($(this).text() === "Read Explanation") {
a demo:
$("button:nth-of-type(1)").click(function() {
if ($(this).text() === "Read Explanation") {
//$(".explanation").fadeIn("slow", function() {});
$(this).text("Hide Explanation");
} else {
$(this).text("Read Explanation");
}
$(".explanation").toggleClass("hidden");
});
.hidden {
display: none;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.1/jquery.min.js"></script>
<div><button>Read Explanation</button></div>
<div class="explanation hidden">explanation</div>
$(this) is jquery object with text() attribute while this is pure js
object without text or text() attribute in this case.
= is assignment operator while === is Comparison operators
There are several issues in your code:
this should be $(this)
text should be text()
You are using assignment operator in if condition. It should be comparison operator == or strict comparison operator ===
You can toggle the hidden class outside if-else block
$( "button:nth-of-type(1)" ).click(function() {
if($(this).text() == "Read Explanation") {
$(this).text("Hide Explanation");
} else {
$(this).text("Read Explanation");
}
$(".explanation").toggleClass("hidden");
});
.hidden{
display: none;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class='explanation hidden'>Some explanation</div>
<button>Read Explanation</button>
you can't make decisions based on data that can change.
if the text of the button changes, you'll need to change your code.
by this way, if the text of the button changes, you need to change your data.
This is not the best option, but it may works.
https://jsfiddle.net/foo8drb2/8/
var data = {
1: "Read Explanation",
2: "Hide Explanation"
}
// asssign default id to the text
var id_text = 1; //1 id for "Read Explanation"
// add data attribute to the button
$("button:nth-of-type(1)").attr("data-id-text", id_text);
// event
$("button:nth-of-type(1)").click(function () {
if ($(this).attr("data-id-text") == 1) {
//change id_text -> 2 for "Hide Explanation"
id_text = 2;
// show hide options
$(".explanation").fadeIn();
} else {
//change id_text -> 1 for "Read Explanation"
id_text = 1;
// show hide options
$(".explanation").fadeOut();
}
// change data id
$(this).attr("data-id-text", id_text);
// update text
$(this).text(data[id_text]);
});
Thanks everyone. This seems to be the simplest / close to what I had. I changed as suggested by Ankit:
this to $(this)
text to text()
= to ==
Using - fade out - instead of - hide - helped
$( "button:nth-of-type(1)" ).click(function() {
if($(this).text() == "Read Explanation") {
$(".explanation").fadeIn( "slow", function() {
});
$(this).text("Hide Explanation");
} else {
$(this).text("Read Explanation");
$(".explanation").fadeOut( "slow", function() {
});
}
});

Simple JQuery show/hide text button

I'm trying to practice with JQuery, so I made a simple program...or tried to. There is a button that, when clicked, hides the only element on the page. That works fine. But when I click it again, it doesn't bring the paragraph back and change the button text back, as its supposed to. And there any way I can get this to work without using two buttons? Here's what the script looks like right now:
<script>
$(document).ready(function(){
var t;
$("button").click(function(){
if (t === "off") {
$("p").show();
$(this).text("hide text");
}
$("p").hide();
$(this).text("show text");
t = "off";
});
});
</script>
$(document).ready(function(){
var t = "on";
$("button").click(function(){
if (t === "off")
{
$("p").show();
$(this).text("hide text");
t = "on";
}
else
{
$("p").hide();
$(this).text("show text");
t = "off";
}
});
});
Something like that. basically the $("p").hide part always triggers.
Or even easier, use toggle function
That's because you need to put the hide logic in else:
if (t === "off") {
$("p").show();
$(this).text("hide text");
} else {
$("p").hide();
$(this).text("show text");
t = "off";
}
In your code, when you "click it again", although t is off and $("p") is made to shown at beginning, it would be immediately made to hide again.
$(document).ready(function(){
var t;
$("button").click(function(){
if (t === "off")
{
$(this).text("hide text");
t = "";
} else {
$(this).text("show text");
t = "off";
}
$("p").toggle();
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button type="button">Click Me!</button>
<p>Paragraph text</p>
There are many answers that have already provided to you, so I'm just going to point out things that I think could be done better.
You need to put the part of the code below in an else statement, otherwise this block of code will execute regardless of the value of t. I suggest you learn more about if-else conditional statement.
$("p").hide();
$(this).text("show text");
t = "off";
$("button").click(function(){ you should use id of the button, i.e. $("#nameOfButtonID").click(function(){. Learn about the id or class attribute in html. id is a unique way identify which button to handle the click event.
t could be treated as boolean.
In your button click function you have to return before the if loop exits and you need to set some other value or undefined to t.
Order of execution:
First click:
t value is "undefined"
if loop wont execute
hide "p"
set button value as 'show text' and t as "off"
Second click:
t value is "off"
if loop will execute
it will show 'p'
change button value to 'hide text'
---- here you should change t's value and return----
As there is no return 'p' will hide
button text will be 'show text' again.
$("button").click(function() {
if (t === "off") {
$("p").show();
$(this).text("hide text");
//add the below code
t = undefined;
return;
}
$("p").hide();
$(this).text("show text");
t = "off";
});

jQuery AddClass method not working

I am trying to add a new class to a "submit" input after checking that other form elements are filled up. I´m using .keyup() to trigger the function. This function changes the property "disabled" to "false", but after that it does not add the class " animate pulse ". Thanks!
<script> //checks that all fields are completed before enabling submit button
$(document).ready(function() {
$('input[type="submit"]').prop('disabled', true);
$('input[type="text"],input[type="email"],input[type="password"]').keyup(function() {
if($('#log_password').val() != '' && $('#log_email').val() != '') {
$('input[type="submit"]').prop('disabled', false).addClass("animated pulse");
}
else{
$('input[type="submit"]').prop('disabled',true);
}
});
});
</script>
Your problem is how are you using the prop() function since this function does not return anything, and the addClass() function needs to be called from a jQuery object.
As you can see on the prop defintion it says:
Returns: Anything
This practice is called Chaining and in order to do Chaining functions those functions should return a jQuery Object.
More info
You can rewrite your line of code by something like this:
$('input[type="submit"]')
.addClass('animated pulse')
.prop('disabled', false);
Add seperately the addclass()
$(document).ready(function() {
$('input[type="submit"]').prop('disabled', true);
$('input[type="text"],input[type="email"],input[type="password"]').keyup(function() {
if($('#log_password').val() != '' && $('#log_email').val() != '')
{
$('input[type="submit"]').prop('disabled', false);
//add in next line
$('input[type="submit"]').addClass('animated pulse');
}
else{
$('input[type="submit"]').prop('disabled',true);
}
});
});

Disable button if no checkbox is checked jquery

I have a jquery function for multiple delete.
$('input.delete-selected[type="submit"]').attr('disabled','disabled');
$('[id^=partners_], [id^=invitations_], [id^=clients_], [id^=partner_services_], [id^=partner_products_]').on("click", function (event) {
if ($(this).is(":checked")) {
$('input.delete-selected[type="submit"]').removeAttr('disabled');
} else {
$('input.delete-selected[type="submit"]').attr('disabled', 'disabled');
}
})
The problem is, if I have 2 items, select both and then deselect one of them, the 'delete' button disables again.
How can I disable the button only if no checkbox is checked?
Do I have to implement an each function?
Use prop():
$('input.delete-selected[type="submit"]').prop('disabled', ($('[id^=partners_]:checked, [id^=invitations_]:checked, [id^=clients_]:checked, [id^=partner_services_]:checked, [id^=partner_products_]:checked').length == 0));
This will disable the button depending on the second parameter evaluation state.
If it is true, button will be disabled, if not button will be enabled.
$('[id^=partners_]:checked, [id^=invitations_]:checked, [id^=clients_]:checked, [id^=partner_services_]:checked, [id^=partner_products_]:checked').length will get the number of checkboxes checked.
Try this : get all checkbox selector in one variable and bind the click event to it. Inside click handler see if any of the checkbox is checked then enable / disable the button accordingly. Use .prop() instead of .attr()
$('input.delete-selected[type="submit"]').attr('disabled','disabled');
var $checkbox = $('[id^=partners_], [id^=invitations_], [id^=clients_], [id^=partner_services_], [id^=partner_products_]');
$($checkbox).on("click", function (event) {
$('input.delete-selected[type="submit"]').prop('disabled', $checkbox.is(':checked').length==0);
});
You can use a variable flag to count how much checkbox is checked, if atleast one is checked then remove disabling else you know.
$('input.delete-selected[type="submit"]').attr('disabled','disabled');
$('[id^=partners_], [id^=invitations_], [id^=clients_], [id^=partner_services_], [id^=partner_products_]').on("click", function (event) {
var flag = 0; //HERE IS THE VARIABLE
if ($(this).is(":checked")) {
flag += 1; //HERE
} else {
flag -= 1; //HERE
}
});
if(flag <= 0)
{
$('input.delete-selected[type="submit"]').attr('disabled', 'disabled');
}
else {
$('input.delete-selected[type="submit"]').removeAttr('disabled');
}
$('input.delete-selected[type="submit"]').attr('disabled','disabled');
$('[id^=partners_], [id^=invitations_], [id^=clients_], [id^=partner_services_], [id^=partner_products_]').on("click", function (event) {
if ($(this).siblings().andSelf().prop("checked").length > 0) {
$('input.delete-selected[type="submit"]').removeAttr('disabled');
} else {
$('input.delete-selected[type="submit"]').attr('disabled', 'disabled');
}
})

jQuery - Enable/Disable a button following checkboxes state

I'm using ASP.NET MVC 4 to develop a web app. I have a page which contains a submit button which should be enabled only if one of my two checkboxes (or both of them) is (are) enabled. The thing is, I'm trying to add an "or" operator in the following script but it does not give me what I want. So, here's my script :
The jQuery sample
And this is the part I'd like to improve :
$(document).ready(function() {
the_terms = $("#the-terms");
the_terms2 = $("#the-terms2");
the_terms.click(function() {
if ($(this).is(":checked")){
$("#submitBtn").removeAttr("disabled");
} else {
$("#submitBtn").attr("disabled", "disabled");
}
});
});
And I can't find a way to tell my document "Okay, if one of these 2 checkboxes (or both of them) is (are) checked, we can press on the button. If not, don't allow it".
Any idea guys?
It can be done with:
Fiddle
$('.checkbox').change(function(){
$('#submitBtn').prop('disabled', !$('.checkbox:checked').length > 0)
});
Note:
This find the checkboxes by class name checkbox so it will work with two checkboxes, whereas your original code is looking at a single checkbox via its ID.
Use the change event not click.
Simply use
$(".checkbox").click(function() {
$("#submitBtn").prop("disabled", !$('.checkbox:checked').length);
});
DEMO
$(document).ready(function() {
the_terms = $("#the-terms");
the_terms2 = $("#the-terms2");
$('.checkbox').change(function(){
$("#submitBtn").prop("disabled", !(the_terms.is(":checked") || the_terms2.is(":checked")));
});
});
// Make a function to be called on onload or on click
function checkTerm() {
jQuery('input[type="submit"]').attr('disabled',!jQuery('input.term:checked').length > 0 ) ;
}
// Call the function on load
$(document).ready(checkTerm) ;
// And call it on check change
jQuery(document).on('change','input.term',checkTerm) ;
Try below modified script , please check if it works as you want.
$(document).ready(function() {
the_terms = $("#the-terms");
the_terms2 = $("#the-terms2");
if(the_terms.is(":checked") || the_terms2.is(":checked"))
{
$("#submitBtn").removeAttr("disabled");
}
else
{
$("#submitBtn").attr("disabled", "disabled");
}
the_terms.click(function() {
if ($(this).is(":checked") || the_terms2.is(":checked")){
$("#submitBtn").removeAttr("disabled");
} else {
$("#submitBtn").attr("disabled", "disabled");
}
});
the_terms2.click(function() {
if ($(this).is(":checked") || the_terms.is(":checked") ){
$("#submitBtn").removeAttr("disabled");
} else {
$("#submitBtn").attr("disabled", "disabled");
}
});
});

Categories