jQuery Toggle/cycle through 3 state - javascript

I have a button, which i need to run through 3 state. eg: Mute, On and Off
<html>
<head>
<!-- define mute/on/off styles -->
<style type="text/css">
.mute{ background:gray }
.on { background:green }
.off { background:red }
</style>
<!-- define the toggle/cycle function -->
<script language="javascript">
function toggleState(item){
if(item.className == "mute") {
item.className="on";
} else if(item.className == "on") {
item.className="off";
} else {
item.className="mute";
}
}
</script>
</head>
<body>
<!-- call 'toggleState' whenever clicked -->
<input type="button" id="btn" value="button" class="mute" onclick="toggleState(this)" />
</body>
</html>
How can i cycle through this using jQuery rather using plain JavaScript

Try this:
var classNames = ['mute','on','off'];
$('div').click(function () {
$(this).toggleClass(function (i, className, b) {
var index = (classNames.indexOf(className) + 1) % classNames.length;
$(this).removeClass(className);
return classNames[index];
});
});
In this code, className is the old class. Then get the new class through classNames array, then return it.
And before return, the old class should be removed.
And with this method, you can easily expand 3 to any larger number.
Here is jsfiddle. http://jsfiddle.net/f3qR3/2/
Another situation
If there are other classes in the element, you can use the following code, but it is more complicated.
var classNames = ['mute', 'on', 'off'];
$('div').click(function () {
var $this = $(this);
$this.toggleClass(function (i, className, b) {
var ret_index;
$.each(classNames, function (index, value) {
if ($this.hasClass(value)) {
ret_index = (index + 1) % classNames.length;
}
});
$this.removeClass(classNames.join(' '));
return classNames[ret_index];
});
});
Here is jsfiddle. http://jsfiddle.net/f3qR3/4/

$("#btn").click(function(
var this=$(this);
if(this.hasClass('mute')) {
this.removeClass("mute").addClass("on");
} else if(this.hasClass('on')) {
this.removeClass("on").addClass("off");
} else {
this.removeClass("off").addClass("mute");
}
}
});
You don't need to add any onclick function, just placed it under jquery ready() function.

try this without using if and else ..
$('input[type=button]').click( function(){
var statemp = { mute: 'on', on: 'off', off :'mute' };
var toggle = $(this).attr('class')
.split(' ')
// Requires JavaScript 1.6
.map( function( cls ) {
return statemp[ cls ] || cls ;
})
.join(' ');
$(this).attr('class','').addClass( toggle );
});

Try
$(function(){
$('#btn').click(function(){
var $this = $(this);
if($this.is('.mute')) {
$this.toggleClass("mute on");
} else if($this.is('.on')) {
$this.toggleClass("on off");
} else if($this.is('.off')) {
$this.toggleClass("off mute");
}
})
})
Demo: Fiddle

function filterme(val){
if (val == 1){
$('#RangeFilter').removeClass('rangeAll').removeClass('rangePassive').addClass('rangeActive');
$("span").text("Active");
}
else if (val == 2)
{
$('#RangeFilter').removeClass('rangeActive').removeClass('rangePassive').addClass('rangeAll');
$("span").text("All");
}
else if(val==3){
$('#RangeFilter').removeClass('rangeAll').removeClass('rangeActive').addClass('rangePassive');
$("span").text("Passive");
}
}
<p class="range-field" style=" width:60px">
<input type="range" id="RangeFilter" name="points" onchange="filterme(this.value);" min="1" class="rangeAll" max="3" value="2">
</p>
<span>All</span>

Related

Css change on value change in input field. jQuery

