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

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");
}
}

Related

If statement does not seem to be working properly

I am working on a real estate site and would like to have specific pages to show properties for rent/sale. I am trying to only show properties that have the "Rent" status, but the if statement seems to just default to else.
Using border styles to visibly see if statements.
web page: http://targetrealtygroupdev.com/rent/
What am I missing?
<div class="property-item">
<div class="proprty-inner>
<div class="property-status-bg">
"Rent"
</div>
</div>
</div>
.one {
border: 1px solid red;
}
.two {
border: 1px solid blue;
}
<script>
document.addEventListener("DOMContentLoaded", function(event) {
var status = document.getElementsByClassName("property-status-bg");
for (item of status) {
var type = item.innerText;
if (type == 'Rent') {
jQuery('.property-item').addClass('one');
} else {
jQuery('.property-item').addClass('two');
}
}
});
</script>
you are changing all jQuery('.property-item') for each item
and .property-status-bg is not only with a simple text == 'Rent' or 'Sale' ...
it's look like:
<p>
<span class="property-status-bg" style="background-color: #888">
Rent
<span class="property-arrow" style="border-left-color: #888; border-right-color: #888"></span>
</span>
</p>
So you have to use the string.include method
try:
document.addEventListener("DOMContentLoaded", function(event)
{
document.querySelectorAll('.property-status-bg').forEach(item =>
{
let ClassChoice = item.textContent.includes('Rent') ? 'one' : 'two'
item.closest('.property-item').classList.add( ClassChoice )
})
})
You are selecting all the elements, you are not selecting the one you are referencing in the loop.
item.closest('.property-item').classList.add('one');

Create multiple divs with different content

