I'm building a simple shopping cart where visitors can select a few items they want, click on the "Next" button, and see the confirmation list of things they just selected. I would like to have the confirmation list shown on each line for each item selected.
HTML selection
<div id="c_b">
<input type="checkbox" value="razor brand new razor that everyone loves, price at $.99" checked>
<input type="checkbox" value="soap used soap for a nice public shower, good for your homies, price at $.99" checked>
<input type="checkbox" value="manpacks ultimate choice, all in 1, price at $99">
</div>
<button type='button' id='confirm'>Next</button>
HTML confirmation list
<div id='confirmation_list' style='display:none;'>
<h2>You have selected item 1</h2>
<h2>Your have selected item 2 </h2>
</div>
JS
$(function(){
$('#confirm').click(function(){
var val = [];
$(':checkbox:checked').each(function(i){
val[i] = $(this).val();
});
});
});
I ultimately want to replace the words 'Your have selected item 2' in h2s with the values selected from each check box. With the code above I'm able to collect the values of each checkbox into an array val, but having difficulty looping through and displaying them.
Any advice would be appreciated.
Try
$(function () {
$('#confirm').click(function () {
var val = [];
var els = $('input:checkbox:checked').map(function (i) {
return $('<h2 />', {
text: 'You have selected item \'' + this.value + '\''
})
}).get();
$('#confirmation_list').empty().append(els).show()
});
});
Demo: Fiddle
Try this
<div id="c_b">
<input type="checkbox" value="razor brand new razor that everyone loves, price at $.99" checked>
<input type="checkbox" value="soap used soap for a nice public shower, good for your homies, price at $.99" checked>
<input type="checkbox" value="manpacks ultimate choice, all in 1, price at $99">
</div>
<button type='button' id='confirm'>Next</button>
<div id='confirmation_list' style='display:none;'>
</div>
Your JS code should be
$(function () {
$('#confirm').click(function () {
$("#confirmation_list").empty();
$('input:checkbox:checked').each(function (i) {
$("#confirmation_list").append("<h2>You have selected item '" + $(this).val() + "'</h2>");
});
$("#confirmation_list").show();
});
});
Fiddle
Related
I have 2 radio buttons that switch on selected. When one of the two radio buttons is selected, there should be a description for it, when the other is selected, the description should change.
The code below does pretty much what I want, but the problem is it does it on CLICK. One of the radio buttons will come as pre-selected (with 'checked' attribute) and a description isn't going to show up until the user clicks a radio button. Thus I would like for the description to match the corresponding radio button if one of them is pre-checked.
$(document).ready(function(){
$('input[name="subscription-type"]').click(function(){
var inputValue = $(this).attr("value");
var targetBox = $("." + inputValue);
$(".subscription-desc").not(targetBox).hide();
$(targetBox).show();
});
});
.subscription-desc {
display: none;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="radio-toolbar-3">
<input type="radio" id="classic" name="subscription-type" value="classic" class="choose" checked>
<label for="classic">Classic</label>
<input type="radio" id="adventurer" name="subscription-type" value="adventurer" class="choose">
<label for="adventurer">Adventurer</label>
</div>
<div class="classic subscription-desc">
Description 1
</div>
<div class="adventurer subscription-desc">
Description 2
</div>
Basically in the above, "Classic" option will come as pre-selected, but there is no description for it until the user clicks it.
Seems like a simple problem but I just can't find a solution for it. Any help appreciated. Thanks
You can trigger the .click event on the :checked radio button so that it fires the click event:
$('input[name="subscription-type"]:checked').click();
$(document).ready(function() {
$('input[name="subscription-type"]').click(function() {
var inputValue = $(this).attr("value");
var targetBox = $("." + inputValue);
$(".subscription-desc").not(targetBox).hide();
$(targetBox).show();
});
$('input[name="subscription-type"]:checked').click();
});
.subscription-desc {
display: none;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="radio-toolbar-3">
<input type="radio" id="classic" name="subscription-type" value="classic" class="choose" checked>
<label for="classic">Classic</label>
<input type="radio" id="adventurer" name="subscription-type" value="adventurer" class="choose">
<label for="adventurer">Adventurer</label>
</div>
<div class="classic subscription-desc">
Description 1
</div>
<div class="adventurer subscription-desc">
Description 2
</div>
Alternatively, you can extract the code that does the display into a function and call that:
function updateSubscription() {
var inp = $('input[name="subscription-type"]:checked');
var inputValue = $(inp).attr("value");
var targetBox = $("." + inputValue);
$(".subscription-desc").not(targetBox).hide();
$(targetBox).show();
}
$(document).ready(function() {
$('input[name="subscription-type"]').click(updateSubscription);
updateSubscription();
});
function updateSubscription() {
var inp = $('input[name="subscription-type"]:checked');
var inputValue = $(inp).attr("value");
var targetBox = $("." + inputValue);
$(".subscription-desc").not(targetBox).hide();
$(targetBox).show();
}
$(document).ready(function() {
$('input[name="subscription-type"]').click(updateSubscription);
updateSubscription();
});
.subscription-desc {
display: none;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="radio-toolbar-3">
<input type="radio" id="classic" name="subscription-type" value="classic" class="choose" checked>
<label for="classic">Classic</label>
<input type="radio" id="adventurer" name="subscription-type" value="adventurer" class="choose">
<label for="adventurer">Adventurer</label>
</div>
<div class="classic subscription-desc">
Description 1
</div>
<div class="adventurer subscription-desc">
Description 2
</div>
Note you can also use
var inputValue = $('input[name="subscription-type"]').val()
instead of
var inp = $('input[name="subscription-type"]:checked');
var inputValue = $(inp).attr("value");
I've kept the code above close to your original, just replacing the clicked this with $('input[name="subscription-type"]:checked')
Another alternative is to show the correct description at the time of load - this way you also don't get the "FOUC" (flash of unstyled content) where the description is displayed only after the page has fully loaded.
How you do this will depend on how you set the 'checked' value on the radio at page load, so may not be a suitable solution.
I have a checkboxes like this:
while($userRow=$resultForUsers->fetch_assoc()){
$nameOfUser=$userRow['users_name'];
$userId=$userRow['user_facebook_id'];
$userFBPicture=$userRow['users_picture'];
echo "
<tr class='tr-data-users'>
<td class='text-center'>
<input type='checkbox' class='checkbox' onclick='if(this.checked){selo(this.value)}else{izbaci(this.value)}' value=$userId>
</td>
So, for each user in my database I'm having one checkbox with value of his id. I need id's of all checked users(i.e checkboxes) in one array. I did it this way:
<input type='checkbox' class='checkbox' onclick='if(this.checked){put(this.value)}else{remove(this.value)}' value=$userId>
var niz={};
var index=0;
function put(o){
niz[index++]=o;
console.log(niz);
}
So, console.log now displays id's of all checked checkboxes. What I want to do is if checkbox is unchecked then to remove that id(i.e chechbox value) from array. I tried it like this:
onclick='if(this.checked){put(this.value)}else{remove(this.value)}'
var niz={};
var index=0;
function put(o){
niz[index++]=o;
console.log(niz);
remove(o,niz);
}
function remove(o,niz){
if($.inArray(o,niz)){
console.log('radim');
var indexNiza= $.inArray(o,niz);
niz= $.grep(niz,function(a,o){
return (a!=o);
});
}
}
As you can see this else part should handle if checkbox is unchecked and remove that id from array, but it doesn't work. Would really appreciate help on this.
It seems that the code you have written is taking a very complex route for a simple job. You can see the following for a good example on how to obtain all of the values into their own arrays for the checked and unchecked states.
In the demonstration, I enumerate through the checked and unchecked checkboxes if the user changes the state of any checkbox, and store the checked values in an array named cbChecked and the unchecked values get stored in cbUnchecked
The key here is the selectors used:
Selector usage
Get all 'checked' objects
:checked
Get all 'unchecked' objects
:not(:checked)
Demonstration
$(document).ready(function() {
$("input[type='checkbox']").change(function() {
var cbChecked = new Array();
var cbUnchecked = new Array();
$("input[type='checkbox']:checked").each(function() {
cbChecked[cbChecked.length] = this.value;
});
$("input[type='checkbox']:not(:checked)").each(function() {
cbUnchecked[cbUnchecked.length] = this.value;
});
$("p#cbChecked").html( cbChecked.join() );
$("p#cbUnchecked").html( cbUnchecked.join() );
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<h2> The checkbox form</h2>
<form id="foo">
<p>A : <input type="checkbox" id="a" value="a"></p>
<p>B : <input type="checkbox" id="b" value="b"></p>
<p>C : <input type="checkbox" id="c" value="c"></p>
<p>D : <input type="checkbox" id="d" value="d"></p>
<p>E : <input type="checkbox" id="e" value="e"></p>
<p>F : <input type="checkbox" id="f" value="f"></p>
</form>
<h2>Checked Values</h2>
<p id="cbChecked"></p>
<h2>Unchecked Values</h2>
<p id="cbUnchecked"></p>
UPDATE
I have now solved it, changing this line:
idList.push(this.id);
to:
$(this).attr('id')
I am trying to loop through all of the checkboxes on my page and add the ID's of all that are checked to an array. I have it looping through each checkbox, and detecting whether or not it is checked, but I am having trouble adding the ID of each checked checkbox to an array.
Could someone tell me where I am going wrong?
Thanks.
Javascript:
if (element == 'deleteButton' || element == 'allowButton')
{
//For testing.
//alert("Button Clicked");
//Create an empty array, so it can be re-sized at run time.
var idList = [];
//Loop through all checkboxes, adding each ones id to an array.
$('#reported_rages').find('input[type="checkbox"]:checked').each(function () {
//this is the current checkbox
//For testing.
//alert("Checked");
//Add the current ID to the array
idList.push(this.id);
});
//return false; // or do something else.
}
alert(idList);
Here try implementing these ideas.
JSFiddle
/*sets variable to global so it can be accessed outside of function*/
var idList = [];
function run(){
/*clears the original variable*/
idList = [];
$('#data').find('input[type="checkbox"]:checked').each(function () {
idList.push(this.id);
});
/*prints after list is populated*/
console.log(idList);
$('#results').html(idList);
}
/*binds run function to click of submit*/
$('#submit').click(run);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id='data'>
<input id='1' type='checkbox' />
<input id='2' type='checkbox' />
<input id='3' type='checkbox' />
<input id='4' type='checkbox' />
<input id='5' type='checkbox' />
</div>
<div id='results'></div>
<button id='submit'>Submit</button>
I have an app I am creating, I've been able to get through it so far relatively hassle free. Until now. At the moment I need to find a way to keep the information produced by if statements for a check box. I have been able to get this working for a radio button by just storing the data in a global variable but I am not sure how to with a check box.
Code:
if ($('#Chk_0').is(':checked')) {
check = "Check1" + ", ";
countCheck++;
}
if ($('#Chk_1').is(':checked')) {
check = "Check2" + ", ";
countCheck++;
}
if (countCheck == 0) {
Check = "Nothing is checked";
}
Checkbox:
<div data-role="collapsible" id="cCheck" class="hCheck">
<h3>CheckBox</h3>
<div data-role="fieldcontain">
<fieldset data-role="controlgroup">
<legend>Option</legend>
<input type="checkbox" name="Check" id="Check_0" class="custom" value="" />
<label for="Check_0">Check1</label>
<input type="checkbox" name="Check" id="Check_1" class="custom" value="" />
<label for="Check_1">Check2</label>
</fieldset>
</div>
</div>
You can use an array and a string.
var checkedOptions=[]
var checkedGroup="";
if ($('#Check_0').is(':checked')) {
if(checkGroup=="Check"){
checkedGroup.push("Check_0");
}
else
{
checkGroup="Check"
checkedGroup=["Check0"];
}
countCheck++;
}
BTW: You have an error in your code. The IDs of the input tags and the jQuery are not the same.
As i understand your question ,you need to know is any check box is checked and if any checked you need the ids so this may be help
var ids = '';
$(':checked').each(function (i, element) {
ids += $(element).prop('id')+",";
})
then you can chekc if ids has length
if (ids.length>0) {
//use ids variable here
}
I have simple code for filtering multiple item, so far its working
Here is the code :
<div class="container btn-group tags" data-toggle="buttons">
<label class="btn btn-primary active" id="myBtn">
<input type="checkbox" rel="arts" /> Arts
</label>
<label class="btn btn-primary" id="myBtn">
<input type="checkbox" rel="computers" /> Computers
</label>
<label class="btn btn-primary" id="myBtn">
<input type="checkbox" rel="health" /> Health
</label>
<label class="btn btn-primary" id="myBtn">
<input type="checkbox" rel="video-games" /> Video Games
</label>
</div>
<div class="container">
<div class="results">
<div class="container arts computers">
Result 1
</div>
<div class="container video-games">
Result 2
</div>
<div class="container computers health video-games">
Result 3
</div>
<div class="container arts video-games">
Result 4
</div>
</div>
</div>
and this is the script :
$('div.tags').delegate('input[type=checkbox]', 'change', function()
{
var $lis = $('.results > div'),
$checked = $('input:checked');
if ($checked.length)
{
var selector = $checked.map(function ()
{
return '.' + $(this).attr('rel');
}).get().join('');
$lis.hide().filter(selector).show();
}
else
{
$lis.show();
}
});
My question is, if i have filter let said A - Z letter, and some one select A & M how to displaying the letter that he selected? and give an option to clear all the field by clicking clear button?
here is the fidle http://jsfiddle.net/nucleo1985/g9SAQ/
Thanks,
Updated your fiddle to ALERT when a box is checked (so you can see how to display value of checkbox checked) and added a button to clear all (so you can see how to reset result list and clear all checkbox checks)
Working Fiddle Demo
<button onclick="$('input:checkbox').removeAttr('checked');$('.results > div').show();$('.checkedItem').html('');">Clear All</button>
i've added a new div to put the last checked box value into:
<div class="checkedItem">checked item will go here once clicked</div>
and here is how its put in:
$('.checkedItem').html($(this).attr('rel'));
Remove the id="myBtn" as id must be unique and add class category to the checkboxes
Also add a checkbox whose id is clear to clear the div like,
$('div.tags').delegate('#clear', 'change', function() {
$('.category').prop('checked',false);
$('.results > div').hide();
});
And modfy your category checkboxes like,
$('div.tags').delegate('input[type=checkbox].category', 'change', function() {
if($('.category:checked').length){// if clear is checked then uncheck it
$('#clear').prop('checked',false);
}
var $lis = $('.results > div'),
$checked = $('input.category:checked');
if ($checked.length){
var selector = $checked.map(function (){
return '.' + $(this).attr('rel');
}).get().join(', '); // join the array with ', '
$lis.hide().filter(selector).show();
} else{
$lis.show();
}
});
Demo
Updated, if you want to show active div's try this,
CSS
.active{
background:#BBE4E7;
}
In Jquery replace the lines
$lis.hide().filter(selector).show(); by $lis.removeClass('active').filter(selector).addClass('active');
$('.results > div').hide(); by $('.results > div').removeClass('active');
Updated Demo