var footerEmail = $('footer#footer input.email');
var footerEmailLength = footerEmail.val().length;
var footerEmailCaptcha = $("footer#footer .captcha-hide");
footerEmail.focus( function() {
footerEmailCaptcha.css("display","block");
});
footerEmail.blur( function() {
if(footerEmailLength > 0) {
footerEmailCaptcha.css("display","block");
}
else if (footerEmailLength == 0) {
footerEmailCaptcha.css("display","none");
}
});
.captcha-hide {
display:none;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.1/jquery.min.js"></script>
<footer id="footer">
<input class='email'>
<div class="captcha-hide">Testing</div>
</footer>
I want to make sure that onblur works when I enter something inside the text (input) field.
First if condition inside the blur function is not working since it is taking the value as '0' which will be initially. When I enter something and click outside of the input field then the css should be display:block
Please guide me how I can proceed further. I am new to jQuery/Javascript. Googling around to learn stuff.
you have to give the var footerEmailLength = footerEmail.val().length; inside blur function.
The blur function should be like this:
footerEmail.blur( function() {
var footerEmailLength = footerEmail.val().length;
if(footerEmailLength > 0) {
footerEmailCaptcha.css("display","block");
}
else if (footerEmailLength == 0) {
footerEmailCaptcha.css("display","none");
}
And if you use class as selector then change the footerEmail.val().length
to footerEmail[0].val().length.
The running code
var footerEmail = $('.email');
var footerEmailCaptcha = $(".captcha-hide");
footerEmail.focus( function() {
footerEmailCaptcha.css("display","block");
});
footerEmail.blur( function() {
var footerEmailLength = footerEmail[0].val().length;
if(footerEmailLength > 0) {
footerEmailCaptcha.css("display","block");
}
else if (footerEmailLength == 0) {
footerEmailCaptcha.css("display","none");
}
});
.captcha-hide {
display:none;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<footer id="footer">
<input class='email'>
<div class="captcha-hide">Testing</div>
</footer>

jQuery onChange() does not work…

so I tried making a simple on change fiddle. I can't get it to work. No matter what I do. WHY?
HTML CODE
<div id="status" style="display:none">0</div>
<button class="start">GO</button>
Javascript CODE
var cntTo = 2;
var cnt = 0;
$('#status').change( function() {
console.log('status changed');
if ($(this).text() == '1'){
if(cnt <= cntTo){
getNext(cnt);
}
}
});
$('.start').click(function(){
console.log('start clicked');
console.log('text of status now: ' + $('#status').text());
if($('#status').text() != '1'){
console.log('setting text');
$('#status').text('1');
console.log('text of status now: ' +$('#status').text());
}
});
function getNext(cnt){
$('#status').text('0');
console.log('getting details');
}
https://jsfiddle.net/hakz47vg/
The .change() function is limited to input, textarea, and select.
Source: https://api.jquery.com/change/
Use this
$('#status').bind("DOMSubtreeModified",function(){
var cntTo = 2;
var cnt = 0;
$(document).ready(function() {
$('.start').click(function() {
if ($('#status').text() != '1') {
$('#status').text('1');
}
});
$('#status').bind("DOMSubtreeModified",function(){
console.log('fired');
if ($(this).text() == '1') {
if (cnt <= cntTo) {
getNext(cnt);
}
}
});
});
function getNext(cnt) {
$('#status').text('0');
console.log('getting details');
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="status" style="">0</div>
<button class="start">GO</button>
You can embed onchange function code directly with GO button click event like this:
$('.start').click(function(){
if($('#status').text() != '1'){
$('#status').text('1');
}
else
{
if(cnt <= cntTo){
getNext(cnt);
}
}
});
You are using change event which does not watch or respond to div content.Use DOMSubtreeModified event and trigger action on that event.
var cntTo = 2;
var cnt = 0;
$('#status').on("DOMSubtreeModified", function() {
if ($(this).text() == '1') {
if (cnt <= cntTo) {
getNext(cnt);
}
}
});
$('.start').click(function() {
if ($('#status').text() != '1') {
console.log('setting text');
$('#status').text('1');
console.log('text of status now: ' + $('#status').text());
}
});
function getNext(cnt) {
$('#status').text('0');
console.log('getting details');
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="status" style="display:none">0</div>
<button class="start">GO</button>
If you want to do some action when the content modified inside the div element you have to use the event called DOMSubtreeModified like below.
$("body").on('DOMSubtreeModified', "#status", function() {
UPDATED FIDDLE
Reference:
For more information read out the thread already discussed about this in stack overflow.
jQuery Event : Detect changes to the html/text of a div
Use DOMSubtreeModified event
DOMSubtreeModified This is a general event for notification of all changes to the document. It can be used instead of the more specific mutation and mutation name events. Reference
$('#status').bind("DOMSubtreeModified",function(){
alert('changed');
});
Working fiddle
another simple solution
when text in #text changes in script fires a trigger and you can bind it to change event
var cntTo = 2;
var cnt = 0;
$('#status').bind('change', function () {
console.log('fired');
if ($(this).text() == '1'){
if(cnt <= cntTo){
getNext(cnt);
}
}
});
$('.start').click(function(){
if($('#status').text() != '1'){
$('#status').text('1');
$('#status').trigger('change');
}
});
function getNext(cnt){
$('#status').text('0');
console.log('getting details');
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="status" style="display:none">0</div>
<button class="start">GO</button>
$("start").click function put inside in ready Function

checkbox oncheck javascript

I have a checkbox That I need to show a div when it is clicked. I have 3 different javascripts that i have attempted to get this to work with.
//function showhide() {
// var checkbox = document.getElementById("assist");
// var expanded1 = document.getElementById("expanded");
// var expanded2 = document.getElementById("expanded2");
// expanded1.style.visibility = (expanded1.style.visibility == 'false') ? "true" : "false";
// alert('test');
//}
function(){
var checkbox = document.getElementById("assist");
var expanded1 = document.getElementById("expanded");
var expanded2 = document.getElementById("expanded2");
checkbox.onchange = function () {
expanded1.style.visibility = this.checked ? 'true' : 'false';
alert('test');
}
//function check() {
// $('chk').click(function () {
// if (this.checked) {
// $("#expanded").show();
// $("#expanded2").show();
// }
// else {
// $("#expanded").hide();
// $("#expanded2").hide();
// }
// });
//}
This is the checkbox below.
<input type="checkbox" runat="server" id="assist" onclick="showhide();" /></div>
The divs that need to be shown/hidden are expanded and expanded2.
I cannot get the javascript functions to be hit from the checkbox could someone tell me what is wrong.
Use the window.onload event to assign the change handler and remove the inline onclick from the HTML. Also the visibility CSS should be visible or hidden.
Fiddle
window.onload = function () {
var checkbox = document.getElementById("assist");
var expanded1 = document.getElementById("expanded");
checkbox.onchange = function () {
expanded1.style.visibility = this.checked ? 'visible' : 'hidden';
};
};
For Hiding the DIV using Jquery you can try below code:
instead of this.checked use $(this).is(':checked')
$('.chk').click( function () {
var $this = $(this);
if( $this.is(':checked') == true ) {
$("#div1").show();
} else {
$("#div1").hide();
}
});
html
<input type="checkbox" runat="server" id="assist" onclick="showhide();" />
<div class="required1" id="mycheckboxdiv1" style="display:none" >
your code;
</div>
this will do for u :)
jquery
<script>
$(document).ready(function() {
$('#mycheckboxdiv1').hide();
$('#assist').click(function(){
if($('#assist').is(':checked')){
$('#mycheckboxdiv1').toggle();
}
else
{
$('#mycheckboxdiv1').hide();
}
});
});
</script>
http://jsfiddle.net/maree_chaudhry/QmXCV/ here is fiddle
You're already using jQuery, so you could just use:
$("#assist").change(function(){
$("#expanded, #expanded2").toggle();
});
jsFiddle here

Adding keyup events to dynamically generated elements using jquery

I have a button which creates text boxes dynamically and there is another button 'Clear'.
If there is no text in any of the text field then the clear button is disabled or else it will be enabled. It works for the text box that is created when the dom is loaded but for the dynamically created textboxes it does not work.
Here is the HTML
<input type="button" value="Click Me" class="a" />
<input type="button" value="Clear" class="a" id="clearBasicSearch" />
<div id="basicSearchFields">
<input type="text" />
</div>
Javascript
$(".a").click(function () {
$("#basicSearchFields").append("<input type='text' class='b' />");
});
/*$(".b").live("keyup", function () {
//alert('you pressed ' + $(this).val());
$(this).val($(this).val().toUpperCase());
});*/
var toValidate = $("#basicSearchFields input[type='text']");
$("#clearBasicSearch").removeClass('hidden').removeClass('button').attr('disabled', true);
toValidate.live('keyup', function () {
console.log("hi");
var valid = false; //default is false
toValidate.each(function () {
if ($(this).val().length > 0) {
valid = true; //non-empty element found
return false; //break
}
});
$("#clearBasicSearch").attr('disabled', !valid).toggleClass('button', valid);
});
JSfiddle link - http://jsfiddle.net/TpExS/
Please help me out!!
Try this
$(document).on('keyup', "#basicSearchFields input[type='text']",function () {
console.log("hi");
var valid = false; //default is false
var toValidate = $("#basicSearchFields input[type='text']");
toValidate.each(function () {
if ($(this).val().length > 0) {
valid = true; //non-empty element found
return false; //break
}
});
$("#clearBasicSearch").attr('disabled', !valid).toggleClass('button', valid);
});
$(document).on('keyup', "input#basicSearchFields",function () {
// do something here
}
Here is another possible solution http://jsfiddle.net/TpExS/2/
Note: JQuery 2.0.2 used
Javascript
$(document).ready(function(){
var fields = $('input[class=b]');
for(var i = 0; i < fields.length; i++){
$(fields[i]).on('keyup', validateFields);
}
});
$(".a").click(function () {
var newField = $('<input/>').attr('type', 'text').attr('class', 'b');
$(newField).on('keyup', validateFields);
$("#basicSearchFields").append(newField);
});
function validateFields(){
if($(this).val().length){
$('#clearBasicSearch').attr('disabled', false);
return;
}
$('#clearBasicSearch').attr('disabled', true);
var fields = $('input[class=b]');
for(var i = 0; i < fields.length; i++){
if($(fields[i]).val().length){
$('#clearBasicSearch').attr('disabled', false);
return;
}
}
}
Try
$("#basicSearchFields").delegate("input[type='text']", 'keyup', function () {
validate();
});
function validate(){
console.log("hi");
var valid = false; //default is false
var toValidate = $("#basicSearchFields input[type='text']");
toValidate.each(function () {
if ($(this).val().length > 0) {
valid = true; //non-empty element found
return false; //break
}
});
$("#clearBasicSearch").attr('disabled', !valid).toggleClass('button', valid);
}
Demo: Fiddle
Simple, Updates your global "toValidate" variable when you add more elementson the click.
$(".a").click(function () {
$("#basicSearchFields").append("<input type='text' class='b' />");
toValidate = $("#basicSearchFields input:text");
});
Why? The time you set toValidate, it will return an array at that moment, you should updates it in each time there are new elements, or check for all of then inside the live event.

Check for the class in an element

If there is an element with the class myclass in the #main element, I want to alert ok but in my example it always shows no, how can fix this?
Demo: http://jsfiddle.net/mF2K6/1/
<form>
<div id="main">
<div class="myclass"></div>
</div>
<button>Click Me</button>
</form>
$('button').live('click', function (e) {
e.preventDefault();
//var copy_html = $('#main').clone();
//if ($('#main').hasClass('myclass')) {
if ($('#main').is('.myclass')) {
alert('ok');
} else {
alert('no');
}
})
To check sub-elements for myclass, use this:
if ($('#main').find('.myclass').length != 0)
or this:
if ($('#main .myclass').length != 0)
Your <div id="main"> does not have myclass class, only one of its children has it.
You can check the latter with the following code:
if ($("#main .myclass").length > 0) {
alert('ok');
} else {
alert('no');
}
Something like this should help:
$("button").click(function () {
window.alert(isClassPresent() ? "Yes" : "No");
});
function isClassPresent() {
return $("#main .myclass").length > 0;
}
this will work fine:jsfiddle
var main=$("#main");
$("button").click(function(){
if(!!main.find(".myclass").length){
alert("ok");
}else{
alert("no");
};
});
[0]is method can't to compare different doms!
[1]why must use live?
[2]cache main(jQuery Object) is more efficient.select only ones.

Categories

Resources