JavaScript - jQuery toggle option - javascript

I have a script to execute some tasks based on an option variable. Option has a default value 1. The value can be toggled by clicking some links. Then a set of operations are set, for that operations to execute. The sample layout will be like;
HTML
<a id="opt1">1</a><br><a id="opt2">2</a><br><a id="opt3">3</a><br>
<div id="mydiv">option1</div>
JS
var opt=1;
$('#opt1').click(function() {
opt=1;
});
$('#opt2').click(function() {
opt=2;
});
$('#opt3').click(function() {
opt=3;
});
if(opt == 1){
$('#mydiv').text("option1");
}else if(opt == 2){
$('#mydiv').text("option2");
}else{
$('#mydiv').text("option3");
}
JS is wrapped inside document ready function. The sample is meant to change text according to option variable. Sorry that the tasks cannot be nested inside .click(function() and are purely depend on option value. How can I achieve this?
here is the fiddle http://jsfiddle.net/Naw3y/

problem is your if condition is called just once on document.ready.. make a function , add your condition and call that function in click event
var opt=1;
$('#opt1').click(function() {
opt=1;
divText(opt); //calling divText(1) is shorter :)
});
$('#opt2').click(function() {
opt=2;
divText(opt)
});
$('#opt3').click(function() {
opt=3;
divText(opt)
});
function divText(opt){
if(opt == 1){
$('#mydiv').text("option1");
}else if(opt == 2){
$('#mydiv').text("option2");
}else{
$('#mydiv').text("option3");
}
}
not sure why aren't you calling straight away .. without if and function.. but here you go
$('#opt1').click(function() {
$('#mydiv').text("option1");
});
$('#opt2').click(function() {
$('#mydiv').text("option2");
});
$('#opt3').click(function() {
$('#mydiv').text("option3");
});
fiddle here
fiddle for second option

This should do the trick: http://jsfiddle.net/Naw3y/6/:
var opt = 1;
$(function() {
$('#opt1').click(function() {
opt=1;
changeText();
});
$('#opt2').click(function() {
opt=2;
changeText();
});
$('#opt3').click(function() {
opt=3;
changeText();
});
});
function changeText(){
if(opt == 1){
$('#mydiv').text("option1");
}else if(opt == 2){
$('#mydiv').text("option2");
}else{
$('#mydiv').text("option3");
}
}

I think what you need in your situation is 'encapsulation' of your property, and this is what the other answers lack:
var opt;
//setter function for opt that does the div update
function setOpt(value) {
opt = value;
$('#mydiv').text('option' + value);
}
$(document).ready(function() {
//bind click handlers
$('#opt1').click(function() {
setOpt(1);
});
$('#opt2').click(function() {
setOpt(2);
});
$('#opt3').click(function() {
setOpt(3);
});
//set default value
setOpt(1);
});

$(document).ready(function(){
$('a').click(function(){
$('#mydiv').text('option'+$(this).html());
});
});
Sorry If i didnt understand your question well.. try to explain better..

Related

jQuery Show image in a div with a third click

function () {
var i = 0;
$('.class').click(i=i+1)
if(i=3) {
$('.class2').css('display','block');
}
}
This code does not work, Please help me.
Should be :
$(function() { //ready function
var i = 0;
$('.class').click(function(){ //Attach click event to '.class'
i=i+1; //Or i++;
if(i===3) { //Use triple equal '===' for comparaison
$('.class2').css('display','block');
}
})
})
Hope this helps.
You should bind your click event outside the function, and then track the 3rd click. You should also use a comparison operator instead of assignment. Of course, all of this should be wrapped in document ready.
var i = 0;
$('.class').on('click', function() {
i = i + 1;
if(i === 3) {
$('.class2').css('display','block');
}
});
Here is a Fiddle Demo.

firing the second .click function

I think this is very newbie question but is it possible to have 2 separate function on a .click on 1st and 2nd click?
$(div).click(function(){
alert("1st click");
},
function(){
alert("2nd click");
});
http://jsfiddle.net/2xe8a/
Or is there any suggestion that would separate that function?
Thanks guys!
Sure, just set something when clicked the first time and check it the second time
$('div').click(function(){
var clicked = $(this).data('clicked');
if ( clicked ) {
alert('the rest of the time');
}else{
alert('first time');
}
$(this).data('clicked', !clicked);
});
FIDDLE
One way would be to unbind on the first click:
function click1 () {
alert('1st click');
$(this).off('click', click1).on('click', click2);
}
function click2 () {
alert('2nd click');
}
$(function () {
$('#click').on('click', click1);
});
Updated JSFiddle: http://jsfiddle.net/2xe8a/1/
Another option would be to use a wrapper method to determine which method is supposed to fire:
function click1 () {
alert('1st click');
}
function click2 () {
alert('2nd click');
}
$(function () {
$('#click').data('clicks', 0).on('click', function () {
var $this = $(this),
clicks = $this.data('clicks') + 1;
switch (clicks) {
case 1: click1.call(this); break;
case 2: click2.call(this); break;
}
$this.data('clicks', clicks);
});
});
Updated JSFiddle: http://jsfiddle.net/2xe8a/6/
Edit: As per Juhana's suggestion, a 3rd option might look like this:
function click2 () {
alert('2nd click');
}
$(function () {
$('#click').one('click', function () {
alert('1st click');
$(this).one('click', click2);
});
});
JSFiddle Link: http://jsfiddle.net/2xe8a/8/
If you only want each function to happen once, you can use one instead of on (and, I always use something like on('click') instead of the shortcut click() method):
$("#click").one('click', function(){
alert("1st click");
$("#click").one('click', function(){
alert("2nd click");
});
});
If you need a little more control over which one fires, you can use on and then off to unbind the event handlers:
$("#click").on('click', function(){
alert("1st click");
$("#click").off('click');
$("#click").on('click', function(){
alert("2nd click");
$("#click").off('click');
});
});
If you want to do it with variables, you could do:
var firstClick = true;
$("#click").on('click', function(){
if (firstClick) {
alert("1st click");
firstClick = false;
}
else {
alert("2nd click");
}
});
I am unsure of what exactly you are trying to do.
If you are trying to have the 2nd function execute every 2nd click (i.e even number of clicks), and execute the 1st function on the odd number of clicks, then why not use a counter?
This is a very simple example but I think it illustrates the principle:
var count = 0;
$("#click").click(function(){
if (count % 2 === 0) {
oddNumberOfClicks();
}
else {
evenNumberOfClicks();
}
count++;
});
function oddNumberOfClicks() {
alert('Doing some work for odd');
}
function evenNumberOfClicks() {
alert('Doing some work for even');
}
http://jsfiddle.net/2xe8a/4/
Using an incrementing variable?
clicks = 0;
$(div).click(function(){
clicks = clicks +1; // clicks++
if ( clicks == 1 ) {
alert("1st click");
} else if ( clicks == 2 ) {
alert("2nd click");
} else {
//...
}
});
(function(){
var count = 0;
$("#click").click(function(e){
if(count % 2 == 0){
count++;
alert(1);
// first click
}else{
count++;
alert(2);
// second click
}
});
});
Using a counter.
FIDDLE
P.S. This thing can be done without jQuery. http://youmightnotneedjquery.com/
Simple way:
var t = false;
$("#click").click(
function(){
if(!t){
alert("1st click");
t = true;
} else {
alert("2st click");
}
}
);
Fiddle:
http://jsfiddle.net/2xe8a/9/
By 2nd click do you mean a double click? If so, there is a double click method in jQuery:
$(div).dblclick( function() {
alert("asdf");
});

jQuery issue with conditions

I have two anchor links One is Like and Second is Favorite Now I am trying get alert when user click to specific option.
If user click to Like option alert('Like Clicked');
or
If user click to Favorite option alert('Favorite Clicked');
but something is wrong and getting multiple alerts with Like and Favorite.
Whats wrong with my code I can't understated.
MY JS WORK:
$(window).load(function(){
$('.ovrly a').click( function () {
var getImageID = $(this).attr("id"); //class name with id
if($(".like").children("."+getImageID)) {
alert('Like Clicked');
}
if($(".fav").children("."+getImageID)) {
alert('Favourite Clicked');
}
});
});
MY HTML WORK:
<div class="ovrly">
<span class="like">
<a class="like_32" id="like_32" href="javascript:void(0);">Like</a>
<p class="likeCount_32">
15
</p>
</span>
<span class="fav">
<a class="favourite_32" id="favourite_32" href="javascript:void(0);">Favourite</a>
<p class="favouriteCount_32">
09
</p>
</span>
</div>
My Sample JS FIDDLE
My Sample Code With Ajax Code:
<script type="text/javascript">
// like and favourite ajax script
$(function () {
$('.load_more_ctnt .ovrly a').live("click", function () {
var getImageID = $(this).attr("id"); //class name with id
var getID = getImageID.replace(/[^0-9]+/g, ""); //only id
var getOptionName = getImageID.replace(/[^A-Za-z]+/g, ""); //only id
//alert(getImageID);
$(document).ajaxStart(function() {
if($(".like").children("."+getImageID).length > 0) {
alert('Like Clicked');
}
if($(".fav").children("."+getImageID).length > 0) {
alert('Favourite Clicked');
}
}).ajaxStop(function() {
if($(".like").children("."+getImageID).length > 0) {
alert('Like Clicked');
}
if($(".fav").children("."+getImageID).length > 0) {
alert('Favourite Clicked');
}
});
if (getImageID) {
$.ajax({
type: "POST",
url: "<?php echo URL; ?>home/passImageID",
data: "getImageID=" + getImageID,
success: function (html) {
$("#" + getImageID).removeAttr("id");
if(html == 'like'){
$("." + getImageID).addClass( "iplike" );
var incrementBy1 = $(".likeCount_" + getID).text();
var tempLikeNewValue = +incrementBy1+1;
$(".likeCount_" + getID).text("");
$(".likeCount_" + getID).text(tempLikeNewValue);
}else{
$("." + getImageID).addClass( "ipfav" );
var incrementBy1 = $(".favouriteCount_" + getID).text();
var tempFavNewValue = +incrementBy1+1;
$(".favouriteCount_" + getID).text("");
$(".favouriteCount_" + getID).text(tempFavNewValue);
}
}
});
} else {
//$(".more_tab").html('The End');
}
return false;
});
});
</script>
I think you need .is().
Check the current matched set of elements against a selector, element, or jQuery object and return true if at least one of these elements matches the given arguments.
Code
$('.ovrly a').click(function () {
if ($(this).is(".like_32")) {
alert('Like Clicked');
}
if ($(this).is(".favourite_32")) {
alert('Favorite Clicked');
}
});
DEMO
reference hasClass()
$('.ovrly').on('click','a',function () {
if ($(this).hasClass("like_32")) {
alert('Like Clicked');
}
if ($(this).hasClass("favourite_32")) {
alert('Favorite Clicked');
}
});
DEMO
$(".like").children("."+getImageID) the code provide you children element selector object, for the exist check, you can use langth.
if($(".like").children("."+getImageID).length > 0) {
alert('Like Clicked');
}
Your problem is that both conditions are always true!
$(".like").children("." + getImageID)
$(".fav").children("." + getImageID)
You are not comparing anything. Both statements return true since both elements exists in your page.
use length in jquery
if ($(".like").children("." + getImageID).length > 0) {
alert('Like Clicked');
}
if ($(".fav").children("." + getImageID).length > 0) {
alert('Favorite Clicked');
}
Fiddle
Another option...
$('#favourite_32').click(function () {
alert('Favorite Clicked');
});
$('#like_32').click(function () {
alert('Like Clicked');
});
your approach is correct, but you have little bit diverted from basic concept.
$(".like").children("."+getImageID) and $(".fav").children("."+getImageID) both are returning object.
In case, when you click on like then
$(".like").children("."+getImageID) return a object of array that have element.
$(".feb").children("."+getImageID) return a object of array that are empty.
but in both case there is object of array and for a object of array if condition is always true.
try to execute on js console :
if([]){
console.log("it will print that condition is true")
}
then you alwaye find:
it will print that condition is true
You would have use for correct working.
if($(".like").children("."+getImageID).length>0){
}
and
if($(".like").children("."+getImageID).length > 0){
}

jquery/javascript: adding an else statement?

I am trying to add an else statement to this piece of javascript so that if a div-1 is clicked once it shows div-2 and if div-1 is clicked again it hides div-2.
Does anyone know how I could do this?
$(function() {
$('.div-1').click(function() {
$('.div-2').show();
return false;
});
});
Try toggle() instead:
$('.div-1').click(function() {
$('.div-2').toggle();
return false;
});
You can add a dummy class and check for it's exixtence.
$(function() {
$('.div-1').click(function() {
var $this = $(this),
$div2 = $('.div-2');
if($this.hasClass('open')) {
$this.removeClass(open');
$div2.hide();
} else {
$this.addClass(open');
$div2.show();
}
return false;
});
});
I totally agree with Jason P's answer that you should be using toggle instead, but in case you actually needed to use an if statement, you can do this:
$('.div-1').click(function() {
if ($('.div-2').is(':visible')) {
$('.div-2').hide();
} else {
$('.div-2').show();
}
return false;
});
jsFiddle

How to set previous value when cancelling a drop-down list change event

I am designing a html page.
I want to show a confirmation msg on changing a drop down element using jquery or javascript.
Please help to do this.
I have code which will ask confirmation. On selecting cancel it will not select previous item of Drop down.
$("#dropdownId").change(function(e)
{
if($(this).val() == "40")
{
if(confirm("Are you sure"))
return true;
else
return false;
}
});
Thanks
You should be able to store the previous value on the click event and set it back on the change event:
var setLastSelected = function(element) {
$(element).data('lastSelected', $(element).find("option:selected"));
};
$("select").each(function () {
setLastSelected(this);
});
$("select").change(function(){
if(confirm("Are you sure")) {
setLastSelected(this);
return true;
}
else {
$(this).data('lastSelected').attr("selected", true);
return false;
}
});
See: http://jsfiddle.net/w9JYX/14/
Update: I updated the code to work more generically on a set of dropdown controls and also removed the click handler.
Here's a bit tighter solution along the same lines without having to create global variables or other functions:
$('#dropdownId')
.on('focus', function () {
$(this).data("prev", $(this).val());
})
.change(function () {
if (confirm('Are you sure?')) {
//normal case where the dropdown changes
$(this).data("prev", $(this).val());
} else {
//if the user doesn't confirm reset the dropdown back to what it was
$(this).val($(this).data("prev"));
}
});
var previous_option = $('#dropdownId option:selected');
$("#dropdownId").change(function(e){
var $this = $(this),
selected = $this.find('option:selected');
if($this.val() == "40"){
if(confirm("Are you sure")){
previous_option = selected;
return true;
} else{
selected.removeAttr('selected');
previous_option.attr('selected', 'selected');
}
} else{
previous_option = selected;
}
});
Usage for ASP.NET page:
$("#<%= dropdownId.ClientID %>")
.on('focus', function () {
$(this).data("prev", $(this).val());
})
.change(function () {
if (confirm('Are you sure?')) {
$(this).data("prev", $(this).val());
} else {
$(this).val($(this).data("prev"));
}
});

Categories