The problem is when duplicate multiple div but with different data-type, it still running a same content, i want correct all div will have the different content following the different data-type.
Is there a way to do this?
$(function() {
// document
'use strict';
var cp = $('div.box');
// unique id
var idCp = 0;
for (var i = 0; i < cp.length; i++) {
idCp++;
cp[i].id = "cp_" + idCp;
}
// diffrent type
if (cp.data('type') == "c1") {
cp.addClass('red').css({
"background: 'red',
"padding": "20px",
"display": "table"
});
$('.box').append('<div class="cp-title">' + 'c1-title' + '</div>');
} else if (cp.data('type') == "c2") {
cp.addClass('green').css({
"background": 'green',
"padding": "20px",
"display": "table"
});
$('.box').append('<div class="cp-title">' + 'c2-title' + '</div>');
} else {
return false;
}
}); //end
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<! it should be like this>
<div class="box" data-type="c1" id="cp_1">
<div class="cp-title">c1 title</div>
</div>
<div class="box" data-type="c2" id="cp_2">
<div class="cp-title">c2 title</div>
</div>
<! currently wrong output>
<div class="box" data-type="c1" id="cp_1">
<div class="cp-title">c1 title</div>
</div>
<div class="box" data-type="c2" id="cp_2">
<div class="cp-title">c1 title</div>
</div>
The problem in your code is that you are not looping inside the div's. You have to use the .each() function while looping inside all the elements
$(function() {
var cp = $('div.box');
cp.each(function() {
var _cp = $(this);
var text = _cp.attr("data-type") + "-title"; //Generate the text dynamically
var cls = _cp.attr("data-class"); //Get the class dynamically
_cp.addClass(cls).append('<div class="cp-title">' + text + '</div>'); //Add the class and append the text to the parent div
});
}); //end
.box{
padding: 20px;
display: table;
}
.red{
background: red;
}
.green{
background: green;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="box" data-type="c1" data-class="red"></div>
<div class="box" data-type="c2" data-class="green"></div>
Probably you're searching for something like this.
// document.ready
$(function() {
'use strict';
$('.box').each(function(i,elem){
var ref = +$(elem).attr("data-type").match(/\d/)[0], addClass = 'default';
switch(true) {
case ref === 1:
addClass = 'red';
break;
case ref === 2:
addClass = 'green';
break;
}
$(this)
.addClass(addClass)
.append('<div class="cp-title">c'+ref+' title</div>');
});
}); //end
.red{
background: red;
padding: 20px;
display: table;
}.green{
background: green;
padding: 20px;
display: table;
}.default {
background: #2d2d2d;
color: #f6f6f6;
padding: 20px;
display: table;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="box" data-type="c1"></div><div class="box" data-type="c2"></div>

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

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.

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>

Node Jquery load pages into div error

// Userlist data array for filling in info box
var userListData = [];
// DOM Ready =============================================================
$(document).ready(function() {
// Populate the user table on initial page load
populateTable();
// Username link click
$('#userList table tbody').on('click', 'td a.linkshowuser', showUserInfo);
// Add User button click
$('#btnAddUser').on('click', addUser);
// Delete User link click
$('#userList table tbody').on('click', 'td a.linkdeleteuser', deleteUser);
//Set Default page to Home.html
$('#content').load('views/home.html');
//Call navBar function
navBar();
projectBtn();
});
// Functions =============================================================
//Navbar function
function navBar() {
$('ul#navtest li a').click(function() {
var page = $(this).attr('title');
$('#content').fadeOut(400);
setTimeout(function(){$('#content').load('views/' + page + '.html')}, 400);
$('#content').fadeIn(400);
return false;
});
}
function projectBtn() {
$('a.projectbutton').click(function() {
var page = $(this).attr('title');
$('#content').fadeOut(400);
setTimeout(function(){$('#content').load('views/' + page + '.html')}, 400);
$('#content').fadeIn(400);
return false;
});
}
// Fill table with data
function populateTable() {
// Empty content string
var tableContent = '';
// jQuery AJAX call for JSON
$.getJSON( '/users/userlist', function( data ) {
// Stick our user data array into a userlist variable in the global object
userListData = data;
// For each item in our JSON, add a table row and cells to the content string
$.each(data, function(){
tableContent += '<tr>';
tableContent += '<td>' + this.username + '</td>';
tableContent += '<td>' + this.email + '</td>';
tableContent += '<td>delete</td>';
tableContent += '</tr>';
});
// Inject the whole content string into our existing HTML table
$('#userList table tbody').html(tableContent);
});
};
// Show User Info
function showUserInfo(event) {
// Prevent Link from Firing
event.preventDefault();
// Retrieve username from link rel attribute
var thisUserName = $(this).attr('rel');
// Get Index of object based on id value
var arrayPosition = userListData.map(function(arrayItem) { return arrayItem.username; }).indexOf(thisUserName);
// Get our User Object
var thisUserObject = userListData[arrayPosition];
//Populate Info Box
$('#userInfoName').text(thisUserObject.fullname);
$('#userInfoAge').text(thisUserObject.age);
$('#userInfoGender').text(thisUserObject.gender);
$('#userInfoLocation').text(thisUserObject.location);
};
// Add User
function addUser(event) {
event.preventDefault();
// Super basic validation - increase errorCount variable if any fields are blank
var errorCount = 0;
$('#addUser input').each(function(index, val) {
if($(this).val() === '') { errorCount++; }
});
// Check and make sure errorCount's still at zero
if(errorCount === 0) {
// If it is, compile all user info into one object
var newUser = {
'username': $('#addUser fieldset input#inputUserName').val(),
'email': $('#addUser fieldset input#inputUserEmail').val(),
'fullname': $('#addUser fieldset input#inputUserFullname').val(),
'age': $('#addUser fieldset input#inputUserAge').val(),
'location': $('#addUser fieldset input#inputUserLocation').val(),
'gender': $('#addUser fieldset input#inputUserGender').val()
}
// Use AJAX to post the object to our adduser service
$.ajax({
type: 'POST',
data: newUser,
url: '/users/adduser',
dataType: 'JSON'
}).done(function( response ) {
// Check for successful (blank) response
if (response.msg === '') {
// Clear the form inputs
$('#addUser fieldset input').val('');
// Update the table
populateTable();
}
else {
// If something goes wrong, alert the error message that our service returned
alert('Error: ' + response.msg);
}
});
}
else {
// If errorCount is more than 0, error out
alert('Please fill in all fields');
return false;
}
};
// Delete User
function deleteUser(event) {
event.preventDefault();
// Pop up a confirmation dialog
var confirmation = confirm('Are you sure you want to delete this user?');
// Check and make sure the user confirmed
if (confirmation === true) {
// If they did, do our delete
$.ajax({
type: 'DELETE',
url: '/users/deleteuser/' + $(this).attr('rel')
}).done(function( response ) {
// Check for a successful (blank) response
if (response.msg === '') {
}
else {
alert('Error: ' + response.msg);
}
// Update the table
populateTable();
});
}
else {
// If they said no to the confirm, do nothing
return false;
}
};
.border {
border: 4px solid black; }
.back2 {
background-color: #232323; }
.marginleft {
margin-left: 8%; }
.margin {
margin-right: 4%;
margin-left: 4%;
margin-top: 2%;
margin-bottom: 2%; }
.padding {
padding: 1%; }
.margintop {
margin-top: 1%; }
.margintop2 {
margin-top: 5%; }
.iconmargintop {
margin-top: 50px; }
.fill {
height: 100%;
width: 100%; }
p {
color: #ffffff; }
label {
color: #ffffff; }
h1 {
color: #ffffff; }
h2 {
color: #ffffff; }
th {
color: #ffffff; }
span {
color: #ffffff; }
h3 {
color: #ffffff; }
.projectseltext {
padding: 1%;
margin: 1%; }
.background {
background-color: #333333;
position: relative;
height: 100%; }
#blacktext {
color: black; }
.disablelink {
pointer-events: none;
cursor: default; }
.nav {
background-color: #b2b2b2; }
.nav a {
color: #ffffff;
font-size: 11px;
font-weight: bold;
padding: 14px 10px;
text-transform: uppercase; }
.nav li {
display: inline; }
.back1 {
background-color: #0c0c0c; }
.fit {
height: 100%;
width: 100%; }
.well {
background-color: #333333; }
.backg1 {
background-color: #333333; }
<html>
<head>
<meta name="generator"
content="HTML Tidy for HTML5 (experimental) for Windows https://github.com/w3c/tidy-html5/tree/c63cc39" />
<title></title>
</head>
<body>
<div id="project">
<div class="container-fluid row">
<a href="#" title="projectnew" class="projectbutton">
<div class="back2 col-md-11 margin border">
<img src="images/ph.jpg" class="thumbnail margin col-md-3" style="width:150px;" />
<h1 class="margin" style="margin-top:75px;">New Projects</h1>
</div>
</a>
</div>
</div>
</body>
</html>
<!DOCTYPE html>
<html>
<head>
<meta name="generator"
content="HTML Tidy for HTML5 (experimental) for Windows https://github.com/w3c/tidy-html5/tree/c63cc39" />
<link rel="stylesheet" href="stylesheets/bootstrap.min.css" />
<link rel="stylesheet" href="stylesheets/main.css" />
<script src="build/js/jquery-2.2.4.min.js"></script>
<script src="build/js/bootstrap.min.js"></script>
<script src="build/js/global.js"></script>
<title></title>
</head>
<body class="background">
<div class="container-fluid nav navbar-inverse">
<ul id="navtest" class="margintop">
<li>
Home
</li>
<li>
Projects
</li>
<li>
Contact
</li>
<li>
Resume
</li>
<li>
About
</li>
<li>
Database
</li>
</ul>
</div>
<div id='content' class="tab-content" />
</body>
</html>
<html>
<head>
<meta name="generator"
content="HTML Tidy for HTML5 (experimental) for Windows https://github.com/w3c/tidy-html5/tree/c63cc39" />
<title></title>
</head>
<body>
<div id="projectnew">
<div class="row">
<div class="container col-md-12 margintop marginleft">
Back
</div>
<div class="container-fluid margin">
<a href="" data-toggle="tab">
<div class="back2 col-md-11 margin border">
<img src="images/ph.jpg" class="thumbnail margin" style="width:150px" />
<h1 class="margin">Comming soon.</h1>
</div>
</a>
</div>
</div>
</div>
</body>
</html>
This file is temporary, i know the contents wont do anything.
The function navBar works perfectly, however when trying to apply the same method to another class and div it seems to fail.
Whenever i click on the projectbutton class it redirects to error.html. For some reason the javascript is not seeing/handling the class on click and the href being an unsupported type redirects me to error.html. However i'm not sure what is wrong with my code.
welcome;
In your HTML code, <a href="projectnew" class="projectbutton"> you have an href for your a element, if you click on this, it will go to the page "www.yourdomain.com/projectnew" since this page does not exist, you will be redirected to your error page...
To solve this problem, you should use preventDefault, in order to prevent your link element to operate things that you do not want.
$('a.projectbutton').click(function(event) {
event.preventDefault();
var page = $(this).attr('href');
$('#content').fadeOut(400);
setTimeout(function(){$('#content').load('views/' + page + '.html')}, 400);
$('#content').fadeIn(400);
return false;
});
I did not try it out, but it should work.
Read more about preventDefault: https://api.jquery.com/event.preventdefault/
OR;
Since the main problem is your href attributes in your a elements, try to remove them;
Home
Use title as your specifier in your JS;
$('a.projectbutton').click(function() {
var page = $(this).attr('title'); //changed this into title.
$('#content').fadeOut(400);
setTimeout(function(){$('#content').load('views/' + page + '.html')}, 400);
$('#content').fadeIn(400);
return false;
});

Categories

Resources