I want to hide and show list items based on their attributed class.
The problem is that certain list items have multiple classes. So if I toggle one class then toggle another, any items with both selected classes will be removed.
I created a demo of my problem: http://jsfiddle.net/a4NkN/2/
Here's the JS CODE:
$('#easy').click(function(){
$(this).toggleClass( "checked" );
$('.easy').toggle();
});
$('#fun').click(function(){
$(this).toggleClass( "checked" );
$('.fun').toggle();
});
$('#silly').click(function(){
$(this).toggleClass( "checked" );
$('.silly').toggle();
});
If you select the "Easy" and "Fun" buttons, Boating will disappear.
How can I get Boating to stay?
This might be a good point to start from. Although you can do this cheaper and cleaner, that gives the idea:
Use an array to save the status of your selection buttons and one corresponding to hold the class names. Whenever your select buttons get clicked, you set all your elements invisible and reset those visible again, that are already selected by other buttons or the currently clicked, which is all saved in the switcher array.
//saves whether button is active
var switcher = [false, false, false];
//holds your classes selectable
var classes = ['easy', 'fun', 'silly'];
$('.toggler').click(function () {
// toogle the select button and save status
var x = $(this).hasClass('checked');
switcher[$(this).data('switch')] = !x;
$(this).toggleClass("checked", !x);
// iterate through your elements to set them active if needed
$('li').each(function () {
var cur = $(this);
cur.addClass('hidden');
$.each(switcher, function (index, data) {
if (data && cur.hasClass(classes[index])) {
cur.removeClass('hidden');
}
});
});
});
Whole solution in this fiddle: http://jsfiddle.net/BMT4x/
You cannot unconditionally toggle elements based on a click on one of the button filters if it is possible for an element to satisfy multiple filters at once. The correct approach is a little more involved.
Since your checked class means that only items corresponding to that button should be shown, do exactly this: toggle them based on the current status of the button. The items should be shown if and only if the corresponding button is checked as a result of clicking it.
$('#easy').click(function(){
$(this).toggleClass( "checked" );
$('.easy').toggle($(this).is(".checked"));
});
This code uses the last version of .toggle, the one accepting a boolean argument.
It can also be done more succintly:
$('.easy').toggle($(this).toggleClass( "checked" ).is(".checked"));
Related
Here, I've three radio group in a single page. But in the entire page I want to select only one radio option. Like if I'm selecting Monday then Tuesday selection should be unchecked automatically. How can I proceed with the logic, below logic is not working as expected.
sample JSON :
{
report:[
{
day:'Monday',
slot:[
'9-10am',
'10-11am',
'11-12am'
]
},{
day:'Tuesday',
slot:[
'9-10am',
'10-11am',
'11-12am'
]
},{
day:'Wednesday',
slot:[
'9-10am',
'10-11am',
'11-12am'
]
}
]}
JS code
for(var I=0; I<reports.length; I++){
var radios = document.getElementsByTagName('input')
if(radios[I].type === 'radio' && radios[I].checked){
document.getElementById(radios[I].id).checked = false
}
If you're able to create radio buttons in SurveyJS, you should be able to give the button group a name, so there would be no need for any additional JavaScript. Check out their documentation for an example.
Looks like the sort of nested structure you have for the buttons could be achieved with something like a dynamic panel or cascading conditions in SurveyJS. You should be able to render the available time slots dynamically with "visibleIf" based on the selected day.
I would definitely dig around the documentation of SurveyJS to find a solution there rather than hacking your way around it. But solely as an exercise, the problem in your current code could be that you're selecting a button by ID, which will not work correctly if you have tried to give the same ID to multiple buttons. After all, you already have the target button as radios[I], so you could just use radios[I].checked = false. Or the issue could be that you're unchecking the selected button AFTER the new selection has been made, which might actually uncheck the button you just clicked. Hard to say without additional information, but in any case, looping your inputs based on a value that might be something else than the actual number of inputs (you're using reports.length) is probably not the best idea, since that value might be different from the number of inputs in your form, which would mean that not all of them are included in the loop. Here are a couple of examples of what you could do instead:
// Get all radio buttons
const radioButtons = document.querySelectorAll('input[type="radio"]')
// If you need to uncheck the previously selected one (don't do this if you can avoid it!)
radioButtons.forEach(radioButton => {
// Use a mousedown event instead of click
// This gives you time to uncheck the previous one before the new one gets checked
radioButton.addEventListener('mousedown', () => {
// Get the currently selected button and uncheck it
const currentlySelected = document.querySelector('input[type="radio"]:checked')
if (currentlySelected) currentlySelected.checked = false
})
})
// You can add further options to the querySelector, such as [name]
// This gets the currently selected button in the specified group
const checkedRadioButton = document.querySelector('input[type="radio"][name="group-name"]:checked')
Here's a fiddle demonstrating this sort of "fake" radio button functionality (without a "name" attribute).
You can give all these radio buttons the same name, then one radio only will be checked.
I am trying to prevent a paragraph element with a class attribute of 'show' from toggling away on the click event on updateButton. I've tried if else statements but to no avail.
I'm essentially trying to create an editing state when I click update button and all the text on the bottom of these buttons need to show (the paragraph elements). Though there is one button with text underneath it already which I want to prevent from toggling the class .hide.
The other buttons already have the .hide class attribute on them already so when toggled from the click event, they appear.
TLDR: I want to prevent the one paragraph element with no .hide class attribute from toggling it on when I toggle all the other paragraph elements in the .risk-text container.
// select indicator div
const riskIndicator = document.getElementById("Risk__indicator");
// select update button
const updateButton = document.getElementById("Update_button");
// Indicator buttons
const indicatorButton = document.getElementsByClassName("Risk_indicator_button");
// Indicator 'check every..' text
const checkIndicatorText = document.querySelectorAll(".risk-text");
// select update button
updateChange: updateButton.addEventListener("click", function (event) {
riskIndicator.classList.toggle("active");
});
// If statement to check whether the Risk Indicator is active to apply background changes
editState: updateButton.addEventListener("click", function(el) {
[].map.call(document.querySelectorAll('.risk-text'), function(el) {
// loop through text indicator elements checking to see if it's got a hidden class attribute
el.classList.toggle('hide');
});
});
Depending on your use case:
If you want to exclude it only once, and then toggle this element with others, do something like:
editState: updateButton.addEventListener("click", function(el) {
[].map.call(document.querySelectorAll('.risk-text:not(.hide)'), function(el) {
// loop through text indicator elements checking to see if it's got a hidden class attribute
el.classList.toggle('hide');
});
});
If you want to leave the "ember" element alone, then
editState: updateButton.addEventListener("click", function(el) {
[].map.call(document.querySelectorAll('.risk-text:not(.low_risk_text__wrap--risk-middle-amber)'), function(el) {
// loop through text indicator elements checking to see if it's got a hidden class attribute
el.classList.toggle('hide');
});
});
You can also add new class, like "spareMe", and exclude it with .not()
I want to display tables when a selection is made in a form and a 'Generate Factsheet' button is clicked. I've got a working code where I individually hide other divs when displaying the one I am interested in. Since I have several options in the form (and hence several corresponding divs in which the respective tables are enclosed), the final code appears bulky. I want to write a function to hide other divs whiles displaying the one I am interested in. This is the code I currently have:
var tableDivs = ['tableOPVDiv','tablePneumoDiv','tableRotaDiv'];
var selectedVaccine;
var selectedTableDiv;
function generateFactsheetFunction(){
// Selecting the vaccine chosen from the dropdown
var e = document.getElementById("selectVaccine");
selectedVaccine = e.options[e.selectedIndex].text;
console.log("selectedVaccine: ", selectedVaccine);
if (selectedVaccine=="Rotavirus Vaccine"){
selectedTableDiv='tableRotaDiv';
console.log("rotavirus selected");
hideOtherTables();
} else if (selectedVaccine=="Polio Vaccine"){
console.log("polio selected");
selectedTableDiv='tableOPVDiv';
hideOtherTables();
} else if (selectedVaccine=="Pneumococcal Vaccine"){
console.log("pneumo selected");
selectedTableDiv='tablePneumoDiv';
hideOtherTables();
}
}
function hideOtherTables(){
var testa = tableDivs.indexOf(selectedTableDiv);
console.log("tableDivs[testa]: ", tableDivs[testa]);
console.log("testa: ", testa);
testb = tableDivs[testa];
console.log("testb: ", testb);
document.getElementById(tableDivs[testa]).style.display="block";
/*var newTableDivs=tableDivs.splice(testa);*/
/*for (y=0;y<newTableDivs.length;y++){
document.getElementById(newTableDivs[y]).style.display="none";
}*/
}
The uncommented part works fine. In the commented part, I want to say that for all array elements other than selectedVaccine, I want the display to be:
document.getElementById(tableDivs[testa]).style.display="none";
I cannot splice the data because the selections are repititive (the selections are from a form). What is the way to set the visibility of tableDivs associated with other selections to be none.
Why should you change the display property of each and every division seperately? give a common class name to all the divisions and hide them all at once and then display only the required table.
$(".yourClass").hide();
document.getElementById(tableDivs[testa]).style.display="block";
You will have to use the jQuery Library too.
If you are not familiar with jQuery then use the for loop to hide all the tables first and then display only the required table.
for (y=0;y<TableDivs.length;y++){//you need not create newTableDivs
document.getElementById(TableDivs[y]).style.display="none";
}
document.getElementById(tableDivs[testa]).style.display="block";
i.e you just have to interchange the order of execution. ;)
Cannot read property 'style' of null this means that document.getElementById(tableDivs[y]) return null and can not find this element
try to write
document.getElementById("ElementId")
This is a solid, proper syntax set of functions, and for the life of me I can't figure out why, but the function ServiceHover() will not run unless I trigger it manually in the console, while it's almost exact equal CategoryHover() runs perfectly each time. It has to be something about the way that I'm calling the functions, and clearly there's something about functions that I fundamentally missed in javascript, because this happens to me often, where I'm unsure why my functions are not executing.
I keep my code all very well commented, so I shouldn't have to explain the functions's purposes, and furthermore, this is more a question of the fundamental execution of the functions rather than their inner functionality. Each function does work if called manually in the console.
//this function generates the content of the page based on which category the user selects,
//which services the user selects, and help maneuver through each stage of the feature selection
//so that the QuoteEngine function can display the user's selected hour count, price per hour
// and total cost of the needed service so that the user can see very clearly what services
//he is getting and where every dollar of his total cost is coming from so that the user can
//make a well informed purchase decision, and be able to clearly understand the services offered
//and related pricing.
$(document).ready(function () {
function BasicDropdown() {
//hide the drop-downs to begin with
//hide element with class dropdown-category
$(".dropdown-category").hide();
//hide element with class dropdown-service
$(".dropdown-service").hide();
//when the category list title is hovered over, show the category drop-down list
//when element with class category is hovered, do this:
$(".category").hover(function () {
//show the list
$(".dropdown-category").show();
//when element with class category is no longer hovered, do this:
}, function () {
//hide the list
$(".dropdown-category").hide();
});
//when the service list title is hovered over, show the service drop-down list
//when element with class service is hovered, do this:
$(".service").hover(function () {
//show the list
$(".dropdown-service").show();
//when element with class service is no longer hovered, do this:
}, function () {
//hide the list
$(".dropdown-service").hide();
});
}
//change the selected service based on an id input
//create a function to change the selected service
function ChangeService(id) {
//clear the service list element
$(".dropdown-service").empty();
//make the name inside the service drop-down title show the new title
$("#ServiceOutput").text(ServiceArray[id][0][1]);
//loop through the chosen section of the service array for as many times as the
//section is in length
for (var i = 0; i < ServiceArray[id].length; i++) {
//each loop, append a paragraph element with a data key equal to the current
//loop count, an id equal to the id of the array area based on the loop count,
//and also insert the element's text according to that loop count also.
$(".dropdown-service").append('<p data-key="' + i + '" id="' + ServiceArray[id][i][0] + '">' + ServiceArray[id][i][1] + "</p>");
}
//set the variable "Category" to be equal to the chosen id.
Category = id;
}
function CategoryHover() {
//make the category drop-down list open and show its list of services
//when the user hovers over an element in the category drop-down, do this:
$(".dropdown-category > p").hover(function () {
//hide the welcome wrapper
$(".welcomeWrapper").hide();
//set the variable "thisKey" based on the value of the data "key" attached
thisKey = $(this).data("key");
//create a variable "outputList" and assign a value to it from "CategoryArray"
outputList = CategoryArray[thisKey];
//set the title of the category drop-down lists title to the currently hovered text
$("#CategoryOutput").text($(this).text());
//call the ChangeService function and pass the variable "thisKey" into it
ChangeService(thisKey);
//show the service drop-down list
$(".dropdown-service").show();
//show the ListOutput element (this shows a short description of the hovered element)
$(".ListOutput").show();
//append the variable "outputList" as the value of a paragraph element
$(".ListOutput").append('<p>' + outputList + '</p>');
}, function () {
//hide the service drop-down list
$(".dropdown-service").hide();
//empty the ListOutput element
$(".ListOutput").empty();
//hide the ListOutput element
$(".ListOutput").hide();
//show the welcome wrapper again
$(".welcomeWrapper").show();
});
}
function ServiceHover() {
//make the service drop-down list open and show the list of services for the category
//when the user hovers over an element in the service drop-down, do this:
$(".dropdown-service > p").hover(function () {
//hide the welcome wrapper
$(".welcomeWrapper").hide();
//set the variable "thisKey" based on the value of the data "key" attached
thisKey = $(this).data("key");
//create a variable "outputList" and assign a value to it from "CategoryArray"
outputList = ServiceArray[Category][thisKey][2][0];
//show the ListOutput element (this shows a short description of the hovered element)
$(".ListOutput").show();
//append the variable "outputList" as the value of a paragraph element
$(".ListOutput").append('<p class="blue">' + outputList + '</p>');
}, function () {
//empty the ListOutput element
$(".ListOutput").empty();
//hide the ListOutput element
$(".ListOutput").hide();
//show the welcome wrapper again
$(".welcomeWrapper").show();
});
}
BasicDropdown();
CategoryHover();
ServiceHover();
//initiate
ChangeService(0);
});
What am I doing wrong with these calls?
JS Fiddle: http://jsfiddle.net/gbJcg/4/
Note: I mentioned in my question but for some reason the update didn't show up, that all of the arrays should be assumed defined. I'll now include them to remove confusion, but it will make the scripts extensively long
Added detail: ChangeCategory works. ChangeService doesn't appear to. If I copy and paste ChangeService, however, in the console, and call it, in the console, the functionality works perfectly. Does that help? I have no idea what I'm doing wrong here...
Well what I know is, since your dropdown-service is added dynamically, you need to delegated it to closest static parent present in the document which is dropdown-service in your case.
$(".dropdown-service").on("mouseenter" ,"p",function () {
..
});
$(".dropdown-service").on("mouseleave" ,"p",function () {
...
});
Since live is deprecated in latest version of jQuery you need to use on delegated event and break the hover into mouseenter and mouseleave function.
fiddle here
Check your console, you have Uncaught ReferenceError: ServiceArray is not defined
This Exception is thrown and the rest of the program is not ran
EDIT: after fiddle changed with the missing Arrays initialization is seems like the code works. I added alerts in the begining of 2 functions to make sure they are called (see http://jsfiddle.net/gbJcg/3/)
EDIT #2:
The call to $(".dropdown-service > p").hover(...) is done when you do not have any elements that respond to ".dropdown-service > p" selector, They are probably added later via ajax or some other html manipulation that is done by js
You should use the equivalent for jquery live instead:
$(document).on("mouseenter",".dropdown-service > p",function() {
....
});
$(document).on("mouseleave",".dropdown-service > p",function() {
....
});
On clicking a radio button in radiogroup2, the selected radio should swap positions with the radio with the id='selectedradio'. fiddle http://jsfiddle.net/DCC66/6/ --- updated --- clear view of radio rows and code is swapping but cancelling out http://jsfiddle.net/DCC66/14/
tried this to sort the id issue: http://jsfiddle.net/DCC66/18/
$(".radiogroup2 input[type='radio']").on('click', function () {
$('#radioselected').closest('label').before($(this).closest('label'));
$(this).closest('label').after($('#radioselected').closest('label'));
$(this).attr('domaintype', 'radioselected');
$('radioselected').attr('radioselected', 'domaintype');
});
and now this:// swaps once then stops and then just makes the clicked radio disapear. think it needs to add the id="radioselected" to the newly swapped radio. also still not swapping though only replacing radio.
$(".radiogroup2 input[type='radio']").on('click', function ()
{
$('#radioselected').closest('label').replaceWith($(this).closest('label'));
});
trying using clone still no luck:
$("div.radiogroup2 input[name='domain_ext']").click(function ()
{
$(this).clone('#radioselected').after(this);
});
Original
$("div.radiogroup2 input[name='domain_ext']").click(function()
{
//only if a the radio in radiogroup to are clicked take radio and swap with id='radioselected'
if ($(this).prop('checked'))
{
$(this).after('#radioselected').add(this);
$('#radioselected').after(this);
}
});
so any radio clicked in the "swap" row should switch positions with the radio in the first row with the id 'selectedradio'
Use a delegate instead of binding the event on the radio buttons directly. That way the radio buttons that are swapped into the div will also work.
Use the closest method to get the label around the radio buttons.
Remove the id from the radio button that you swap with, and add it to the selected radio button.
Use the after method to move the label into the second list next to the selected one, then use prependTo to move the label with the selected radio button into the first list.
You have some invalid HTML code that makes the rows swap place. Change <td><tr> to <tr><td>.
$("div.radiogroup2").on("click", ":radio", function () {
var l = $(this).closest('label');
var r = $('#radioselected');
r.removeAttr('id');
l.after(r.closest('label'));
$(this).attr('id', 'radioselected');
l.prependTo('.radiogroup1');
});
Demo: http://jsfiddle.net/DCC66/16/