I'm using this function with an unordered list (<ul>) in order to replicate the functionality of a Select dropdown element. The function correctly shows the user's selected values in the designated container when they are checked, but it isn't removing them when an item is unchecked.
I've included the relevant snippet below, and posted a working example with the complete code here: http://jsfiddle.net/chayacooper/GS8dM/7/
JS
$(document).ready(function () {
$(".dropdown_box").click(function () {
$("#select_colors").show();
});
$(".dropdown_container ul li").click(function () {
var text = $(this.children[0]).find("input").val();
var currentHtml = $(".dropdown_box span").html();
$(".dropdown_box span").html(currentHtml.replace('Colors', ''));
$(".dropdown_box span").append(', ' + text);
});
});
HTML
<div class="dropdown_box"><span>Colors</span></div>
<div class="dropdown_container">
<ul id="select_colors">
<li><label><input type="checkbox" name="color[]" value="Black" />Black</label></li>
</ul>
</div>
You should give the container id to the function. Then, before you add the text of the selection, you should make sure that it is not in the text. If it is, delete it.
Related
For example, I have checkbox that can be checked or unchecked.
Whenever it is checked, I want all the elements in the HTML list to be displayed.
Whenever it is not checked, I want just some objects (that are not filtered) to be displayed, like others don't exist (I don't want white spaces etc).
The HTML (Handlebars) list:
<ol>
{{#each personList}}
<li>{{showPerson this}}</li>
{{/each}}
</ol>
Handlebars helper:
Handlebars.registerHelper('showPerson', function(person) {
return person.firstName + " " + person.lastName;
});
My filtering function looks like this:
function filterOldPeople(person) {
return person.age > 60;
}
The thing I want to achieve is something like this:
var filter; // I am getting this boolean value from checkbox
if (filter) {
doFilter(); // will filter the HTML list that is already rendered
}
Now I don't know how the function doFilter() should look like to achieve this. Now with jQuery the problem is I can get the HTML object of list item but not the actual person object so this won't work:
$( "li" ).filter(filterOldPeople).addClass("hide");
And something like that is exactly what I need. How do I achieve this?
Here you go! Only thing you want to do is to place all elements you want to hide in one div and then hide it, it is alot of easier to hide one element than couple of them.
function check() {
if (document.getElementById("test").checked == true) {
document.getElementById("two").style.display = "none";
} else {
document.getElementById("two").style.display = "block";
}
}
<div class="info">
<div id="one">
If you click on me, #two will hide.
<input type="radio" id="test" onclick="check()">
</div>
<div id="two">
Hi, click on the button!
</div>
</div>
If you don't want to use two lists, you could modify using something like the following (add code to function as needed):
HTML
<ul id="theList">
<li class="number">One</li>
<li>Red</li>
<li class="number">Two</li>
<li>Green</li>
<li class="number">Three</li>
<li>Blue</li>
</ul>
<br /><input type="checkbox" id="numbers" checked><label for="numbers">Show Numbers</label>
JS
$('#numbers').change(function() {
$('.number').hide();
});
https://jsfiddle.net/1ngotz5u/
How I would approach this would be:
function filterOldPeople(person) {
return person.age > 60;
}
// Get all li Elements (useful so we don't have to search the dom multiple times)
var liElements = $("li");
// loop through each li and filter it.
function filterAges() {
liElements.each(function () {
if (filterOldPeople($(this).val())) {
$(this).addClass("hide");
}
});
}
// Show all hidden elements by removing the hide class
function showAll() {
liElements.removeClass("hide");
}
// Create our event
$("#checkbox").change(function () {
if ($(this).is(":checked")) {
filterAges();
} else {
showAll();
}
});
I have a list in JQuery that's called additionalInfo, which is filled in using this JQuery function:
$('#append').on('click', function () {
//check if the following area is valid before moving on, check the jquery validation library
var text = $('#new-email').val();
var li = '<li>' + text + 'input type="hidden" name="additionalInfo" value="'+text+'"/> </li>';
$('#additional-info-list').append(li);
$('#new-email').val('');
});
The point of the function is not only to store the info in a list that can be used later, but also to render a <li> with the info text in it. Right now I have another button on each <li> that when pressed, makes the li vanish, but I also need to add code to it that completely removes the info text from the additionalInfo list. This is the code I have for that method so far:
$('#removeEmail').on('click', 'li>.remove-btn', function (event){
$(event.currentTarget).closest('li').remove();
});
How can I get the segment of info text out of the li and then remove it from additionalInfo?
You have few problems. First of all when you create the new items, your markup is not correct. You were missing the opening bracket of input tag. Also i changed the code for delete so that it listens for the click event on any item with class remove-btn under the li element. This should delete the item when you click the remove link inside the li.
$(function(){
$('#append').on('click', function () {
var text = $('#new-email').val();
var li = '<li>' + text + '<input type="hidden" name="additionalInfo"
value="'+text+'"/>
<a href="#" class="remove-btn" >remove</a></li>';
$('#additional-info-list').append(li);
$('#new-email').val('');
});
$(document).on('click', 'li>.remove-btn', function (event){
var _this =$(this);
_this.closest('li').remove();
});
});
Here is a working jsfiddle
I'm a UI Designer working on a multi-page Q&A form, I'm a beginner with jQuery mostly mashing snippets together.
Here's the code: http://codepen.io/covanant/pen/GJZYLq
This part of the form is basically multiple accordions wrapped into tabs, I have most of it working as required but one of the things I need to do, is that whenever I a choice or option, I want to be able to output that option to an element as text right underneath the question.
The element is:
<span class="selected-answer"></span>
You can see it displayed in the first question in the demo, the way that I'd like it to work is that whenever I click the Close All button, it will fadeIn the .selected-answer element and when I click Open All, it will fadeOut the .selected-answer element.
The buttons:
Open All
Close All
jQuery:
// Open All & Close All buttons
$('.closeall').click(function(){
$('.panel-collapse.in')
.collapse('hide');
});
$('.openall').click(function(){
$('.panel-collapse:not(".in")')
.collapse('show');
});
First, it doesn't make sense to give each of your select options the same value attribute. By convention, these should be distinct. If you aren't using the value attribute, you can remove it altogether. Otherwise, you should change it to something like:
<select>
<option value="None Selected">None Selected</option>
<option value="Photocell On">Photocell On</option>
<option value="Off Control Only">Off Control Only</option>
<option value="Photocell On / Off Control Only">Photocell On / Off Control Only</option>
</select>
Once that is sorted out, you need to go up the DOM hierarchy and find the right span element to change.
$('select').on('change', function() {
var span = $(this).closest('div.panel').find('span.selected-answer');
span.text($(this).val());
});
For the checkbox questions, you I would do something like this:
HTML:
<span class="selected-answer">
<ul class="checked-options">
<li data-check="checkbox1">nWifi (nLight)</li>
<li data-check="checkbox2">nLightFixtures</li>
<li data-check="checkbox3">xCella (LC&D)</li>
<li data-check="checkbox4">Daylight Harvesting</li>
<li data-check="checkbox5">xPoint (LC&D)</li>
<li data-check="checkbox6">nWifi (nLight)</li>
</ul>
</span>
CSS:
.checked-options li {
display: none;
}
jQuery:
$('input[type="checkbox"]').on('change', function() {
var checkbox = $(this);
var id = checkbox.attr('id');
if ($(this).prop('checked'))
$('li[data-check="' + id + '"]').show();
else
$('li[data-check="' + id + '"]').hide();
});
As for the fading, this should do the trick:
// Open All & Close All buttons
$('.closeall').click(function(){
$('.panel-collapse.in')
.collapse('hide');
$('.selected-answer').fadeIn();// <-- Fade in
});
$('.openall').click(function(){
$('.panel-collapse:not(".in")')
.collapse('show');
$('.selected-answer').fadeOut();// <-- Fade out
});
Also, depending on whether you want all the questions open or closed by default when the form first loads, you may need to hide all the .selected-answer elements on page load.
Here's the updated codepen.
I agree with VCode on using distinct values for each option in the select elements. But instead of using the value you provide for each option, I think you should use the actual label, that way you can have a more description label, than the option value.
I modified a few of your existing functions to actually populate the selected answer. First I noticed that you already have a function for handling changes to your select - in there I added a small snippet to get the selected answer and pass it to nextQuestion.
$(".panel-body select").change(function() {
var selectElem = $(this);
var answer = selectElem.find("option:selected").text();
nextQuestion(selectElem, answer);
});
Then you also have input elements. Here is your modified input change function:
$(".panel-body input").change(function() {
var inputElem = $(this);
var inputType = inputElem.attr('type');
// common parent for input
var commonParent = inputElem.closest(".panel-body");
var answers = commonParent
.find("input:checked")
.closest("."+inputType)
.find("label")
.map(function(){return this.innerText;})
.get()
.join(", ");
nextQuestion(inputElem, answers);
});
And now as you may have noticed, I added a parameter to the nextQuestion function. I put this code in nextQuestion because you were already accessing the parent there so I wanted to re-use that logic to populate the selected answer.
function nextQuestion(currentQuestion,selectedAnswer) {
var parentEle = currentQuestion.parents(".panel");
if (arguments.length>1) {
parentEle.find('.selected-answer').text(selectedAnswer);
}
if (parentEle.next()) {
parentEle.find(".fa-question").addClass("fa-check check-mark").removeClass("question-mark fa-question").text("");
}
}
Just like VCode mentioned, you can do the fading of the answers using fadeIn/fadeOut
// Open All & Close All buttons
$('.closeall').click(function(){
$('.panel-collapse.in')
.collapse('hide');
$('.selected-answer').fadeIn();// <-- Fade in
});
$('.openall').click(function(){
$('.panel-collapse:not(".in")')
.collapse('show');
$('.selected-answer').fadeOut();// <-- Fade out
});
// hide all .selected-answers
$('.selected-answer').hide();
Here is a link to your codepen with my modifications: http://codepen.io/anon/pen/ZGpXXK
My site has a column of checkboxes with IDs in sequential order like "keepbox1", "keepbox2", etc. Each checkbox resides within a list item, along with a href attribute like this:
<li>
Title
<br>
<input id="keepbox1" type="checkbox" class="kboxes" name="keepbox1" />
<label for="keepbox1">Keep</label>
<div class="tinybox" alt="tinypic1" id="tinypic1" style="display:none;">
Content Here
</div>
</a>
</li>
There is also an element on the page that I use as button
<a><label class="getFiles" for="lightbox-two">Submit</label></a>
When a user clicks this button, I have a script that loops through each variation of keepbox to see if a user checked it. If a particular keepbox is checked, I'd like to extract the href attribute's value in that particular li.
So if a user had checked keepbox1 from the demo code above, I'd like it to alert back "http://iNeedThisUrl.com".
I'm using the following script which successfully identifies a checked keepbox, but it's returning "undefined" in the alert box. I'm guessing I'm not grabbing the attribute properly. Any ideas? Thank you!
<script type="text/javascript">
$(document).ready(function() {
$('.getFiles').click(function() {
for (i = 1; i <= 100; i++)
{
if ($("#keepbox" + i).prop('checked'))
{
var addressValue = $("#tinypic" + i).closest("li").attr("href");
alert(addressValue);
}
}
});
});
</script>
Two issues:
1) you have closing anchor tag </a> without opening anchor tag as next sibling of div in li. you need to remove it.
2) div elements #tinypic+n are siblings of anchor element. You need to use:
$("#tinypic" + i).siblings("a").attr("href");
or
$("#tinypic" + i).prevAll("a").attr("href");
or
$("#tinypic" + i).closest("li").find("a").attr("href");
$(".kboxes").each(function(){
if ($(this).prop('checked')) {
var addressValue = $(this).closest("a").attr("href");
alert(addressValue);
return false;
}
});
I`m trying to write a script that gets the ID from a checkbox element and do something with it. The problem is that I can not target the checkboxes by value since its generated from mysql query.
Here is how the html for the checkboxes looks like :
<div class="cat_checkbox cat_unchecked">
<input id="r_c136" type="checkbox" value="36" name="r_c1[]">
Sample
</div>
<div class="cat_checkbox cat_unchecked">
<input id="r_c131" type="checkbox" value="31" name="r_c1[]">
Text1
</div>
And here is the code I managed to write (I`m still learning java script and jQquery).
What I am trying to do is to tell js to select the that contains "Text1" and find the checkbox inside it, get its id and then add checked prop to the item.
But instead it selects the first div finds the checkbox inside and checks it no matter the value inside.
$( "#click" ).click(function() {
if ($( "div:contains('Text1')" ))
{
id = $("div:contains('Text1')").find("input[type='checkbox']").attr("id")+"";
alert(id);
$("#"+id).prop("checked", !($("#"+id)).is(':checked'));
}
});
});
Any help will be aprciated. Thank you.
Use $("div:contains('Text1')").length instead of $("div:contains('Text1')")
Change Your code as
$("#click").click(function () {
if($("div:contains('Text1')").length) {
var checkbox = $("div:contains('Text1')").find("input[type='checkbox']"); //Find Checkbox here
checkbox.prop("checked", !checkbox.is(':checked'));
}
});
DEMO
Change your code as
$("#click").click(function () {
var checkbox = $("div:contains('Text1')").find("input[type='checkbox']");
if (checkbox.length) {
checkbox.prop("checked", !checkbox.is(':checked'));
}
});
Updated DEMO