Keeping data from detached Checkbox - javascript

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
}

Related

jQuery to hide divs that don't match selected classes

I'm trying to use jQuery to filter through some product search results.
There are various types of filters one could use to dig through the results (color, type, size, etc) and I would like to make it impossible to end up with "no results" through the filters by hiding the ones that do not have any content as filters are engaged.
I suppose another way of phrasing my question would be that I'm trying to verify what filters should exist before allowing the user to activate them.
For example in the sample code, if #brnd_B was selected and no products contained .prdbx.brnd_B.ptype_C, then #ptype_C should be disabled so the user cannot select it.
The #col_Red option should be disabled once any of the filters are engaged since it doesn't exist within the products list. #cat_C sould be disabled for the same reason.
Then the appropriate .prdbx boxes should display after filtering, obviously.
Sample Code:
<h1>Brands</h1>
<input type="radio" class="bFilter filterSwitch" name="bFilter" id="brnd_A">
<input type="radio" class="bFilter filterSwitch" name="bFilter" id="brnd_B">
<input type="radio" class="bFilter filterSwitch" name="bFilter" id="brnd_C">
<h1>Types</h1>
<input type="radio" class="pTypeFilter filterSwitch" name="pTypeFilter" id="ptype_A">
<input type="radio" class="pTypeFilter filterSwitch" name="pTypeFilter" id="ptype_B">
<input type="radio" class="pTypeFilter filterSwitch" name="pTypeFilter" id="ptype_C">
<h1>Options</h1>
<input type="radio" class="bTypeFilter filterSwitch" name="bTypeFilter" id="cat_A">
<input type="radio" class="bTypeFilter filterSwitch" name="bTypeFilter" id="cat_B">
<input type="radio" class="bTypeFilter filterSwitch" name="bTypeFilter" id="cat_C">
<h1>Colors</h1>
<input type="radio" class="cTypeFilter filterSwitch" name="cTypeFilter" id="col_Black">
<input type="radio" class="cTypeFilter filterSwitch" name="cTypeFilter" id="col_Blue">
<input type="radio" class="cTypeFilter filterSwitch" name="cTypeFilter" id="col_Red">
<h1>Products</h1>
<div class="prdbx show brnd_A cat_B ptype_C col_Black yld_Standard mod_PIXMAiP4820 mod_PIXMAiX6520 mod_PIXMAiX6550">Data 1</div>
<div class="prdbx show brnd_B cat_A ptype_A col_Blue yld_Standard mod_PIXMAiX6520">Data 2</div>
<div class="prdbx show brnd_A cat_A ptype_B col_Black yld_Standard mod_PIXMAiP4820">Data 3</div>
This is the jQuery I have so far; it's displaying the appropriate .prdbx's for the most part, but it never "verifies the radio button should be allowed" before displaying them, which is what I'm struggling with.
If I make the sep variable a comma, I get mixed results, as well.
Any help would be greatly appreciated.
$('.filterSwitch').click(function(e) {
$('.brandbx').hide();
$('.prdbx').hide(); // hide all products
// set up variables
thisFilter1 = "";
var sep = ""
// hide inapplicable filters
// figure out what we're displaying
$('input[name=bFilter]:checked').each(function(e) {
thisFilter1 = thisFilter1 + sep + '.'+this.id;
});
$('input[name=bTypeFilter]:checked').each(function(e) {
thisFilter1 = thisFilter1 + sep + '.'+this.id;
});
$('input[name=pTypeFilter]:checked').each(function(e) {
thisFilter1 = thisFilter1 + sep + '.'+this.id;
});
$('.cTypeFilter').each(function(e) {
thisFilter1 = thisFilter1 + sep + '.'+this.id;
});
$(thisFilter1).show();
verifyEmpty();
});
function verifyEmpty(){
var totalFilter = 0;
$('input[name=bFilter]:checked').each(function(e) {
totalFilter++;
});
$('.cTypeFilter:checked').each(function(e) {
totalFilter++;
});
$('.pTypeFilter:checked').each(function(e) {
totalFilter++;
});
$('.bTypeFilter:checked').each(function(e) {
totalFilter++;
});
if(totalFilter == 0){
$('.prdbx').show(); // show all products
$('.brandbx').show(); // show models
}
}
You can try following code
$('.filterSwitch').each(function(){
if($("."+this.id).length<=0)
this.disabled=true;
});
This is considering that even if one radio button is selected and others are blank it should filter the values(as your code works now).
If its not the case & you want all the radio buttons to be selected before filtering then the code will be different.

Checkboxes, javascript runs 2 times through function if I click on text

