I am using the script below to show and hide a div based on whether or not the checkbox is checked, this if so I can show/hide a paypal button until they accept the terms.
But we now want of offer three payment option so it will need to open/close 3 divs, I tried just copying the div 3 times but it still only opened one. Can any body help me with this please?
<script type="text/javascript">
function doInputs(obj){
var checkboxs = obj.form.c1;
var i =0, box;
document.getElementById('mydiv').style.display = 'none';
while(box = checkboxs[i++]){
if(!box.checked)continue;
document.getElementById('mydiv').style.display = '';
break;
}
}
</script>
<form>
<input type="checkbox" name="c1" onclick="doInputs(this)">
</form>
<div id="mydiv" style="display:none">
<input type="text">
</div>
Also it would be amazing if someone could help me add in another checkbox, and make the paypal buttons (divs) only show when BOTH are checked?
Thanks very much!
I also stole Marcus's answer but with the following improvements:
I use the jQuery document ready event so the code fires after the page loads
I simplified the logic
It works for multiple types of payment
http://jsfiddle.net/5Byes/3/
Using jQuery you can have an array or just two variables that are set to false. When a button is checked you set that equivalent value to the opposite of the current value (so if it was false, it would become true and vice-versa).
Here's a simple example of how you could accomplish this: http://jsfiddle.net/5Byes/
Only one element with particular ID is allowed on the page. If you want more — use class attribute.
On the other hand, you could wrap all divs with payments method in one div with ID, let's say, paymentsMethods and then show/hide it.
var paymentsDiv = document.getElementById('paymentsMethods');
if (box.checked) paymentsDiv.show(); else paymentsDiv.hide();
If you want 2 checkboxes — set onclick of both to same handler and change condition to box1.checked && box2.checked.
With jQuery (which is in your question tags) you could do $('#paymentsMethods').toogle() on checkbox click (see also $.hide() and $.show()).
If I understand correctly what you're looking for, you can do it like this:
HTML:
<input id="opt1cb" type="checkbox" value="Option 1" />Option 1<br />
<input id="opt2cb" type="checkbox" value="Option 2" />Option 2<br />
<input id="opt3cb" type="checkbox" value="Option 3" />Option 3<br />
<div class="option" id="opt1">Option 1</div>
<div class="option" id="opt2">Option 2</div>
<div class="option" id="opt3">Option 3</div>
<div class="option" id="opt23">Option 2 & 3</div>
jQuery:
$('.option').hide();
$('#opt1cb').click( function() {
if( $(this).prop("checked") ) {
$('#opt1').show();
} else {
$('#opt1').hide();
}
});
$('#opt2cb').click( function() {
if( $(this).prop("checked") ) {
$('#opt2').show();
if( $('#opt3cb').prop("checked") )
$('#opt23').show();
} else {
$('#opt2').hide();
$('#opt23').hide();
}
});
$('#opt3cb').click( function() {
if( $(this).prop("checked") ) {
$('#opt3').show();
if( $('#opt2cb').prop("checked") )
$('#opt23').show();
} else {
$('#opt3').hide();
$('#opt23').hide();
}
});
Working jsfiddle here: http://jsfiddle.net/bCDqa/
http://jsfiddle.net/5Byes/4/
I stole Marcus' fiddle and updated it to do what you want.
Related
I would like to conditionally disable a button based on a radio and checkbox combination. The radio will have two options, the first is checked by default. If the user selects the second option then I would like to disable a button until at least one checkbox has been checked.
I have searched at length on CodePen and Stack Overflow but cannot find a solution that works with my conditionals. The results I did find were close but I couldn't adapt them to my needs as I am a Javascript novice.
I am using JQuery, if that helps.
If needed:
http://codepen.io/traceofwind/pen/EVNxZj
<form>
<div id="input-option1">First option: (required)
<input type="radio" name="required" id="required" value="1" checked="checked">Yes
<input type="radio" name="required" id="required" value="2">No
<div>
<div id="input-option2">Optionals:
<input type="checkbox" name="optionals" id="optionals" value="2a">Optional 1
<input type="checkbox" name="optionals" id="optionals" value="2b">Optional 2
<div>
<div id="input-option3">Extras:
<input type="checkbox" name="extra" id="extra" value="3">Extra 1
<div>
<button type="button" id="btn">Add to Cart</button>
</form>
(Please excuse the code, it is in short hand for example!)
The form element IDs are somewhat fixed. The IDs are generated by OpenCart so I believe the naming convention is set by group, rather than unique. I cannot use IDs such as radio_ID_1 and radio_ID_2, for example; this is an OpenCart framework facet and not a personal choice.
Finally, in pseudo code I am hoping someone can suggest a JQuery / javascript solution along the lines of:
if radio = '2' then
if checkboxes = unchecked then
btn = disabled
else
btn = enabled
end if
end if
Here is a quick solution and I hope that's what you were after.
$(function() {
var $form = $("#form1");
var $btn = $form.find("#btn");
var $radios = $form.find(":radio");
var $checks = $form.find(":checkbox[name='optionals']");
$radios.add($checks).on("change", function() {
var radioVal = $radios.filter(":checked").val();
$btn.prop("disabled", true);
if (radioVal == 2) {
$btn.prop("disabled", !$checks.filter(":checked").length >= 1);
} else {
$btn.prop("disabled", !radioVal);
}
});
});
Here is a demo with the above + your HTML.
Note: Remove all the IDs except the form ID, button ID (since they're used in the demo) as you can't have duplicate IDs in an HTML document. an ID is meant to identify a unique piece of content. If the idea is to style those elements, then use classes.
If you foresee a lot of JavaScript development in your future, then I would highly recommend the JavaScript courses made available by Udacity. Although the full course content is only available for a fee, the most important part of the course materials--the videos and integrated questions--are free.
However, if you don't plan to do a lot of JavaScript development in the future and just need a quick solution so you can move on, here's how to accomplish what you are trying to accomplish:
$(document).ready(function(){
$('form').on('click', 'input[type="radio"]', function(){
conditionallyToggleButton();
});
$('form').on('click', 'input[type="checkbox"]', function(){
conditionallyToggleButton();
});
});
function conditionallyToggleButton()
{
if (shouldDisableButton())
{
disableButton();
}
else
{
enableButton();
}
}
function shouldDisableButton()
{
if ($('div#input-option1 input:checked').val() == 2
&& !$('form input[type="checkbox"]:checked').length)
{
return true;
}
return false;
}
function disableButton()
{
$('button').prop('disabled', true);
}
function enableButton()
{
$('button').prop('disabled', false);
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form>
<div id="input-option1">First option: (required)
<input type="radio" name="required" id="required" value="1" checked="checked">Yes
<input type="radio" name="required" id="required" value="2">No
<div>
<div id="input-option2">Optionals:
<input type="checkbox" name="optionals" id="optionals" value="2a">Optional 1
<input type="checkbox" name="optionals" id="optionals" value="2b">Optional 2
<div>
<div id="input-option3">Extras:
<input type="checkbox" name="extra" id="extra" value="3">Extra 1
<div>
<button type="button" id="btn">Add to Cart</button>
</form>
Note that the JavaScript code above is a quick-and-dirty solution. To do it right, you would probably want to create a JavaScript class representing the add to cart form that manages the behavior of the form elements and which caches the jQuery-wrapped form elements in properties.
I have a reason to use checkboxes instead of radio buttons so please don't suggest I use radio buttons but need to duplicate the functionality. However when I select the Yes checkbox, it disables the No checkbox for some reason. When no is selected I want to hide the div and deselect Yes, and the opposite when I select Yes I want to show the div and uncheck NO. The only way I can select NO when Yes is checked is to uncheck it.
Working demo Here
JS Fiddle not working Here
Javascript
function injure() {
if (document.getElementById("f2").checked == true) {
document.getElementById("LocFall").style.display="block";
document.getElementById("f1").checked = false;
} else {
if (document.getElementById("f1").checked == true) {
document.getElementById("LocFall").style.display="none";
document.getElementById("f2").checked = false;
}
}
}
CSS
#LocFall {
display:none;
}
HTML
<input type="checkbox" id="f1" name="" onclick="injure();">
<label for="f1"> No </label><BR>
<input type="checkbox" id="f2" name="" onclick="injure();">
<label for="f2"> Yes</label><BR>
<div id="LocFall">
Show some stuff
</div>
http://jsfiddle.net/6NN6s/14/
<input type="checkbox" id="f1" name="same" onclick="injure(this);" />
<label for="f1">No</label>
<BR>
<input type="checkbox" id="f2" name="same" onclick="injure(this);" />
<label for="f2">Yes</label>
<BR>
<div id="LocFall">Show some stuff</div>
function injure(cmb) {
if (cmb.checked) {
if(cmb.id==="f2")
{ document.getElementById("LocFall").style.display = "block";
document.getElementById("f1").checked = false;
}
else
{
document.getElementById("LocFall").style.display = "none";
document.getElementById("f2").checked = false;
}
}
}
try this out, may be what you need.
In Fiddle change on the left in second drop-down list 'onLoad' to 'no wrap - in <head>'.
Split injure into a different function for each; if you choose No, then you cannot choose Yes because of the way your function is set up - the first condition will always evaluate as true.
The problem stems from not knowing which checkbox was actually clicked inside the function. As it is there's only two different ways the function can respond: one if f1 is checked and one if f2 is checked. The problem is there's actually more possible states that you're trying to represent.
State 1: Nothing checked, user clicks f1 or f2
State 2: f1 checked, f2 clicked
State 3: f2 checked, f1 clicked
Your code handles the first state fine but it can't deal properly with the second ones. If you split your code into two seperate functions to handle each box then you'll have all the necessary information to write correct decision logic.
There's also the states of clicking the same box, but they are simple and your code handles them already.
I have tried several ways to achieve this, but somehow nothing works for this.
How can I copy the "label text" of respective Radio Button, which is selected by user into the input field (Result Box) in real time?
HTML -
<ul class="gfield_radio" id="input_4_4">
Radio Buttons:
<br />
<li class="gchoice_4_0">
<input name="input_4" type="radio" value="2" id="choice_4_0" class="radio_s" tabindex="4">
<label for="choice_4_0">Hi</label>
</li>
<li class="gchoice_4_1">
<input name="input_4" type="radio" value="4" id="choice_4_1" class="radio_s" tabindex="5">
<label for="choice_4_1">Hello</label>
</li>
<li class="gchoice_4_2">
<input name="input_4" type="radio" value="3" id="choice_4_2" class="radio_s" tabindex="6">
<label for="choice_4_2">Aloha</label>
</li>
</ul>
<br />
<div class="ginput_container">
Result Box:
<br />
<input name="input_3" id="input_4_3" type="text" value="" class="medium" tabindex="3">
</div>
My attempts:
$('input').change(function() {
if (this.checked) {
var response = $('label[for="' + this.id + '"]').html();
alert(response);
}
// also this:
// if ($("input[type='radio'].radio_s").is(':checked')) {
// var card_type = $("input[type='radio'].radio_s:checked").val();
// alert('card_type');
// }
});
You need to traverse the DOM from the radio which was clicked to find the nearest label element.
$('.radio_s').change(function() {
$('#input_4_3').val($(this).closest('li').find('label').text());
});
Example fiddle
You could also use $(this).next('label') however, that relies on the position of the label element not changing. My first example means the label can be anywhere within the same li as the radio button and it will work.
Try this:
$('.radio_s').click(function() {
$("#input_4_3").val($("input:checked" ).next().text());
});
Demo: http://jsfiddle.net/WQyEw/3/
This is a slightly tricky question to answer well. The structure of your HTML implies that there may be more than one of these structures on the page. So you may have more than one set of radio buttons with a corresponding checkbox.
I have put some working code into a jsFiddle.
I made one change: all the code you had in your question is now in <div class="container">. You would need as many of these as you had groups of radio buttons and checkboxes.
You can then have jQuery code like this:
$('ul.gfield_radio').on('change', 'input[type="radio"]', function () {
var label = $('label[for="' + this.id + '"]');
$(this).closest('.container').find('input.medium').val(label.text());
});
This code is not tied to the id values in this particular bit of HTML, but would work as many times as necessary throughout the page.
Why to depend on third party library when you can achieve it with plain javascript:
<script>
document.addEventListener('DOMContentLoaded', function () {
var a = document.getElementsByName('input_4');
for (var i = 0; i < a.length; i++) {
document.getElementsByName('input_4')[i].addEventListener('change', function () {
showValue(this);
}, false);
}
}, false);
function showValue(element) {
alert(element.parentNode.getElementsByTagName('label')[0].innerHTML)
}
</script>
I have seen other examples of this but have not successfully gotten this to function correctly. The examples I have seen also are just using regular checkboxes. I have used a class to stylize the checkbox with a sprite sheet so having a bit of trouble taking the ideas of these other examples and applying them to my case.
Here is the mark up:
<div id="showHideAll"">Show/Hide All<input type="checkbox" id="allCheck" name="pinSet" class="pinToggles" onclick="checkAllLinks()">
<label for="allCheck" class="css-label"></label></div>
</div>
<div>Opt1<input type="checkbox" id="opt1Check" name="pinSet" class="pinToggles" onclick="checkOpt1Links()">
<label for="opt1Check" class="css-label"></label>
</div>
<div>Opt2<input type="checkbox" id="opt2Check" name="pinSet" class="pinToggles" onclick="checkOpt2Links()">
<label for="opt2Check" class="css-label"></label>
</div>
<div>Opt3<input type="checkbox" id="opt3Check" name="pinSet" class="pinToggles" onclick="checkOpt3Links()">
<label for="dinShopCheck" class="css-label"></label>
</div>
The checked property is what changes the sprite using a css class.
input[type=checkbox].pinToggles:checked + label.css-label {
background-position: 0 -16px;
}
Most of this is for other functionality but thought I would show it just in case.
This is how I set up the individual checkboxes:
function checkOpt1Links(){
$('#opt1 li a').toggleClass("inactive");
if(opt1.getVisible() == true)
{
opt1.setOptions({visible:false});
}
else
{
opt1.setOptions({visible:true});
}
}
What I am looking for is the typical select all checkbox functionality, where if you check it the boxes all check, if you uncheck they all uncheck but also if you click a box when select all is checked the select all and the clicked checkbox uncheck and vice versa. I did look at this example: Jquery "select all" checkbox but just having difficult time making it work. Thanks for the help!
1) Use change event handler instead of click for checkbox and radio buttons.
You can make it simple like this
$('#showHideAll').on('change', 'input[type=checkbox]', function () {
if ($('.pinToggles').is(':checked')) {
$('.pinToggles').prop('checked', false)
}
else {
$('.pinToggles').prop('checked', true)
}
});
2) I have removed the class and onclick event handler in the below checkbox only.
HTML:
<div id="showHideAll">Show/Hide All<input type="checkbox" id="allCheck" name="pinSet" >
<label for="allCheck" class="css-label"></label></div>
</div>
Check this JSFiddle
I have made a check-box checkall/uncheckall.
HTML
<div> Using Check all function </div>
<div id="selectCheckBox">
<input type="checkbox" class="all" onchange="checkAll('selectCheckBox','all','check','true');" />Select All
<input type="checkbox" class="check" onchange="checkAll('selectCheckBox','all','check','false');" />Check Box 1
<input type="checkbox" class="check" onchange="checkAll('selectCheckBox','all','check','false');" />Check Box 2
<input type="checkbox" class="check" onchange="checkAll('selectCheckBox','all','check','false');" />Check Box 3
<input type="checkbox" class="check" onchange="checkAll('selectCheckBox','all','check','false');" />Check Box 4
</div>
main.js
function checkAll(parentId,allClass,checkboxClass,allChecked){
checkboxAll = $('#'+parentId+' .'+allClass);
otherCheckBox = $('#'+parentId+' .'+checkboxClass);
checkedCheckBox = otherCheckBox.filter($('input[type=checkbox]:checked'));
if(allChecked=='false'){
if(otherCheckBox.size()==checkedCheckBox.size()){
checkboxAll.attr('checked',true);
}else{
checkboxAll.attr('checked',false);
}
}else{
if(checkboxAll.attr('checked')){
otherCheckBox.attr('checked',true);
}else{
otherCheckBox.attr('checked',false);
}
}
}
It works fine. But get bulky when I have whole lot of checkboxes. I want to do same work by using jQuery rather than putting onchange on each checkbox. I tried different sort of things but couldnot work. I tried following one:
$('.check input[type="checkbox"]').change(function(e){
checkAll('selectCheckBox','all','check','true');
});
to do same work as onchange event but didnot work. Where do I went wrong.
I think you just need this: You do not need to pass all the arguments and have the inline onchange event attached to it. You can simplify your code.
$(function () {
$('input[type="checkbox"]').change(function (e) {
if(this.className == 'all')
{
$('.check').prop('checked', this.checked); //Toggle all checkboxes based on `.all` check box check status
}
else
{
$('.all').prop('checked', $('.check:checked').length == $('.check').length); // toggle all check box based on whether all others are checked or not.
}
});
});
Demo
Your selector is wrong:
.check input[type="checkbox"]
Above selects any input of type checkbox that has the ancestor with class .check. It'll match this:
<div class="check">
<input type="checkbox".../>
</div>
it should be:
input.check[type="checkbox"]
You closed the string here $('.check input[type='checkbox']') instead, you should use double quotes $('.check input[type="checkbox"]')