I have found a script with jquery filtering that i need.
In that script some item have values of green and some of green and yellow. If you choose colors green and yellow, you get all green and yellow items, and items that are both green and yellow.
I would need to change that so that if i choose green and yellow, i would only get item that are both green and yellow.
I'm not really good at js so i would really appreciate the help.
var byProperty = [], byColor = [], byLocation = [];
$("input[name=fl-colour]").on( "change", function() {
if (this.checked) byProperty.push("[data-category~='" + $(this).attr("value") + "']");
else removeA(byProperty, "[data-category~='" + $(this).attr("value") + "']");
});
$("input[name=fl-size]").on( "change", function() {
if (this.checked) byColor.push("[data-category~='" + $(this).attr("value") + "']");
else removeA(byColor, "[data-category~='" + $(this).attr("value") + "']");
});
$("input[name=fl-cont]").on( "change", function() {
if (this.checked) byLocation.push("[data-category~='" + $(this).attr("value") + "']");
else removeA(byLocation, "[data-category~='" + $(this).attr("value") + "']");
});
$("input").on( "change", function() {
var str = "Include items \n";
var selector = '', cselector = '', nselector = '';
var $lis = $('.flowers > div'),
$checked = $('input:checked');
if ($checked.length) {
if (byProperty.length) {
if (str == "Include items \n") {
str += " " + "with (" + byProperty.join(',') + ")\n";
$($('input[name=fl-colour]:checked')).each(function(index, byProperty){
if(selector === '') {
selector += "[data-category~='" + byProperty.id + "']";
} else {
selector += ",[data-category~='" + byProperty.id + "']";
}
});
} else {
str += " AND " + "with (" + byProperty.join(' OR ') + ")\n";
$($('input[name=fl-size]:checked')).each(function(index, byProperty){
selector += "[data-category~='" + byProperty.id + "']";
});
}
}
if (byColor.length) {
if (str == "Include items \n") {
str += " " + "with (" + byColor.join(' OR ') + ")\n";
$($('input[name=fl-size]:checked')).each(function(index, byColor){
if(selector === '') {
selector += "[data-category~='" + byColor.id + "']";
} else {
selector += ",[data-category~='" + byColor.id + "']";
}
});
} else {
str += " AND " + "with (" + byColor.join(' OR ') + ")\n";
$($('input[name=fl-size]:checked')).each(function(index, byColor){
if(cselector === '') {
cselector += "[data-category~='" + byColor.id + "']";
} else {
cselector += ",[data-category~='" + byColor.id + "']";
}
});
}
}
if (byLocation.length) {
if (str == "Include items \n") {
str += " " + "with (" + byLocation.join(' OR ') + ")\n";
$($('input[name=fl-cont]:checked')).each(function(index, byLocation){
if(selector === '') {
selector += "[data-category~='" + byLocation.id + "']";
} else {
selector += ",[data-category~='" + byLocation.id + "']";
}
});
} else {
str += " AND " + "with (" + byLocation.join(' OR ') + ")\n";
$($('input[name=fl-cont]:checked')).each(function(index, byLocation){
if(nselector === '') {
nselector += "[data-category~='" + byLocation.id + "']";
} else {
nselector += ",[data-category~='" + byLocation.id + "']";
}
});
}
}
$lis.hide();
console.log(selector);
console.log(cselector);
console.log(nselector);
if (cselector === '' && nselector === '') {
$('.flowers > div').filter(selector).show();
} else if (cselector === '') {
$('.flowers > div').filter(selector).filter(nselector).show();
} else if (nselector === '') {
$('.flowers > div').filter(selector).filter(cselector).show();
} else {
$('.flowers > div').filter(selector).filter(cselector).filter(nselector).show();
}
} else {
$lis.show();
}
$("#result").html(str);
});
function removeA(arr) {
var what, a = arguments, L = a.length, ax;
while (L > 1 && arr.length) {
what = a[--L];
while ((ax= arr.indexOf(what)) !== -1) {
arr.splice(ax, 1);
}
}
return arr;
}
Link to jsfiddle: http://jsfiddle.net/3gf1j1ec/
This is how you would obtain an intersection of arrays. It uses the Array.prototype.every method to produce the match.
var byProperty = [], byColor = [], byLocation = [];
var intersectionOfColours = function(){
// get an array of the selected colours
var selectedColours = $('form input[name="fl-colour"]:checked').map(function(){
return this.value;
}).get();
// iterate through the flowers and show/hide
$('.flowers .flower').each(function(){
var flowerColours = $(this).data("category").split(' ');
// if all selected colours can be found in flowerColours, we have a match
var match = selectedColours.every(function(thisColour){
return (flowerColours.indexOf(thisColour) !== -1);
});
if (match) {
$(this).show();
} else {
$(this).hide();
}
});
// debug
$('#result').html( JSON.stringify(selectedColours) );
};
$("input[name=fl-colour]").on( "change", intersectionOfColours);
label {
float: left;
clear: left;
}
.flowers-wrap {
width: 100%;
}
.flowers-wrap form {
width: 49%;
float: left;
}
.flower {
background-color: #DEE;
padding: .5em;
margin: 3px;
border: 1px solid gray;
}
.flowers {
width: 49%;
float: left;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<pre id=result></pre>
<div class="flowers-wrap">
<h3>Available Flowers</h3>
<p><strong>Filter flowers by colour:</strong></p>
<form>
<label><input type="checkbox" name="fl-colour" value="red" id="red" />Red</label>
<label><input type="checkbox" name="fl-colour" value="yellow" id="yellow" />Yellow</label>
<label><input type="checkbox" name="fl-colour" value="pink" id="pink" />Pink</label>
<label><input type="checkbox" name="fl-colour" value="purple" id="purple" />Purple</label>
<label><input type="checkbox" name="fl-colour" value="green" id="green" />Green</label>
<label><input type="checkbox" name="fl-colour" value="other" id="other" />Other</label>
</form>
<div class="flowers">
<div class="flower" data-id="aloe" data-category="green small medium africa">Aloe</div>
<div class="flower" data-id="lavendar" data-category="purple green medium africa europe">Lavender</div>
<div class="flower" data-id="stinging-nettle" data-category="green large africa europe asia">Stinging Nettle</div>
<div class="flower" data-id="gorse" data-category="green yellow large europe">Gorse</div>
<div class="flower" data-id="hemp" data-category="green large asia">Hemp</div>
<div class="flower" data-id="titan-arum" data-category="purple other giant asia">Titan Arum</div>
<div class="flower" data-id="golden-wattle" data-category="green yellow large australasia">Golden Wattle</div>
<div class="flower" data-id="purple-prairie-clover" data-category="purple green other medium north-america">Purple Prairie Clover</div>
<div class="flower" data-id="camellia" data-category="pink other large north-america">Camellia</div>
<div class="flower" data-id="scarlet-carnation" data-category="red medium north-america">Scarlet Carnation</div>
<div class="flower" data-id="indian-paintbrush" data-category="red medium north-america">Indian Paintbrush</div>
<div class="flower" data-id="moss-verbena" data-category="purple other small south-america">Moss Verbena</div>
<div class="flower" data-id="climbing-dayflower" data-category="blue tiny south-america">Climbing Dayflower</div>
<div class="flower" data-id="antarctic-pearlwort" data-category="green yellow large antarctica">Antarctic Pearlwort</div>
</div>
</div>
Related
So I have these divs that are essentially results, I am trying to filter through said results using checkboxes and data-category tags.
Here is the code I am using below it works except for it should only show the divs if its data category tags match all checkboxes selected. But in this script if you select boditrak, trackman, and indoor it will show each result that has any of those not just the ones that contain each tag
JSFiddle
<html>
<head>
<title>Test</title>
</head>
<body>
<input type='checkbox' name="sq-filter" value="trackman" id="trackman">trackman<br>
<input type='checkbox' name="sq-filter" value="boditrak" id="boditrak"> boditrak<br>
<input type="checkbox" name="sq-filter" value="kvest" id="kvest">kvest<br>
<input type="checkbox" name="sq-filter" value="slowmotion" id="slowmotion">slowmotion<br>
<input type="checkbox" name="sq-filter" value="indoor" id="indoor">indoor<br>
<p>
<div class="filters">
<div data-id="golfer" data-category="boditrak trackman slowmotion">
<p>Golfer Name - boditrak trackman slowmotion</p>
</div>
<div data-id="golfer" data-category="indoor slowmotion trackman">
<p>Golfer Name - indoor slowmotion trackman</p>
</div>
<div data-id="golfer" data-category="kvest boditrak trackman">
<p>Golfer Name - kvest boditrak trackman</p>
</div>
<div data-id="golfer" data-category="indoor slowmotion">
<p>Golfer Name - indoor slowmotion</p>
</div>
</div>
</body>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script>
var byProperty = [];
$("input[name=sq-filter]").on( "change", function() {
if (this.checked) byProperty.push("[data-category~='" + $(this).attr("value") + "']");
else removeA(byProperty, "[data-category~='" + $(this).attr("value") + "']");
});
$("input").on( "change", function() {
var str = "Include items \n";
var selector = '', cselector = '', nselector = '';
var $lis = $('.filters > div'),
$checked = $('input:checked');
if ($checked.length) {
if (byProperty.length) {
if (str == "Include items \n") {
str += " " + "with (" + byProperty.join(',') + ")\n";
$($('input[name=sq-filter]:checked')).each(function(index, byProperty){
if(selector === '') {
selector += "[data-category~='" + byProperty.id + "']";
} else {
selector += ",[data-category~='" + byProperty.id + "']";
}
});
} else {
str += " AND " + "with (" + byProperty.join(' OR ') + ")\n";
$($('input[name=fl-size]:checked')).each(function(index, byProperty){
selector += "[data-category~='" + byProperty.id + "']";
});
}
}
$lis.hide();
console.log(selector);
console.log(cselector);
console.log(nselector);
if (cselector === '' && nselector === '') {
$('.filters > div').filter(selector).show();
} else if (cselector === '') {
$('.filters > div').filter(selector).filter(nselector).show();
} else if (nselector === '') {
$('.filters > div').filter(selector).filter(cselector).show();
} else {
$('.filters > div').filter(selector).filter(cselector).filter(nselector).show();
}
} else {
$lis.show();
}
$("#result").html(str);
});
function removeA(arr) {
var what, a = arguments, L = a.length, ax;
while (L > 1 && arr.length) {
what = a[--L];
while ((ax= arr.indexOf(what)) !== -1) {
arr.splice(ax, 1);
}
}
return arr;
}
</script>
</html>
The problem is with comma , which you are adding between each [data-category~=] in selector variable. So jQuery is looking for element which has any one of these data-category. So just remove comma, then only jQuery will start looking for those element which have all those data-category
Your selector value should be [data-category~='trackman'][data-category~='boditrak'] instead of [data-category~='trackman'],[data-category~='boditrak']
var byProperty = [];
$("input[name=sq-filter]").on( "change", function() {
if (this.checked) byProperty.push("[data-category~='" + $(this).attr("value") + "']");
else removeA(byProperty, "[data-category~='" + $(this).attr("value") + "']");
});
$("input").on( "change", function() {
var str = "Include items \n";
var selector = '', cselector = '', nselector = '';
var $lis = $('.filters > div'),
$checked = $('input:checked');
if ($checked.length) {
if (byProperty.length) {
if (str == "Include items \n") {
str += " " + "with (" + byProperty.join(',') + ")\n";
$($('input[name=sq-filter]:checked')).each(function(index, byProperty){
selector += "[data-category~='" + byProperty.id + "']";
});
} else {
str += " AND " + "with (" + byProperty.join(' OR ') + ")\n";
$($('input[name=fl-size]:checked')).each(function(index, byProperty){
selector += "[data-category~='" + byProperty.id + "']";
});
}
}
$lis.hide();
console.log(selector);
console.log(cselector);
console.log(nselector);
if (cselector === '' && nselector === '') {
$('.filters > div').filter(selector).show();
} else if (cselector === '') {
$('.filters > div').filter(selector).filter(nselector).show();
} else if (nselector === '') {
$('.filters > div').filter(selector).filter(cselector).show();
} else {
$('.filters > div').filter(selector).filter(cselector).filter(nselector).show();
}
} else {
$lis.show();
}
$("#result").html(str);
});
function removeA(arr) {
var what, a = arguments, L = a.length, ax;
while (L > 1 && arr.length) {
what = a[--L];
while ((ax= arr.indexOf(what)) !== -1) {
arr.splice(ax, 1);
}
}
return arr;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type='checkbox' name="sq-filter" value="trackman" id="trackman">trackman<br>
<input type='checkbox' name="sq-filter" value="boditrak" id="boditrak"> boditrak<br>
<input type="checkbox" name="sq-filter" value="kvest" id="kvest">kvest<br>
<input type="checkbox" name="sq-filter" value="slowmotion" id="slowmotion">slowmotion<br>
<input type="checkbox" name="sq-filter" value="indoor" id="indoor">indoor<br>
<p>
<div class="filters">
<div data-id="golfer" data-category="boditrak trackman slowmotion">
<p>Golfer Name - boditrak trackman slowmotion</p>
</div>
<div data-id="golfer" data-category="indoor slowmotion trackman">
<p>Golfer Name - indoor slowmotion trackman</p>
</div>
<div data-id="golfer" data-category="kvest boditrak trackman">
<p>Golfer Name - kvest boditrak trackman</p>
</div>
<div data-id="golfer" data-category="indoor slowmotion">
<p>Golfer Name - indoor slowmotion</p>
</div>
</div>
Here is my fiddle : DEMO
According to data JSON, there are 2 "groups".
Each group has 2 "widgets" each.
Every widget has certain "controls"
Light/Brightness/Color controls can be there for Philips widget. They are associated with a switch/slider/color picker respectively.
for (var k = 0; k < data.groups[i].widgets[j].controls.length; k++) {
$("." + data.groups[i].name + " > .widgets-container > ." + data.groups[i].widgets[j].name + " > .widget-header > .widget-label > .row > .brandName").text(data.groups[i].widgets[j].brandName);
$("." + data.groups[i].name + " > .widgets-container > ." + data.groups[i].widgets[j].name + " > .widget-header > .widget-label > .row > .productName").text(data.groups[i].widgets[j].productName);
var controlDiv;
if (data.groups[i].widgets[j].controls[k].type === "SWITCH") {
controlDiv = lightControl();
} else if (data.groups[i].widgets[j].controls[k].type === "SLIDER") {
controlDiv = brightnessControl();
} else if (data.groups[i].widgets[j].controls[k].type === "PICKER") {
controlDiv = colorControl();
}
controlDiv = $(controlDiv).addClass(data.groups[i].widgets[j].controls[k].name);
$("." + data.groups[i].widgets[j].controls[k].name > ".control-name").text(data.groups[i].widgets[j].controls[k].name);
$("." + data.groups[i].name + " > .widgets-container").append(widgetDiv);
$(widgetDiv).append(controlDiv);
$(".container-box").append(groupDiv);
}
However, the elements are not getting appended as required from the JSON. Also, the labels for light/brightness/color control does not appear. Where am I going wrong?
Any help would be much appreciated.
Thank you.
here is the answer fiddle : AnswerFiddle
I fixed this issue by first creating DOM elements and then assigning/appending values to the DOM elements.
Earlier there was an issue because sometimes assigning of value would be attempted even before DOM element was created.
controlDiv = $(controlDiv).addClass("row " + (data.groups[i].widgets[j].controls[k].name).replace(/\s+/g, '-').toLowerCase()).prepend("<div class='col s7 controlName'>" + data.groups[i].widgets[j].controls[k].name + "</div>");
if (data.groups[i].widgets[j].controls[k].type === 'SWITCH') {
$(controlDiv).append('<div class="col s5 switch"><label>OFF<input type= "checkbox"><span class="lever"></span>ON</label></div>')
} else if (data.groups[i].widgets[j].controls[k].type === 'SLIDER') {
$(controlDiv).append('<div class="col s5 center-align"><img src="images/brightness.png"></div><p class="col s7 range-field"><input type="range" min = "0" max = "100"/></p><div class="col s5 brightness-percentage center-align">60%</div>')
} else if (data.groups[i].widgets[j].controls[k].type === 'PICKER') {
$(controlDiv).append('<input class="col s2" type="color" name="favcolor" value="#ff0000"><div class="col s3 colorHexValue center-align">#ff0000</div>')
} else if (data.groups[i].widgets[j].controls[k].type === 'GRAPH') {
$(controlDiv).html("<img src='images/graph.png'>");
} else if (data.groups[i].widgets[j].controls[k].type === 'DETECTOR') {
$(controlDiv).html("<img src='images/motion.png'>")
}
widgetDiv.append(controlDiv);
groupDiv.append(widgetDiv);
$(".container-box").append(groupDiv);
How can dynamic values be stored in the local storage?
I have a seat layout. How i can store only the selected seat numbers in the local storage, but not reserved seats?
My code can be seen below:
$(function() {
var settings = {
rows: 6,
cols: 10,
rowCssPrefix: 'row-',
colCssPrefix: 'col-',
seatWidth: 35,
seatHeight: 35,
seatCss: 'seat',
selectedSeatCss: 'selectedSeat',
selectingSeatCss: 'selectingSeat'
};
var init = function(reservedSeat) {
var str = [],
seatNo, className;
for (i = 0; i < settings.rows; i++) {
for (j = 0; j < settings.cols; j++) {
seatNo = (i + j * settings.rows + 1);
className = settings.seatCss + ' ' + settings.rowCssPrefix + i.toString() + ' ' + settings.colCssPrefix + j.toString();
if ($.isArray(reservedSeat) && $.inArray(seatNo, reservedSeat) != -1) {
className += ' ' + settings.selectedSeatCss;
}
str.push('<li class="' + className + '"' +
'style="top:' + (i * settings.seatHeight).toString() + 'px;left:' + (j * settings.seatWidth).toString() + 'px">' +
'<a title="' + seatNo + '">' + seatNo + '</a>' +
'</li>');
}
}
$('#place').html(str.join(''));
var SeatNo = document.getElementById('place').value;
localStorage.setItem('SeatNum', SeatNo);
};
//case I: Show from starting
//init();
//Case II: If already booked
var bookedSeats = [5, 10, 25];
init(bookedSeats);
$('.' + settings.seatCss).click(function() {
if ($(this).hasClass(settings.selectedSeatCss)) {
alert('This seat is already reserved');
} else {
$(this).toggleClass(settings.selectingSeatCss);
}
});
$('#btnShow').click(function() {
var str = [];
$.each($('#place li.' + settings.selectedSeatCss + ' a, #place li.' + settings.selectingSeatCss + ' a'), function(index, value) {
str.push($(this).attr('title'));
});
alert(str.join(','));
})
$('#btnShowNew').click(function() {
var str = [],
item;
$.each($('#place li.' + settings.selectingSeatCss + ' a'), function(index, value) {
item = $(this).attr('title');
str.push(item);
});
alert(str.join(','));
})
});
<div>
<div id="holder">
<ul id="place">
</ul>
</div>
<div style="">
<ul id="seatDescription">
<li style="background:url('available_seat_img.gif') no-repeat scroll 0 0 transparent;">Available Seat</li>
<li style="background:url('booked_seat_img.gif') no-repeat scroll 0 0 transparent;">Booked Seat</li>
<li style="background:url('selected_seat_img.gif') no-repeat scroll 0 0 transparent;">Selected Seat</li>
</ul>
</div>
<div style="width:100%">
<input type="button" id="btnShowNew" value="Show Selected Seats" />
<input type="button" id="btnShow" value="Show All" />
</div>
</div>
localStorage is an object within the global 'window' object, and therefore will normally be available throughout your javascript code. It pretty much behaves like a dictionary, you create, retrieve, edit and remove key:value pairs. jQuery will not be necessary.
It is also imporant to remember that localStorage only support string values, and simply saving an array would not work.
// When modifying bookedSeats:
var bookedSeatsCacheString = JSON.stringify(bookedSeats);
localStorage.setItem('bookedSeats', bookedSeatsCacheString);
// Init code:
var bookedSeatsCache = localStorage.getItem('bookedSeats');
var bookedSeats = JSON.parse(bookedSeatsCache);
if(!Array.isArray(bookSeats))
bookedSeats = [];
init(bookedSeats);
EDIT: I edited your code to make this work with localStorage
$(function () {
var settings = {
rows: 6,
cols: 10,
rowCssPrefix: 'row-',
colCssPrefix: 'col-',
seatWidth: 35,
seatHeight: 35,
seatCss: 'seat',
selectedSeatCss: 'selectedSeat',
selectingSeatCss: 'selectingSeat'
};
var init = function (reservedSeat) {
var str = [], seatNo, className;
for (i = 0; i < settings.rows; i++) {
for (j = 0; j < settings.cols; j++) {
seatNo = (i + j * settings.rows + 1);
className = settings.seatCss + ' ' + settings.rowCssPrefix + i.toString() + ' ' + settings.colCssPrefix + j.toString();
if ($.isArray(reservedSeat) && $.inArray(seatNo, reservedSeat) != -1) {
className += ' ' + settings.selectedSeatCss;
}
str.push('<li class="' + className + '"' +
'style="top:' + (i * settings.seatHeight).toString() + 'px;left:' + (j * settings.seatWidth).toString() + 'px">' +
'<a title="' + seatNo + '">' + seatNo + '</a>' +
'</li>');
}
}
$('#place').html(str.join(''));
};
// Init code
var bookedSeatsCache = localStorage.getItem('bookedSeats'),
bookedSeats;
if(typeof bookedSeatsCache === 'string' && bookedSeatsCache.length > 0)
bookedSeats = JSON.parse(bookedSeatsCache);
else
bookedSeats = [];
init(bookedSeats);
$('.' + settings.seatCss).click(function () {
if ($(this).hasClass(settings.selectedSeatCss)){
alert('This seat is already reserved');
}
else{
var seatNum = $(this).attr('title');
bookedSeats.push(seatNum);
localStorage.setItem('bookedSeats', JSON.stringify(bookedSeats));
$(this).toggleClass(settings.selectingSeatCss);
}
});
$('#btnShow').click(function () {
var str = [];
$.each($('#place li.' + settings.selectedSeatCss + ' a, #place li.'+ settings.selectingSeatCss + ' a'), function (index, value) {
str.push($(this).attr('title'));
});
alert(str.join(','));
})
$('#btnShowNew').click(function () {
var str = [], item;
$.each($('#place li.' + settings.selectingSeatCss + ' a'), function (index, value) {
item = $(this).attr('title');
str.push(item);
});
alert(str.join(','));
})
});
#holder{
height:225px;
width:365px;
background-color:#F5F5F5;
border:1px solid #A4A4A4;
margin-left:10px;
}
#place {
position:relative;
margin:7px;
}
#place a{
font-size:0.6em;
}
#place li
{
list-style: none outside none;
position: absolute;
}
#place li:hover
{
background-color:yellow;
}
#place .seat{
background:url("available_seat_img.gif") no-repeat scroll 0 0 transparent;
height:33px;
width:33px;
display:block;
padding:5px;
}
#place .selectedSeat
{
background-image:url("booked_seat_img.gif");
}
#place .selectingSeat
{
background-image:url("selected_seat_img.gif");
}
#place .row-3, #place .row-4{
margin-top:10px;
}
#seatDescription li{
vertical-align: middle;
list-style: none outside none;
color:white;
font-family:'LatoWeb', 'Lucida Grande', 'Lucida Sans Unicode', Arial, sans-serif;
font-size:13px;
padding-left:28px;
padding-top:14px;
height:35px;
float:left;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div>
<div id="holder">
<ul id="place">
</ul>
</div>
<div style="">
<ul id="seatDescription">
<li style="background:url('available_seat_img.gif') no-repeat scroll 0 0 transparent;">Available Seat</li>
<li style="background:url('booked_seat_img.gif') no-repeat scroll 0 0 transparent;">Booked Seat</li>
<li style="background:url('selected_seat_img.gif') no-repeat scroll 0 0 transparent;">Selected Seat</li>
</ul>
</div>
<div style="width:100%">
<input type="button" id="btnShowNew" value="Show Selected Seats" />
<input type="button" id="btnShow" value="Show All" />
</div>
</div>
I'm new to java script. I want prevent adding duplicate values to fourth list box. For example, It would not be same like below i) Paper Manufacturers << Paper Converters << Molded Pulp Products ii) Paper Manufacturers << Paper Converters << Molded Pulp Products And If there is no values in the fourth box, The "Remove Category" Button should be in disabled mode. If there is values & if i select any values in 4th box, The "Remove Category" Button should be enabled & "Add Category" button should be disabled.
$(document).ready(function() {
var firstCategorySelector = '.select-manage-category';
var secondCategorySelector = '.select-manage-category1';
var thirdCategorySelector = '.select-manage-category2';
var firstCategory = $(firstCategorySelector);
var secondCategory = $(secondCategorySelector);
var thirdCategory = $(thirdCategorySelector);
var addCategoryButton = $("#add-category");
var removeCategoryButton = $('#remove-category');
var selectedList = $('#selected-lst-values');
var choice = $("#tget");
$('.select-manage-category, .select-manage-category1, .select-manage-category2').change(function() {
AddCategoryButtonEnable();
});
function getCategoryValues() {
var firstCategoryValue = firstCategory.val();
var secondCategoryValue = secondCategory.val();
var thirdCategoryValue = thirdCategory.val();
return [firstCategoryValue, secondCategoryValue, thirdCategoryValue];
}
function isDisableAddButton() {
var values = getCategoryValues();
return (!values[0] || !values[1] || !values[2]);
}
function AddCategoryButtonEnable() {
var isDisableAddCategoryButton = isDisableAddButton();
addCategoryButton.prop("disabled", isDisableAddCategoryButton).toggleClass('text-bold', isDisableAddCategoryButton);
}
function getNumberOfSelectedOption() {
return selectedList.find("option").length;
}
function getAvailableChoice() {
return 20 - parseInt(getNumberOfSelectedOption());
}
function setAvailableChoice($numChoice) {
var strText = ($numChoice !== 20) ? $numChoice + " more " : "up to 20 ";
choice.text(strText);
}
function appendChoice() {
var count="";
var givenCategoryArrayValue = getCategoryValues();
if ($('#selected-lst-values option:contains("' + givenCategoryArrayValue[0] + ' << ' + givenCategoryArrayValue[1] + ' << ' + givenCategoryArrayValue[2] + '")').length > 0) {alert('This category has already been added.');
return count=1;
}
else {
selectedList.append('<option value="'+ givenCategoryArrayValue[0] + ' << ' + givenCategoryArrayValue[1] + ' << ' + givenCategoryArrayValue[2] +'">' + givenCategoryArrayValue[0] + ' << ' + givenCategoryArrayValue[1] + ' << ' + givenCategoryArrayValue[2] + '</option>');
return count=2;
}
}
addCategoryButton.click(function() {
var availableChoice = getAvailableChoice();
if (availableChoice >= 1) {
var a=appendChoice();
if(a==2){
setAvailableChoice(availableChoice - 1);
}
} else {
setAvailableChoice(0);
}
});
var option = selectedList.find('option:selected');
selectedList.change(function() {
removeCategoryButton.prop("disabled", false);
addCategoryButton.prop("disabled", true);
_addRemoveButtonClickListener();
});
function _addRemoveButtonClickListener() {
removeCategoryButton.click(function() {
selectedList.find('option:selected').remove();
var availableChoice = getAvailableChoice();
if (0 < availableChoice < 6) {
setAvailableChoice(availableChoice);
} else {
setAvailableChoice(0);
}
removeCategoryButton.prop("disabled", true);
});
}
});
.select-manage-category,
.select-manage-category1,
.select-manage-category2 {
width: 100px;
float: left;
margin-right: 4px;
}
p {
clear: left;
text-align: center;
}
#selected-lst-values {
width: 100%;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div><select class="form-control select-manage-category" size="5">
<option value="1">Paper Manufacturers</option>
<option value="2">Paper Products Suppliers</option>
<option value="3">Paper Chemicals Suppliers</option>
</select></div>
<div><select class="form-control select-manage-category1" size="5">
<option value="1">Paper Converters</option>
<option value="2">Lab Apparatus & Supplies</option>
<option value="3">Service Providers</option>
</select></div>
<div><select class="form-control select-manage-category2" size="5">
<option value="1">Molded Pulp Products</option>
<option value="2">Software Vendors</option>
<option value="3">Information Services</option>
</select>
</div>
<p style="padding-top:10px;color:red;">You can add <span id="target">up to 5</span> categories</p>
</div>
<input id="add-category" name="add" type="button" value="Add Category" disabled="true">
<input id="remove-category" name="add" type="button" value="Remove Category" disabled="true">
<div><select id="selected-lst-values" class="form-group percent-100" size="7" multiple="multiple">
</select></div>
<button id="mnage-category-savebtn" class="btn btn-md btn-radius pi-btn prodetails-btn" type="button"><strong>Save Categories</strong> <span class="glyphicon glyphicon-menu-right right-arrow-head-icon"></span></button>
Use this script. It will show alert if try to add duplicate entry. I have changed in function appendChoice().
$(document).ready(function () {
var firstCategorySelector = '.select-manage-category';
var secondCategorySelector = '.select-manage-category1';
var thirdCategorySelector = '.select-manage-category2';
var firstCategory = $(firstCategorySelector);
var secondCategory = $(secondCategorySelector);
var thirdCategory = $(thirdCategorySelector);
var addCategoryButton = $("#add-category");
var removeCategoryButton = $('#remove-category');
var selectedList = $('#selected-lst-values');
var choice = $("#target");
$('.select-manage-category, .select-manage-category1, .select-manage-category2').change(function () {
AddCategoryButtonEnable();
});
function getCategoryValues() {
var firstCategoryValue = firstCategory.val();
var secondCategoryValue = secondCategory.val();
var thirdCategoryValue = thirdCategory.val();
return [firstCategoryValue, secondCategoryValue, thirdCategoryValue];
}
function isDisableAddButton() {
var values = getCategoryValues();
return (!values[0] || !values[1] || !values[2]);
}
function AddCategoryButtonEnable() {
var isDisableAddCategoryButton = isDisableAddButton();
addCategoryButton.prop("disabled", isDisableAddCategoryButton).toggleClass('text-bold', isDisableAddCategoryButton);
}
function getNumberOfSelectedOption() {
return selectedList.find("option").length;
}
function getAvailableChoice() {
return 5 - parseInt(getNumberOfSelectedOption());
}
function setAvailableChoice($numChoice) {
var strText = ($numChoice !== 5) ? $numChoice + " more " : "up to 5 ";
choice.text(strText);
}
function appendChoice() {
var givenCategoryArrayValue = getCategoryValues();
if ($('#selected-lst-values option:contains("' + givenCategoryArrayValue[0] + ' << ' + givenCategoryArrayValue[1] + ' << ' + givenCategoryArrayValue[2] + '")').length > 0)
alert('Duplicate value not allowed.');
else
selectedList.append('<option value="">' + givenCategoryArrayValue[0] + ' << ' + givenCategoryArrayValue[1] + ' << ' + givenCategoryArrayValue[2] + '</option>');
}
addCategoryButton.click(function () {
var availableChoice = getAvailableChoice();
if (availableChoice >= 1) {
appendChoice();
setAvailableChoice(availableChoice - 1);
} else {
setAvailableChoice(0);
}
});
var option = selectedList.find('option:selected');
selectedList.change(function () {
removeCategoryButton.prop("disabled", false);
_addRemoveButtonClickListener();
});
function _addRemoveButtonClickListener() {
removeCategoryButton.click(function () {
selectedList.find('option:selected').remove();
var availableChoice = getAvailableChoice();
if (0 < availableChoice < 6) {
setAvailableChoice(availableChoice);
} else {
setAvailableChoice(0);
}
});
}
});
Check the working code snippet
$(document).ready(function() {
var firstCategorySelector = '.select-manage-category';
var secondCategorySelector = '.select-manage-category1';
var thirdCategorySelector = '.select-manage-category2';
var firstCategory = $(firstCategorySelector);
var secondCategory = $(secondCategorySelector);
var thirdCategory = $(thirdCategorySelector);
var addCategoryButton = $("#add-category");
var removeCategoryButton = $('#remove-category');
var selectedList = $('#selected-lst-values');
var choice = $("#target");
$('.select-manage-category, .select-manage-category1, .select-manage-category2').change(function() {
AddCategoryButtonEnable();
});
function getCategoryValues() {
var firstCategoryValue = firstCategory.val();
var secondCategoryValue = secondCategory.val();
var thirdCategoryValue = thirdCategory.val();
return [firstCategoryValue, secondCategoryValue, thirdCategoryValue];
}
function isDisableAddButton(){
var values = getCategoryValues();
return (!values[0] || !values[1] || !values[2]);
}
function AddCategoryButtonEnable() {
var isDisableAddCategoryButton = isDisableAddButton();
addCategoryButton.prop("disabled", isDisableAddCategoryButton).toggleClass('text-bold', isDisableAddCategoryButton );
}
function getNumberOfSelectedOption(){
return selectedList.find("option").length;
}
function getAvailableChoice(){
return 5 - parseInt(getNumberOfSelectedOption());
}
function setAvailableChoice($numChoice){
var strText = ($numChoice !== 5) ? $numChoice + " more " : "up to 5 ";
choice.text(strText);
}
function appendChoice(){
var givenCategoryArrayValue = getCategoryValues();
if ($('#selected-lst-values option:contains("' + givenCategoryArrayValue[0] + ' << ' + givenCategoryArrayValue[1] + ' << ' + givenCategoryArrayValue[2] + '")').length > 0)
alert('Duplicate value not allowed.');
else
selectedList.append('<option value="">' + givenCategoryArrayValue[0] + ' << ' + givenCategoryArrayValue[1] + ' << ' + givenCategoryArrayValue[2] + '</option>');
}
addCategoryButton.click(function() {
var availableChoice = getAvailableChoice();
if(availableChoice >= 1){
appendChoice();
setAvailableChoice(availableChoice - 1);
} else {
setAvailableChoice(0);
}
});
var option = selectedList.find('option:selected');
selectedList.change(function(){
removeCategoryButton.prop("disabled", false);
addCategoryButton.prop("disabled", true);
_addRemoveButtonClickListener();
});
function _addRemoveButtonClickListener(){
removeCategoryButton.click(function() {
selectedList.find('option:selected').remove();
var availableChoice = getAvailableChoice();
if(0 < availableChoice < 6){
setAvailableChoice(availableChoice);
} else {
setAvailableChoice(0);
}
removeCategoryButton.prop("disabled", true);
});
}
});
.select-manage-category,
.select-manage-category1,
.select-manage-category2 {
width: 100px;
float: left;
margin-right: 4px;
}
p {
clear: left;
text-align: center;
}
#selected-lst-values {
width: 100%;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div><select class="form-control select-manage-category" size="5">
<option>Paper Manufacturers</option>
<option>Paper Products Suppliers</option>
<option>Paper Chemicals Suppliers</option>
</select></div>
<div><select class="form-control select-manage-category1" size="5">
<option>Paper Converters</option>
<option>Lab Apparatus & Supplies</option>
<option>Service Providers</option>
</select></div>
<div><select class="form-control select-manage-category2" size="5">
<option>Molded Pulp Products</option>
<option>Software Vendors</option>
<option>Information Services</option>
</select>
</div>
<p style="padding-top:10px;color:red;">You can add <span id="target">up to 5</span> categories</p>
</div>
<input id="add-category" name="add" type="button" value="Add Category" disabled="true">
<input id="remove-category" name="add" type="button" value="Remove Category" disabled="true">
<div><select id="selected-lst-values" class="form-group percent-100" size="7" multiple="multiple">
</select></div>
<button id="mnage-category-savebtn" class="btn btn-md btn-radius pi-btn prodetails-btn" type="button"><strong>Save Categories</strong> <span class="glyphicon glyphicon-menu-right right-arrow-head-icon"></span></button>
I have a form with three radio buttons and a checkbox set up. A user must click one radio button and click the checkbox to submit. I am using WP-Polls which is a plugin for WordPress. For some reason, the form won't submit. I click a radio button, click the checkbox, but hitting submit does nothing. The live site can be seen here. The relevant section is the dark voting section on top.
HTML
<form id="polls_form_1" class="wp-polls-form" action="/index.php" method="post">
<p style="display: none;"><input type="hidden" id="poll_1_nonce" name="wp-polls-nonce" value="12a6404147"></p>
<p style="display: none;"><input type="hidden" name="poll_id" value="1"></p>
<div id="polls-1-ans">
<ul>
<li><input type="radio" id="poll-answer-1" name="poll_1" value="1"></li>
<li><input type="radio" id="poll-answer-2" name="poll_1" value="2"></li>
<li><input type="radio" id="poll-answer-3" name="poll_1" value="3"></li>
</ul>
<label class="check-terms"><input type="checkbox">I am over 18 and I have read and understand the Terms of Use</label>
<input type="submit" name="vote" value="Vote" class="Buttons" />
</form>
JavaScript
$(function() {
window.poll_vote = function(num) {
console.log(num);
}
$('.wp-polls-form').submit(function(e) {
if (!$('input:radio', this).is(':checked')) {
alert('Please pick a beat.');
return false;
}
if (!$('input:checkbox', this).is(':checked')) {
alert('Please agree to the Terms of Use.');
return false;
}
poll_vote(1);
return false;
});
});
Here is the function for poll_vote(1):
// When User Vote For Poll
function poll_vote(current_poll_id) {
jQuery(document).ready(function($) {
if(!is_being_voted) {
set_is_being_voted(true);
poll_id = current_poll_id;
poll_answer_id = '';
poll_multiple_ans = 0;
poll_multiple_ans_count = 0;
if($('#poll_multiple_ans_' + poll_id).length) {
poll_multiple_ans = parseInt($('#poll_multiple_ans_' + poll_id).val());
}
$('#polls_form_' + poll_id + ' input:checkbox, #polls_form_' + poll_id + ' input:radio, #polls_form_' + poll_id + ' option').each(function(i){
if ($(this).is(':checked') || $(this).is(':selected')) {
if(poll_multiple_ans > 0) {
poll_answer_id = $(this).val() + ',' + poll_answer_id;
poll_multiple_ans_count++;
} else {
poll_answer_id = parseInt($(this).val());
}
}
});
if(poll_multiple_ans > 0) {
if(poll_multiple_ans_count > 0 && poll_multiple_ans_count <= poll_multiple_ans) {
poll_answer_id = poll_answer_id.substring(0, (poll_answer_id.length-1));
poll_process();
} else if(poll_multiple_ans_count == 0) {
set_is_being_voted(false);
alert(pollsL10n.text_valid);
} else {
set_is_being_voted(false);
alert(pollsL10n.text_multiple + ' ' + poll_multiple_ans);
}
} else {
if(poll_answer_id > 0) {
poll_process();
} else {
set_is_being_voted(false);
alert(pollsL10n.text_valid);
}
}
} else {
alert(pollsL10n.text_wait);
}
});
}
The problem is the new checkbox(terms & conditions) that is added inside the form.
If you can change the poll_vote function...
Change
<label class="check-terms"><input type="checkbox">
to
<label class="check-terms"><input type="checkbox" class="check-terms">
then
a("#polls_form_" + poll_id + " input:checkbox, #polls_form_" + poll_id + " input:radio, #polls_form_" + poll_id + " option")
to
a("#polls_form_" + poll_id + " input:checkbox, #polls_form_" + poll_id + " input:radio, #polls_form_" + poll_id + " option").not('.check-terms')