I want to click on a checkbox and if I click this box it should run a function what gets an ID and saves it into an array or deletes it from the array if it still exists in the array.
That works, but if I click on the text beside the box the function runs twice. It first writes the ID into the array and then deletes it.
I hope you can help me so that I can click on the text and it just runs once
HTML
<label><input type="checkbox" value="XXX" >Active</label>
JavaScript/jQuery
function addOrRemoveBoxes(ID){
if(boxArr.indexOf(ID) != -1){
removeFromArray(ID)
}
else{
boxArr.push(ID);
}
}
$(".checkBoxes").unbind().click(function() {
event.stopPropagation();
addOrRemoveBoxes($(this).find('input').val());
});
The problem is probably that your label and your input are picking the click. Try to bind it only to input. Like this:
$(".checkBoxes input").unbind().click(function() {
event.stopPropagation();
addOrRemoveBoxes($(this).find('input').val());
});
Your HTML is structured bad. When your label is clicked it triggers a click event for the input so you have to separate the input form the label like: <input type="checkbox" name="opt1" id="opt1_1" value="ENG"> <label for="opt1_1">hello</label>. Also your jQuery makes no sense, why do you use unbind()? And we can't see what removeFromArray() does (we can guess but I prefer to see all code used or note that you use pseudo code).
I made this in 5 min: (hopes it helps you)
$(document).ready(function(){
window.boxArr = [];
$(document).on('click','[name=opt1]',function(){
addOrRemoveBoxes(this.value);
//show contents of boxArr
if(boxArr.length == 0){
$('#output').html('nothing :/');
}
else{
$('#output').html(boxArr.join(" -> "));
}
});
});
function addOrRemoveBoxes(ID){
var arrayIndex = boxArr.indexOf(ID);
if(arrayIndex > -1){
boxArr.splice(arrayIndex, 1);
}
else{
boxArr.push(ID);
}
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<h1>Choose</h1>
<input type="checkbox" name="opt1" id="opt1_1" value="ENG"> <label for="opt1_1">hello</label> <br>
<input type="checkbox" name="opt1" id="opt1_2" value="DUT"> <label for="opt1_2">hallo</label> <br>
<input type="checkbox" name="opt1" id="opt1_3" value="SWE"> <label for="opt1_3">hej</label>
<br><br><h2>Array contains:</h2>
<div id="output">nothing :/</div>
Side note: with [name=opt1] we select all the elements with name="opt1" attribute.

jQuery adding a numerical value to a span element

I have a HTML span element as shown below.
<span id="total_cost">4.99</span>
Then two following input elements as shown below (one radio field and one checkbox).
<!-- radio field -->
<input type="radio" name="delivery_method" value="standard" checked> standard (FREE)
<input type="radio" name="delivery_method" value="signed"> Signed (2.00)
<input type="radio" name="delivery_method" value="guaranteed"> Guaranteed (6.22)
<!-- checkbox -->
<input type="checkbox" value="digital" name="digital"> Digital copy (2.00)
On selection I would like what the user pressed for the radio field and checkbox field to be added to the value in the span element #total_cost. I would like to use jQuery for this solution.
I have got the radio fields working using javascript but I would like to use jQuery and I also can't get the checkboxes to work as well. Code for javascript shown below.
<script type="text/javascript">
$('input[name="delivery_method"]').on('change', function(){
if ($(this).val()=='signed') {
$("#delivery_price").html("£2.00");
$("#delivery_method").html("Royal Mail Signed For First Class");
$("#total_cost").html("£<?php echo ($item)*4.99 + 2.00; ?>");
} else if($(this).val()=='guaranteed') {
$("#delivery_price").html("£6.22");
$("#delivery_method").html("Royal Mail Special Delivery Guaranteed by 1PM");
$("#total_cost").html("£<?php echo ($item)*4.99 + 6.22; ?>");
} else {
$("#delivery_price").html("£0.00");
$("#delivery_method").html("Royal Mail First Class");
$("#total_cost").html("£<?php echo ($item)*4.99; ?>");
}
});
</script>
Any help would be greatly appreciated.
Many thanks in advance!
Try
<span id="total_cost">4.99</span>
<!-- radio field -->
<input type="radio" name="delivery_method" value="standard" data-price="0.00" data-method="Royal Mail First Class" checked />standard (FREE)
<input type="radio" name="delivery_method" value="signed" data-price="2.00" data-method="Royal Mail Signed For First Class" />Signed (2.00)
<input type="radio" name="delivery_method" value="guaranteed" data-price="6.22" data-method="Royal Mail Special Delivery Guaranteed by 1PM" />Guaranteed (6.22)
<!-- checkbox -->
<input type="checkbox" value="digital" name="digital" />Digital copy (2.00)
then
$('input[name="delivery_method"], input[name="digital"]').on('change', function () {
var $del = $('input[name="delivery_method"]:checked');
var $dig = $('input[name="digital"]');
$("#delivery_price").html('£' + $del.data('price'));
$("#delivery_method").html($del.data('method'));
var price = (parseFloat($del.data('price')) || 0) + ($dig.is(':checked') ? 2 : 0);
$("#total_cost").html('£' + price.toFixed(2));
})
Demo: Fiddle
You didn't show any code for the checkbox, so i am unsure what you have tried or why it is failing or what exactly you are trying to do with it, but if you just need the value of the checkbox
Give the checkbox an ID
<input type="checkbox" ID='digital' value="digital" name="digital"> Digital copy (2.00)
here is a sample jsfiddle
hope that's will help you: fiddle
var item = 0; //<?php echo ($item) ?>;
$('input[name="delivery_method"]').on('change', function(){
var total = 0;
if ($(this).val()=='signed') {
$("#delivery_price").html("£2.00");
$("#delivery_method").html("Royal Mail Signed For First Class");
total = item * 4.99 + 2.00;
$("#total_cost").text(total);
} else if($(this).val()=='guaranteed') {
$("#delivery_price").html("£6.22");
$("#delivery_method").html("Royal Mail Special Delivery Guaranteed by 1PM");
total = item * 4.99 + 6.22;
$("#total_cost").html(total);
} else {
$("#delivery_price").html("£0.00");
$("#delivery_method").html("Royal Mail First Class");
total = item * 4.99;
$("#total_cost").html(total);
}
});

Finding value of a radio in a form after checked? Javascript DOM

I currently have this form, and I am trying to get the value of the radio buttons when it is checked but I continually keep on having an error, what may be the problem with the code below?
html
<form name="radioset2" id="radioset2" action="survey.html">
<fieldset>
<span class = "question"> question1 </span>
<div id = "radio1">
<label for="r_q1_id">Yes</label>
<input id="r_q1_id" type="radio" name="r_q1_name" value="yes" />
</div>
<div id = "radio2">
<label for="r_q2_id">No</label>
<input id="r_q2_id" type="radio" name="r_q1_name" value="no" />
</div>
</fieldset>
</form>
javascript
function validRadio() {
var radio_buttons = document.getElementsByName.elements['r_q1_name'];
for(var x=0; x<radio_buttons.length; x++) {
if(radio_buttons[x].checked) {
alert(radio_buttons[x].value + " button is checked");
} else {
alert(radio_buttons[x].value + " button is not checked");
}
}
return false;
}
If you are targetting modern browsers, you can simply use the :checked CSS selector with the querySelector function to get the value of the checked input. That would remove the need of looping over the inputs.
http://jsfiddle.net/4uy2V/
var val = document.querySelector('[name=r_q1_name]:checked').value;

How to know which radio is checked from a fieldset

I have the following code:
<fieldset id="dificuldade">
<legend>Dificuldade:</legend>
<input type="radio" name="dificuldade" value="facil"> Fácil </input>
<input type="radio" name="dificuldade" value="medio"> Médio </input>
<input type="radio" name="dificuldade" value="dificil"> Difícil </input>
</fieldset>
<fieldset id="tipo">
<legend>Tipo de jogo:</legend>
<input type="radio" name="Tipodejogo" value="somar"> Somar </input>
<input type="radio" name="Tipodejogo" value="subtrair"> Subtrair </input>
<input type="radio" name="Tipodejogo" value="dividir"> Dividir </input>
<input type="radio" name="Tipodejogo" value="multiplicar"> Multiplicar </input>
</fieldset>
<input type="button" value="Começa" id="button" ></input>
</form>
and here is the jsfiddle with both the html and the js http://jsfiddle.net/3bc9m/15/ . I need to store the values of the 2 fieldset so I, depending on the values picked can generate a game, but my javascript isn't returning any of them. What is wrong? I've been told that JQuery is much easier but i can't use it.
Your code on jsFiddle seems to be working fine for the most part. The only thing was that the elements output and output2 don't exist on the page.
So this code that was supposed to display the selected values wasn't working:
document.getElementById('output').innerHTML = curr.value;
document.getElementById('output2').innerHTML = tdj.value;
The part that actually retrieves the selected values is working fine.
Just add those two elements to the page, like this:
<p>Selected Values:</p>
<div id="output"></div>
<div id="output2"></div>
An updated jsFiddle can be found here.
EDIT
If a radio button from only one of the sets is selected, the code fails. You could use this code to find the selected values instead:
document.getElementById('button').onclick = function() {
var dif = document.getElementsByName('dificuldade');
var tip = document.getElementsByName('Tipodejogo');
var difValue;
for (var i = 0; i < dif.length; i++) {
if (dif[i].type === "radio" && dif[i].checked) {
difValue = dif[i].value;
}
}
var tipValue;
for (var i = 0; i < tip.length; i++) {
if (tip[i].type === "radio" && tip[i].checked) {
tipValue = tip[i].value;
}
}
document.getElementById('output').innerHTML = difValue;
document.getElementById('output2').innerHTML = tipValue;
};​
An updated jsFiddle is here.
Consider this post that adresses the issue. It shows a few javascript methods as well as how you would use it in jQuery.
How can I check whether a radio button is selected with JavaScript?
Is there a specific reason you want to break it down by fieldset instead of directly accessing the radio buttons by name?

Categories

Resources