Get the value/solution from an comparison in an if-statement - javascript

I have a comparison in my if statement to check if the id's are identical, but I want to detect the B element who has the same id as the A element and give him a class. You can see the problem in this script:
jQuery('.button').click(function() {
var a = jQuery('.a').attr('id')
var b = jQuery('.b').attr('id')
if (a === b) {
// "jQuery(this)" should be the detectet B-element, which has the same "id" as A
// ↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓
jQuery(this).addClass("active");
jQuery(this).css("background", "red");
// But it detects the button as "jQuery(this)"
} else {
return;
}
});
.a,
.b,
.c {
width: 100px;
height: 100px;
margin: 1em;
background: blue;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
Button
<div class="a" id="block">A</div>
<div class="b" id="block">B</div>
<div class="c" id="notblock">C</div>
Thanks for helping!

Here is the optimised code that you can have a look at. Instead of ID, you can use data attributes:
jQuery('.button').click(function() {
var a = jQuery('.a').data('check');
var $belement = jQuery('.b');
var b = $belement.data('check');
if (a === b) {
$belement.addClass("active").css("background", "red");
}
});
.a,
.b,
.c {
width: 100px;
height: 100px;
margin: 1em;
background: blue;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
Button
<div class="a" id="block-a" data-check="block">A</div>
<div class="b" id="block-b" data-check="block">B</div>
<div class="c" id="notblock" data-check="notblock">C</div>
Ideally, DOM should never have same IDs. IDs are unique, classes can be same. And hence, your entire logic or question is kinda incorrect. You should rather compare some value or other attributes, but never IDs. IDs can't be compared as they are supposed to unique.

Try this : you need to get b element jquery object, here jQuery(this) is the button you clicked
jQuery('.button').click(function() {
var a = jQuery('.a').attr('id');
var $belement = jQuery('.b');
var b = $belement.attr('id')
if (a === b ) {
// "jQuery(this)" should be the detectet B-element, which has the same "id" as A
// ↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓
$belement.addClass("active");
$belement.css("background", "red");
// But it detects the button as "jQuery(this)"
}
else {
return;
}
});
.a, .b, .c {
width: 100px;
height: 100px;
margin: 1em;
background: blue;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
Button
<div class="a" id="block">A</div>
<div class="b" id="block">B</div>
<div class="c" id="notblock">C</div>

jQuery('.button').click(function() {
var a = jQuery('.a').attr('id')
var b = jQuery('.b').attr('id')
if (a === b ) {
// "jQuery(this)" should be the detectet B-element, which has the same "id" as A
// ↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓
jQuery('.b').addClass("active");
jQuery('.b').css("background", "red");
// But it detects the button as "jQuery(this)"
}
else {
return;
}
});
Add the class to the element.

Related

Get and put paramter to url based on slected data using jQuery

I have a following <div> structure:
<div class="color-class" data-color="red">
<div class="inside-color">Red</div>
</div>
<div class="color-class" data-color="green">
<div class="inside-color">Green</div>
</div>
<div class="color-class" data-color="blue">
<div class="inside-color">Blue</div>
</div>
So, when people click on any color class then the page is redirected with corresponding color in the url with the following:
var color=urlObj.searchParams.get("color");
$(".color-class").on("click",function(){
if( $(this).find(".inside-color").hasClass("selected")){
location.href=location.href.replace(/&?color=([^&]$|[^&]*)/i, "");
}
else {
var se_val=$(this).data("color");
$(this).find(".inside-color").addClass("selected");
if ( !color ){
if(url.indexOf("?") >= 0){
url =url+"&color="+se_val;
}
else {
url =url+"?color="+se_val;
}
window.location.href=url;
return;
}
if ( color){
urlObj.searchParams.set("color", color+","+se_val);
window.location.href=urlObj;
return;
}
}
});
So using this code i can redirect so after my redirection i get url like example.com/?color=red
Then I have to add class name called selected to the corresponding inside-color.
So I write the following code:
if ( color ){
$(".color-class[data-color='"+color+"']").find(".inside-color").addClass("selected");
}
But if my url is http://www.example.com/?color=red%2Cgreen how i can add selected class to both… ie add selected class to both red and green,
If my url is http://www.example.com/?color=red%2Cgreen and some one again click on green color then how can i remove green from the url and add selected to red color only.
Any Help will be appreciated.
Consider if this was a form, you might have something like:
<form action="example.com" method="get">
<input type="checkbox" class="inside-color" name="inside-color[]" value="red" /><label>Red</label>
<input type="checkbox" class="inside-color" name="inside-color[]" value="green" /><label>Green</label>
<input type="checkbox" class="inside-color" name="inside-color[]" value="blue" /><label>Blue</label>
<button type="submit">Go</button>
</form>
This will create an encoded URL like:
example.com?inside-color%5B%5D=red&inside-color%5B%5D=green
This is the method for passing an Array via GET. one option would be to pass the details in this method and parse it. Doing this will result in a small array and you can then iterate the array set selected on each of the specific colors.
In your example, you are passing a single string in one variable, and using a delimiter. Sp you'd need to first get the string and then split it. Again, this will result in an array that can be iterated.
if the user unchecked one of the options, removing selected, you could then remove that element from the array.
My suggestions:
function setSelections(c) {
$.each(c, function(k, v) {
if (v) {
$(".color-class[data-color=" + k + "]").addClass("selected");
}
});
}
$(function() {
var colors = {
red: 0,
green: 0,
blue: 0
};
$(".color-class").click(function() {
if ($(this).hasClass("selected")) {
$(this).removeClass("selected");
colors[$(this).attr("data-color")] = 0;
} else {
$(this).addClass("selected");
colors[$(this).attr("data-color")] = 1;
}
});
$("#save-selection").click(function(e) {
e.preventDefault();
var url = "http://example.com/?" + $.param(colors);
console.log("URL: " + url);
})
});
.color-class {
width: 40px;
height: 40px;
border: 2px solid #ccc;
border-radius: 4px;
margin: 2px;
}
.color-class:hover {
border-color: #a0a0a0;
}
.color-class.selected {
border-color: #202020;
}
.color-class .inside-color {
border-radius: 3px;
width: 100%;
height: 70%;
color: white;
font-size: 75%;
text-align: center;
padding-top: 30%;
}
.color-class .inside-color.red {
background: red;
}
.color-class .inside-color.green {
background: green;
}
.color-class .inside-color.blue {
background: blue;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="color-class" data-color="red">
<div class="inside-color red">Red</div>
</div>
<div class="color-class" data-color="green">
<div class="inside-color green">Green</div>
</div>
<div class="color-class" data-color="blue">
<div class="inside-color blue">Blue</div>
</div>
<button id="save-selection">Save</button>
The console shows: URL: http://example.com/?red=1&green=1&blue=0 This will be easier to parse back into an object that can be used with setSelections() function.
Hope that helps.
ok try something like this i am just posting some part of your code
var color=urlObj.searchParams.get("color");
if ( color ){
var splitColors = color.split('%2C');
for(var i=0;i<splitColors.length;++i)
{
$(".color-class[data-color='"+splitColors[i]+"']").find(".inside-color").toggleClass("selected");
}
}

Remove (and Add) Classes to HTML Element with jQuery, While Updating the DOM tree

I'm trying to change a div's attribute class. I have three defined classes and want to cycle through the classes when a user initiates a click event. The first click event works as expected, but the second doesn't show any results.
I've went through a few iterations of trying to get this to work, but have not had any success. I think what's going on is that the DOM tree isn't being updated with the click event, so when the second click event is fired it sees the card-green class, adds the card-yellow class and then exits the branching logic.
$(document).ready(function() {
$('body').on('click', function(event) {
var cardColors = ['card-green', 'card-yellow', 'card-red'];
if ($(event.target.nodeName).attr('class') == 'card-green') {
$(event.target.nodeName).removeClass(event.target.nodeName.className).addClass(cardColors[1]);
} else if ($(this).attr('class') == 'card-yellow') {
$(event.target.nodeName).removeClass(event.target.nodeName.className).addClass(cardColors[2]);
} else {
$(event.target.nodeName).removeClass(event.target.nodeName.className).addClass(cardColors[0]);
}
})
});
Use a switch and toggleClass(). Details are commented in Snippet. No need for an array if you are using a limited number of options. When using $(this) you don't need to keep track of what you clicked (much like event.target except $(this) isn't concerned about events as it is concerned with owner of function.)
SNIPPET
$(document).ready(function() {
$(document).on('click', 'div', function(event) {
/* Determine $(this) class
|| Pass class through the switch
*/
var color = $(this).attr('class');
/* Each part of the switch is a if/else
|| conditional. If the condition isn't
|| met, then it will kick you
|| down to the next conditional and
|| so on, until you reach default or
|| meet a condition in which case the
|| break will kick you out of switch.
|| Each condition has a toggleClass()
|| method to switch colors according
|| to the present class of div
*/
switch (color) {
case 'green':
$(this).toggleClass('green yellow');
break;
case 'yellow':
$(this).toggleClass('yellow red');
break;
case 'red':
$(this).toggleClass('red green');
break;
default:
break;
}
});
});
div {
height: 30px;
width: 50px;
border: 1px solid black;
cursor: pointer;
}
.green {
background: green
}
.red {
background: red;
}
.yellow {
background: yellow
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class='green'></div>
<div class='green'></div>
<div class='green'></div>
<div class='green'></div>
<div class='green'></div>
<div class='green'></div>
<div class='green'></div>
<div class='green'></div>
<div class='green'></div>
<div class='green'></div>
<div class='green'></div>
<div class='green'></div>
<div class='green'></div>
<div class='green'></div>
<div class='green'></div>
<div class='green'></div>
<div class='green'></div>
<div class='green'></div>
<div class='green'></div>
<div class='green'></div>
<div class='green'></div>
This changes the color in order of the cards array when elements within the document body are clicked:
(Very similar to #gyre's answer, only includes the event.target within the code logic, rather than just the body).
var cards = ['card-green', 'card-yellow', 'card-red'];
$('body').on('click', function() {
var elem = event.target,
curClass = $(elem).attr('class'),
i = cards.indexOf($(elem).attr('class'));
$(elem)
.removeClass(curClass)
.addClass(cards[i = (i + 1) % cards.length]);
});
div {
height: 100px;
width: 100px;
display: inline-block;
}
.card-green {
background-color: green;
}
.card-yellow {
background-color: yellow;
}
.card-red {
background-color: red;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="foo" class="card-green"></div>
<div id="bar" class="card-yellow"></div>
<div id="baz" class="card-red"></div>
Use an additional index variable to keep track of the position in the array:
Demo Snippet:
$(document).ready(function() {
var cardColors = ['card-green', 'card-yellow', 'card-red']
var i = 0
$('body').on('click', function() {
$(this)
.removeClass(cardColors[i])
.addClass(cardColors[i = (i + 1) % cardColors.length])
})
})
body {
width: 100vw;
height: 100vh;
margin: 0;
padding: 0;
}
.card-green { background-color: green; }
.card-yellow { background-color: yellow; }
.card-red { background-color: red; }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
The same code is workable just remove nodeName from removeClass(event.target.nodeName.className) instead of this use removeClass(event.target.className).
Try this, Its working for me.
$(document).ready(function() {
$('body').on('click', function(event) {
var cardColors = ['card-green', 'card-yellow', 'card-red'];
alert(event.target.className)
if ($(event.target.nodeName).attr('class') == 'card-green') {
$(event.target.nodeName).removeClass(event.target.className).addClass(cardColors[1]);
} else if ($(this).attr('class') == 'card-yellow') {
$(event.target.nodeName).removeClass(event.target.className).addClass(cardColors[2]);
} else {
$(event.target.nodeName).removeClass(event.target.className).addClass(cardColors[0]);
}
})
});

Tie children of one div to children of another div with jquery

I have two parent divs: .inputs and .infoBoxes. Each of them have an equal number of children. When the user clicks into the first .input in .inputs, the first .infoBox in .infoBoxes should slideDown(). Same for second, third, etc. I'd like to do this without re-writing the same code for each pair. So far I have:
var $inputs = $('.inputs').children();
var $infoBoxes = $('.infoBoxes').children();
for(var i = 0; i < $inputs.length; i++ ) {
$($inputs[i]).find('.input').focus(function() {
$($infoBoxes[i]).slideDown();
})
$($inputs[i]).find('.input').blur(function() {
$($infoBoxes[i]).slideUp();
})
}
This isn't working but I have tried replacing i with the indexes of each div.
$($inputs[0]).find('.input').focus(function() {
$($infoBoxes[0]).slideDown();
})
$($inputs[0]).find('.input').blur(function() {
$($infoBoxes[0]).slideUp();
})
repeat...
repeat...
repeat...
This works but isn't very DRY. I'm looking for a better solution that won't have me repeating a bunch of code.
First code will not work, because you using same variable for all internal functions. You should wrap it into function, which will create local variable for index. Try following code:
var $inputs = $('.inputs').children();
var $infoBoxes = $('.infoBoxes').children();
for(var i = 0; i < $inputs.length; i++ ) {
(function(ix) {
$($inputs[ix]).find('.input').focus(function() {
$($infoBoxes[ix]).slideDown();
})
$($inputs[ix]).find('.input').blur(function() {
$($infoBoxes[ix]).slideUp();
})
})(i);
}
slideDown is used for showing elements. I am guessing you want to hide elements, since you are clicking on them and you cant click an hidden element. Use hide or slideUp to hide elements.
$(".input, .infobox").on("click", function() {
var ind = $(this).index();
$(".infobox:eq(" + ind + "), .input:eq(" + ind + ")").hide(500);
});
.input,
.infobox {
widht: 100%;
height: 50px;
text-align: center;
margin: 5px 0;
color: white;
}
.input {
background: red;
}
.infobox {
background: blue;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="inputs">
<div class="input">1</div>
<div class="input">2</div>
<div class="input">3</div>
<div class="input">4</div>
<div class="input">5</div>
</div>
<div class="infoboxes">
<div class="infobox">1</div>
<div class="infobox">2</div>
<div class="infobox">3</div>
<div class="infobox">4</div>
<div class="infobox">5</div>
</div>

create an array with values of selected images

Im trying to gather the images selected, take their values, put them into an array, and then push them to a mysql database.
Here is my current code
$(document).ready(function() {
var startfind = $("body").find('.on').val();
var awnsers = $('.on').map(function() {
return $(startfind).text();
}).get().join(',');
$("img").click(function() {
$(this).toggleClass("on");
});
$('button').click(function() {
alert(awnsers);
});
});
#seasoning {
margin: 8px;
font-size: 16px;
height: 100px;
width: 100px;
}
.on {
padding: 10px;
background-color: red;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<img src="https://i.imgur.com/7HyU4yh.jpg" id="seasoning" value="0">
<br>
<img src="https://i.imgur.com/OEHCjCK.jpg" id="seasoning" value="1">
<br>
<button>Submit</button>
I can't get the alert to show the values of the items selected.
You can trigger an event when you click on an image
Then listen on that event, an update the answer
use answer when you need it
an I change a little in your html code, that change img's value attr to data-value
============Here is the code and jsFiddle=======================
$(function(){
//catch this values, because you will use these for more than one time
var answers = [];
function getAnswers(){
answers = []; //empty old answers so you can update it
$.map($('.on'), function(item){
answers.push($(item).data('value'));
});
}
//init the answers in case you use it before click
getAnswers();
$(document).on('click', 'img', function(e){
e.preventDefault();
$(this).toggleClass('on');
//trigger the state change when you click on an image
$(document).trigger('state-change');
});
//get answers when event was triggered
$(document).on('state-change', function(e){
getAnswers();
});
$('#btn-show').click(function(){
alert(answers.join(',') || 'nothing was selected');
});
});
#seasoning {
margin: 8px;
font-size: 16px;
height: 100px;
width: 100px;
}
.on {
padding: 10px;
background-color: red;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<img src="https://i.imgur.com/7HyU4yh.jpg" id="seasoning" data-value="0">
<br>
<img src="https://i.imgur.com/OEHCjCK.jpg" id="seasoning" data-value="1">
<br>
<button id="btn-show">Submit</button>
Please check this code.
$("img").on('click',function() {
$(this).toggleClass("on");
});
$(document).on('click', 'button', function() {
var awnsers = $('.on').map(function() {
return $(this).attr('value');
}).get().join(',');
alert(awnsers);
});
Working fiddle - http://jsfiddle.net/Ashish_developer/6ezf363a/

Add div below another div

I have a requirement to add 5 divs one by one on each click of a div button. ( the new div should be added below the existing div)
I done the code, but the news ones are getting attached on the top of existing div. please help to correct this.
I have another button which removes the added divs one by one(new ones to be remove first)
here is my code.
<div class="clearFix"></div>
<div id="containershowmore" >
<div id="dragbtnmore" style="cursor: default;">Show more buttons</div>
<div id="dragbtnless" style="cursor: default;">Show Fewer buttons</div>
</div>
<div class="toAdd" style="display:none;" >
<div id="dragdashboardmain" style="cursor: pointer;">dash</div></div>
<div class="toAdd" style="display:none;" >
<div id="dragrcalendar" style="cursor: pointer;">Calendar</div></div>
<div class="toAdd" style="display:none;">
<div id="dragresourcelist" style="cursor: pointer;">Rlist</div></div>
<div class="toAdd" style="display:none;">
<div id="dragdailynotes" style="cursor: pointer;">D Notes</div></div>
<div class="toAdd" style="display:none;">
<div id="dragweeklynotes" style="cursor: pointer;">W Notes</div></div>
script:
$("#dragbtnmore").click(function () {
$('.toAdd').each(function () {
if ($(this).css('display') == 'none') {
$(this).css('display', 'block');
return false;
}
});
var i = 0;
$('.toAdd').each(function () {
if ($(this).css('display') != 'none') {
i++;
}
});
if (i == 5)
$('#dragbtnmore').click(function () { return false; });
});
$("#dragbtnless").click(function () {
$('.toAdd').each(function () {
if ($(this).css('display') == 'block') {
$(this).css('display', 'none');
return false;
}
});
var i = 0;
$('.toAdd').each(function () {
if ($(this).css('display') != 'block') {
i++;
}
});
if (i == 5)
$('#dragbtnless').click(function () { return false; });
$('#dragbtnless').click(function () { return true; });
});
$("#containershowmore").mouseleave(function () {
$(this).hide();
});
function showmore() {
document.getElementById('containershowmore').style.display = "block";
}
style:
#containershowmore
{
margin-top: -75px;position: relative;margin-left: 160px;background-color: #b1dafb;z-index: 1;
width: 125px;
float: right;
padding-left: 5px;
}
.toAdd
{
background-color: blue;
margin-top: -55px;
position: relative;
margin-bottom: 14px;
}
*I referred this Fiddle *
**Solution:
Thankyou Shivam Chopra for helping me . Thanks a TON!! :)
for others, HEre is the solution**
jsfiddle.net/coolshivster/YvE5F/12
Remove margin top from both the div.
#containershowmore
{
position: relative;margin-left: 160px;background-color: #b1dafb;z-index: 1;
width: 125px;
float:right;
padding-left: 5px;
}
#dragbtnmore{
margin-bottom:10px;
border:1px solid black;
}
.toAdd
{
height:20px;
width:70px;
background-color: blue;
position: relative;
margin-bottom: 14px;
}
Then, it will work accordingly.
Here, the code : http://jsfiddle.net/coolshivster/YvE5F/
I have rewritten your code according to your requirement.
Some explanation about the code
I have create a parent div element with id="Add-element" that covers every element which contains class .toAdd .
Then I created data attribute for every div containing class .toAdd .
Now, I display the element one by one. But after first element. Every other element will prepend on the parent div i.e., #Add-element class.
Now, the code which I have rewritten.
jsfiddle link : http://jsfiddle.net/YvE5F/10/

Categories

Resources