Liferay alloy button enable/disable - liferay-6

I am trying to get a simple button to be enabled/disabled when checkboxes are being selected, yet in Alloy UI within Liferay, it doesnt seem to work. Any suggestions?
<aui:form>
<aui:input checked="<%= true %>" cssClass="input-container" label="Decline" name="termsOfServiceRadio" type="radio" onClick='<%= renderResponse.getNamespace() + "disableCheckout();"%>'/>
<aui:input cssClass="input-container" label="Accept" name="termsOfServiceRadio" type="radio" onClick='<%= renderResponse.getNamespace() + "enableCheckout();"%>'/>
<aui:button-row>
<aui:button type="submit" name="submitButton" id="submitButtonID" disabled="true" />
</aui:button-row>
</aui:form>
<aui:script>
function <portlet:namespace />enableCheckout() {
document.<portlet:namespace />fm.<portlet:namespace />.getElementById("submitButtonID").disabled = false;
}
function <portlet:namespace />disableCheckout() {
document.<portlet:namespace />fm.<portlet:namespace />.getElementById("submitButtonID").disabled = true;
}
</aui:script>
To continue my trials with no success:
<aui:script>
function <portlet:namespace />enableCheckout() {
var mySubmittButton = A.one('#<portlet:namespace />submitButton');
mySubmittButton.set('disabled', false);
mySubmittButton.ancestor('.aui-button').removeClass('aui-button-disabled');
}
</aui:script>
<aui:script use="aui-base">
function <portlet:namespace />enableCheckout() {
var A = AUI();
var myBtn = A.one('.submitVisible-button');
myBtn.one(':button').attr('disabled', false);
myBtn.toggleClass('aui-button-disabled', false);
}
</aui:script>
<
<aui:button type="submit" name="submitButtonID" id="submitButtonID" cssClass="submitVisible-button" disabled="true" />
<aui:script use="aui-base">
Liferay.provide(
window,
'<portlet:namespace />enableCheckout',
function() {
var myButton = A.one('#<portlet:namespace />submitButtonID');
Liferay.Util.toggleDisabled(myButton, 'true');
myButton.set('disabled', false);
myButton.ancestor('.aui-button').removeClass('aui-button-disabled');
});
</aui:script>
<aui:script use="aui-base">
Liferay.provide(
window,
'<portlet:namespace />enableCheckout',
function() {
var A = AUI();
var myButton = A.one('#<portlet:namespace />submitButtonID');
Liferay.Util.toggleDisabled(myButton, true);
});
</aui:script>

So it appears you want to enable/disable submitButtonID based on termsOfServiceRadio.
You have several variations of essentially the same approach available. The basic concept is to assign click listeners to each radio button setting the state of the button based only on the "Accept" option being "checked". You can use either an id attribute to apply the listeners individually or some css class that will allow you to get both input elements at once and apply the listeners through the each method. A third option is to use the delegate function, which would require that you wrap the radio options in a "container".
YUI().use('aui-base', function(A){
var button = A.one('#mySubmitButton');
button.set('disabled', true);
var func = function(){button.set('disabled', !A.one('#AcceptRadioId').get('checked'));}
A.all('.tosRadioOption').each(function(node){
node.on('click', func)
})
})
Ultimately the set method using the disabled property on the submitButtonID node is the key components required to achieve the desired functionality. My fiddle contains the three approaches I mentioned. Considering you are using the aui taglib elements you'll need to prefix the ids with <portlet:namespace /> as you have done in some of your other attempts.

Ended up doing this a different way
<aui:form>
<aui:input checked="<%= true %>" cssClass="input-container" label="Decline" name="termsOfServiceRadio" type="radio" onClick="document.getElementById('test').style.visibility = this.checked ? 'hidden' : 'visible';"/>
<aui:input cssClass="input-container" label="Accept" name="termsOfServiceRadio" type="radio" onClick="document.getElementById('test').style.visibility = this.checked ? 'visible' : 'hidden';" />
<div id="test" style="visibility:hidden;">
<br/>
<strong>Choose a payment method:</strong>
<br/><br/>
<aui:input checked="<%= true %>" cssClass="input-container" label="Pay online with PayPal" name="paymentMethod" type="radio" onClick='<%= renderResponse.getNamespace() + "setPaypal();"%>'/>
<aui:input cssClass="input-container" label="Pay with check or wire transfer" name="paymentMethod" type="radio" onClick='<%= renderResponse.getNamespace() + "setOffline();"%>'/>
<aui:button-row>
<aui:button type="submit" name="submitButtonID" id="submitButtonID" cssClass="submitVisible-button" value='<%= shoppingPrefs.usePayPal() ? "continue" : "finished" %>' />
</aui:button-row>
</div>

Related

How to validate that at least one checkbox should be selected?

I want to do validation for checkboxes here without form tag. At least one checkbox should be selected.
<div *ngFor="let item of officeLIST">
<div *ngIf=" item.officeID == 1">
<input #off type="checkbox" id="off" name="off" value="1" [(ngModel)]="item.checked">
<label>{{item.officename}}</label>
</div>
<div *ngIf="item.officeID== 2">
<input #off type="checkbox" id="off" name="off" value="2" [(ngModel)]="item.checked">
<label>{{item.officename}}</label>
</div>
<div *ngIf="item.officeID== 3">
<input #off type="checkbox" id="off" name="off" value="3" [(ngModel)]="item.checked">
<label>{{item.officename}}</label>
</div>
</div>
for other field I will put required and do the error|touched|valid etc. but since checkbox is not single input, I cannot put required in every checkbox because all checkbox will be compulsory to checked. so how do I do the validation to alert user atleast one should be checked?
The accepted answer abuses stuff to use in a way they are not meant to be. With reactive forms the best, easiest and probably right way is to use a FormGroup that holds your grouped checkboxes and create a validator to check if at least one(or more) checkbox is checked within that group.
To do so just create another FormGroup inside your existing FormGroup and attach a validator to it:
form = new FormGroup({
// ...more form controls...
myCheckboxGroup: new FormGroup({
myCheckbox1: new FormControl(false),
myCheckbox2: new FormControl(false),
myCheckbox3: new FormControl(false),
}, requireCheckboxesToBeCheckedValidator()),
// ...more form controls...
});
And here is the validator. I made it so you can even use it to check if at least X checkboxes are checked, e.g. requireCheckboxesToBeCheckedValidator(2):
import { FormGroup, ValidatorFn } from '#angular/forms';
export function requireCheckboxesToBeCheckedValidator(minRequired = 1): ValidatorFn {
return function validate (formGroup: FormGroup) {
let checked = 0;
Object.keys(formGroup.controls).forEach(key => {
const control = formGroup.controls[key];
if (control.value === true) {
checked ++;
}
});
if (checked < minRequired) {
return {
requireCheckboxesToBeChecked: true,
};
}
return null;
};
}
In your template don't forget to add the directive 'formGroupName' to wrap your checkboxes. But don't worry, the compiler will remind you with an error-message if you forget. You can then check if the checkbox-group is valid the same way you do on FormControl's:
<ng-container [formGroup]="form">
<!-- ...more form controls... -->
<div class="form-group" formGroupName="myCheckboxGroup">
<div class="custom-control custom-checkbox">
<input type="checkbox" class="custom-control-input" formControlName="myCheckbox1" id="myCheckbox1">
<label class="custom-control-label" for="myCheckbox1">Check</label>
</div>
<div class="custom-control custom-checkbox">
<input type="checkbox" class="custom-control-input" formControlName="myCheckbox2" id="myCheckbox2">
<label class="custom-control-label" for="myCheckbox2">At least</label>
</div>
<div class="custom-control custom-checkbox">
<input type="checkbox" class="custom-control-input" formControlName="myCheckbox3" id="myCheckbox3">
<label class="custom-control-label" for="myCheckbox3">One</label>
</div>
<div class="invalid-feedback" *ngIf="form.controls['myCheckboxGroup'].errors && form.controls['myCheckboxGroup'].errors.requireCheckboxesToBeChecked">At least one checkbox is required to check</div>
</div>
<!-- ...more form controls... -->
</ng-container>
*This template is very static. Of course you could create it dynamically by using an additional array that holds the the form-data(key of FormControl, label, required, etc.) and create the template automatically by use of ngFor.
Please don't abuse hidden FormControl's like in the accepted answer. A FormControl is not meant to store data like id, label, help-text etc. and doesnt even have a name/key. All this, and much more, should be stored separate, e.g. by a regular array of objects. A FormControl only holds an input-value and provides all this cool state's and functions.
I created a working example you can play with: https://stackblitz.com/edit/angular-at-least-one-checkbox-checked
consider creating a FormGroup which contains your check-box group and bind the group's checked value to a hidden formcontrol with a required validator.
Assume that you have three check boxes
items = [
{key: 'item1', text: 'value1'}, // checkbox1 (label: value1)
{key: 'item2', text: 'value2'}, // checkbox2 (label: value2)
{key: 'item3', text: 'value3'}, // checkbox3 (label: value3)
];
Step1: define FormArray for your check boxes
let checkboxGroup = new FormArray(this.items.map(item => new FormGroup({
id: new FormControl(item.key), // id of checkbox(only use its value and won't show in html)
text: new FormControl(item.text), // text of checkbox(show its value as checkbox's label)
checkbox: new FormControl(false) // checkbox itself
})));
*easy to show via ngFor
Step2: create a hidden required formControl to keep status of checkbox group
let hiddenControl = new FormControl(this.mapItems(checkboxGroup.value), Validators.required);
// update checkbox group's value to hidden formcontrol
checkboxGroup.valueChanges.subscribe((v) => {
hiddenControl.setValue(this.mapItems(v));
});
we only care about hidden control's required validate status and won't show this hidden control in html.
Step3: create final form group contains below checkbox group and hidden formControl
this.form = new FormGroup({
items: checkboxGroup,
selectedItems: hiddenControl
});
Html Template:
<form [formGroup]="form">
<div [formArrayName]="'items'" [class.invalid]="!form.controls.selectedItems.valid">
<div *ngFor="let control of form.controls.items.controls; let i = index;" [formGroup]="control">
<input type="checkbox" formControlName="checkbox" id="{{ control.controls.id.value }}">
<label attr.for="{{ control.controls.id.value }}">{{ control.controls.text.value }}</label>
</div>
</div>
<div [class.invalid]="!form.controls.selectedItems.valid" *ngIf="!form.controls.selectedItems.valid">
checkbox group is required!
</div>
<hr>
<pre>{{form.controls.selectedItems.value | json}}</pre>
</form>
refer this demo.
I had the same problem and this is the solution I ended up using with Angular 6 FormGroup because I had few checkboxes.
HTML
Note: I'm using Angular Material for styling, change as needed.
<form [formGroup]="form">
<mat-checkbox formControlName="checkbox1">First Checkbox</mat-checkbox>
<mat-checkbox formControlName="checkbox2">Second Checkbox</mat-checkbox>
<mat-checkbox formControlName="checkbox3">Third Checkbox</mat-checkbox>
</form>
TypeScript
form: FormGroup;
constructor(private formBuilder: FormBuilder){}
ngOnInit(){
this.form = this.formBuilder.group({
checkbox1: [''],
checkbox2: [''],
checkbox3: [''],
});
this.form.setErrors({required: true});
this.form.valueChanges.subscribe((newValue) => {
if (newValue.checkbox1 === true || newValue.checkbox2 === true || newValue.checkbox3 === true) {
this.form.setErrors(null);
} else {
this.form.setErrors({required: true});
}
});
}
Basically, subscribe to any changes in the form and then modify the errors as needed according to the new form values.
On validation (i.e for example some click event) iterate over your array and check whether at least one item is true.
let isSelected: any = this.officeLIST.filter((item) => item.checked === true);
if(isSelected != null && isSelected.length > 0) {
//At least one is selected
}else {
alert("select at least one");
}
Add (ngModelChange)="onChange(officeLIST)" to your checkbox and have below code in your .ts file.
onChange(items) {
var found = items.find(function (x) { return x.checked === true; });
if (found)
this.isChecked = true;
else
this.isChecked = false;
}
Use isChecked variable any places you want.
I implemented a similar solution to the current accepted version proposed by Mick(using FormGroup and a custom Validator), but if you're like me and aren't going to need to handle showing an error for quantities checked > 0, you can simplify the Validator a lot:
export function checkboxGroupValidator(): ValidatorFn {
return (formGroup: FormGroup) => {
const checkedKeys = Object.keys(formGroup.controls).filter((key) => formGroup.controls[key].value);
if (checkedKeys.length === 0) { return { requireCheckboxesToBeChecked: true }; }
return null;
};
}
You should be checking the touched and dirty conditions of the form element
<form #myForm="ngForm" *ngIf="active" (ngSubmit)="onSubmit()">
<div class="form-group">
<label for="name">Name</label>
<input type="text" id="name" class="form-control"
required name="name" [(ngModel)]="myform.name"
#name="ngModel" >
<div *ngIf="name.errors && (name.dirty || name.touched)"
class="alert alert-danger">
<div [hidden]="!name.errors.required">
Name is required
</div>
</div>
</div>
</form>
You can combine the previous and my answer for both scenarios

Proper way of clearing forms without redux-form

This is my form
<form className="input-group" onSubmit={this.handleSubmit}>
<input className="form-control"
type="text"
placeholder="Insert name"
autofocus="true" />
<span className="input-group-btn">
<button type="submit" className={classNames}>Add</button>
</span>
</form>
This is my event handler:
handleSubmit(e) {
e.preventDefault();
let name = e.target[0].value;
if (name.length > 0) {
this.props.dispatch(createClassroom(name));
}
}
My question is:
what's the proper "redux way" to clearing the form after submitting it?
Do I need to dispatch a different action or should I use the existing createClassroom action?
Note: I'd rather not use redux-form package.
First, you have to make sure that the <input> is a controlled component by passing its respective value from the state:
const { classroom } = this.props;
// in return:
<input type="text" value={ classroom.name } />
Then, the form can be cleared by ideally submitting a RESET action that your classroom reducer acts upon:
const initialState = {};
function classroomReducer(state = initialState, action) {
switch (action.type) {
// ...
case 'RESET_CLASSROOM':
return initialState;
default:
return state;
}
}

Meteor - Data saving issue

I have this template:
<Template name="nuevoEjercicio">
<div class="container-fluid">
<div class="form-group">
<input type="text" class="form-control input-lg" name="ejercicio" placeholder="Ejercicio?"/>
<input type="number" class="form-control" name="repeticiones" placeholder="Repeticiones?" />
<input type="number" class="form-control" name="peso" placeholder="Peso?" />
<button type="submit" class="btn btn-success" >
<span class="glyphicon glyphicon-plus"></span>
</button>
</div>
</div>
</Template>
that I use to capture and save to the database.
Then on my .js file I am trying to get the data and save it:
Template.nuevoEjercicio.events({
'click .btn btn-success': function (event) {
var ejercicio = event.target.ejercicio.value;
var repeticiones = event.target.repeticiones.value;
var peso = event.target.peso.value;
ListaRutina.insert({
rutina:"1",
ejercicio:ejercicio,
repeticiones:repeticiones,
peso:peso,
});
// Clear form
event.target.ejercicio.value = "";
event.target.repeticiones.value = "";
event.target.peso.value = "";
// Prevent default form submit
return false;
}
});
}
as I understand, when I click on any object that has the btn btn-success style....but is not the case. For some obscure reason -for me- is not working.
Can you check it and give me some advice?
Thanks!
First of all, there's an error in you selector. It's 'click .btn.btn-success', not 'click .btn btn-success'.
Also you can't do that event.target.ejercicio.value thing. event.target is the element that was clicked. You'll have to do something like this:
'click .btn.btn-success': function (event, template) {
var ejercicio = template.$('[name=ejercicio]').val()
...
OK
What after wasting hours and hours the solution is:
1- on the html file give your input an id:
<input type="number" class="form-control" **id="peso"** placeholder="Peso?" />
<button type="submit" class="btn .btn-success" id="**guardar**" />
so now you want to save data on the input when the button is clicked:
2- You link the button with the funcion via the id
Template.TEMPLATENAMEONHTMLFILE.events({
'click **#guardar**': function (event, template) {
var ejercicio = template.$("**#peso**").val();
and get the value linking using the input id.

Required attribute on multiple checkboxes with the same name? [duplicate]

This question already has answers here:
Using the HTML5 "required" attribute for a group of checkboxes?
(16 answers)
Closed 6 years ago.
I have a list of checkboxes with the same name attribute, and I need to validate that at least one of them has been selected.
But when I use the html5 attribute "required" on all of them, the browser (chrome & ff) doesn't allow me to submit the form unless all of them are checked.
sample code:
<label for="a-0">a-0</label>
<input type="checkbox" name="q-8" id="a-0" required />
<label for="a-1">a-1</label>
<input type="checkbox" name="q-8" id="a-1" required />
<label for="a-2">a-2</label>
<input type="checkbox" name="q-8" id="a-2" required />
When using the same with radio inputs, the form works as expected (if one of the options is selected the form validates)
According to Joe Hopfgartner (who claims to quote the html5 specs), the supposed behaviour is:
For checkboxes, the required attribute shall only be satisfied when one or more of the checkboxes with that name in that form are checked.
For radio buttons, the required attribute shall only be satisfied when exactly one of the radio buttons in that radio group is checked.
am i doing something wrong, or is this a browser bug (on both chrome & ff) ??
You can make it with jQuery a less lines:
$(function(){
var requiredCheckboxes = $(':checkbox[required]');
requiredCheckboxes.change(function(){
if(requiredCheckboxes.is(':checked')) {
requiredCheckboxes.removeAttr('required');
}
else {
requiredCheckboxes.attr('required', 'required');
}
});
});
With $(':checkbox[required]') you select all checkboxes with the attribute required, then, with the .change method applied to this group of checkboxes, you can execute the function you want when any item of this group changes. In this case, if any of the checkboxes is checked, I remove the required attribute for all of the checkboxes that are part of the selected group.
I hope this helps.
Farewell.
Sorry, now I've read what you expected better, so I'm updating the answer.
Based on the HTML5 Specs from W3C, nothing is wrong. I created this JSFiddle test and it's behaving correctly based on the specs (for those browsers based on the specs, like Chrome 11 and Firefox 4):
<form>
<input type="checkbox" name="q" id="a-0" required autofocus>
<label for="a-0">a-1</label>
<br>
<input type="checkbox" name="q" id="a-1" required>
<label for="a-1">a-2</label>
<br>
<input type="checkbox" name="q" id="a-2" required>
<label for="a-2">a-3</label>
<br>
<input type="submit">
</form>
I agree that it isn't very usable (in fact many people have complained about it in the W3C's mailing lists).
But browsers are just following the standard's recommendations, which is correct. The standard is a little misleading, but we can't do anything about it in practice. You can always use JavaScript for form validation, though, like some great jQuery validation plugin.
Another approach would be choosing a polyfill that can make (almost) all browsers interpret form validation rightly.
To provide another approach similar to the answer by #IvanCollantes.
It works by additionally filtering the required checkboxes by name. I also simplified the code a bit and checks for a default checked checkbox.
jQuery(function($) {
var requiredCheckboxes = $(':checkbox[required]');
requiredCheckboxes.on('change', function(e) {
var checkboxGroup = requiredCheckboxes.filter('[name="' + $(this).attr('name') + '"]');
var isChecked = checkboxGroup.is(':checked');
checkboxGroup.prop('required', !isChecked);
});
requiredCheckboxes.trigger('change');
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<form target="_blank">
<p>
At least one checkbox from each group is required...
</p>
<fieldset>
<legend>Checkboxes Group test</legend>
<label>
<input type="checkbox" name="test[]" value="1" checked="checked" required="required">test-1
</label>
<label>
<input type="checkbox" name="test[]" value="2" required="required">test-2
</label>
<label>
<input type="checkbox" name="test[]" value="3" required="required">test-3
</label>
</fieldset>
<br>
<fieldset>
<legend>Checkboxes Group test2</legend>
<label>
<input type="checkbox" name="test2[]" value="1" required="required">test2-1
</label>
<label>
<input type="checkbox" name="test2[]" value="2" required="required">test2-2
</label>
<label>
<input type="checkbox" name="test2[]" value="3" required="required">test2-3
</label>
</fieldset>
<hr>
<button type="submit" value="submit">Submit</button>
</form>
i had the same problem, my solution was apply the required attribute to all elements
<input type="checkbox" name="checkin_days[]" required="required" value="0" /><span class="w">S</span>
<input type="checkbox" name="checkin_days[]" required="required" value="1" /><span class="w">M</span>
<input type="checkbox" name="checkin_days[]" required="required" value="2" /><span class="w">T</span>
<input type="checkbox" name="checkin_days[]" required="required" value="3" /><span class="w">W</span>
<input type="checkbox" name="checkin_days[]" required="required" value="4" /><span class="w">T</span>
<input type="checkbox" name="checkin_days[]" required="required" value="5" /><span class="w">F</span>
<input type="checkbox" name="checkin_days[]" required="required" value="6" /><span class="w">S</span>
when the user check one of the elements i remove the required attribute from all elements:
var $checkedCheckboxes = $('#recurrent_checkin :checkbox[name="checkin_days[]"]:checked'),
$checkboxes = $('#recurrent_checkin :checkbox[name="checkin_days[]"]');
$checkboxes.click(function() {
if($checkedCheckboxes.length) {
$checkboxes.removeAttr('required');
} else {
$checkboxes.attr('required', 'required');
}
});
Here is improvement for icova's answer. It also groups inputs by name.
$(function(){
var allRequiredCheckboxes = $(':checkbox[required]');
var checkboxNames = [];
for (var i = 0; i < allRequiredCheckboxes.length; ++i){
var name = allRequiredCheckboxes[i].name;
checkboxNames.push(name);
}
checkboxNames = checkboxNames.reduce(function(p, c) {
if (p.indexOf(c) < 0) p.push(c);
return p;
}, []);
for (var i in checkboxNames){
!function(){
var name = checkboxNames[i];
var checkboxes = $('input[name="' + name + '"]');
checkboxes.change(function(){
if(checkboxes.is(':checked')) {
checkboxes.removeAttr('required');
} else {
checkboxes.attr('required', 'required');
}
});
}();
}
});
A little jQuery fix:
$(function(){
var chbxs = $(':checkbox[required]');
var namedChbxs = {};
chbxs.each(function(){
var name = $(this).attr('name');
namedChbxs[name] = (namedChbxs[name] || $()).add(this);
});
chbxs.change(function(){
var name = $(this).attr('name');
var cbx = namedChbxs[name];
if(cbx.filter(':checked').length>0){
cbx.removeAttr('required');
}else{
cbx.attr('required','required');
}
});
});
Building on icova's answer, here's the code so you can use a custom HTML5 validation message:
$(function() {
var requiredCheckboxes = $(':checkbox[required]');
requiredCheckboxes.change(function() {
if (requiredCheckboxes.is(':checked')) {requiredCheckboxes.removeAttr('required');}
else {requiredCheckboxes.attr('required', 'required');}
});
$("input").each(function() {
$(this).on('invalid', function(e) {
e.target.setCustomValidity('');
if (!e.target.validity.valid) {
e.target.setCustomValidity('Please, select at least one of these options');
}
}).on('input, click', function(e) {e.target.setCustomValidity('');});
});
});
var verifyPaymentType = function () {
//coloque os checkbox dentro de uma div com a class checkbox
var inputs = window.jQuery('.checkbox').find('input');
var first = inputs.first()[0];
inputs.on('change', function () {
this.setCustomValidity('');
});
first.setCustomValidity( window.jQuery('.checkbox').find('input:checked').length === 0 ? 'Choose one' : '');
}
window.jQuery('#submit').click(verifyPaymentType);
}

jQuery toggle passed boolean false first has different transition

Here is a working example: http://jsfiddle.net/FzZwt/8/
If I pass false to the toggle() first the transition is set to slow
If I pass true to the toggle() first the transition is not set
Can I pass a transition with a boolean in the toggle()?
Example:
var show = true;
$('#elem').toggle(show, 'slow');
HTML
<div data-role="page">
<div data-role="fieldcontain">
<fieldset data-role="controlgroup" data-type="horizontal">
<div>Boolean Test 1 - Passing TRUE first</div>
<input type="radio" name="boolean" id="true" value="true" />
<label for="true">Yes</label>
<input type="radio" name="boolean" id="false" value="false" checked="checked"/>
<label for="false">No</label>
<div class="hidden" name="hidden_div" id="hidden_div">Show Me!!!</div>
</fieldset>
</div>
<div data-role="fieldcontain">
<fieldset data-role="controlgroup" data-type="horizontal">
<div>Boolean Test 2 - Passing FALSE First</div>
<input type="radio" name="boolean2" id="true" value="true" />
<label for="true">Yes</label>
<input type="radio" name="boolean2" id="false" value="false" checked="checked"/>
<label for="false">No</label>
<div class="hidden" name="hidden_div2" id="hidden_div2">Show Me!!!</div>
</fieldset>
</div>
</div>
JS
$(".hidden").hide();
$("[name=boolean]").change(function() {
var show = $('input[name=boolean]:checked').val() == "true";
alert('Passing first: '+show);
$("#hidden_div").toggle(show);
});
$("[name=boolean2]").change(function() {
var show = $(this).val();
alert('Passing First: '+show);
$("#hidden_div2").toggle(show);
});
You're passing string values when it expects either a boolean or an animation speed (either a number or one of the values that translates to numbers).
If you want to pass booleans, you'll need to cast them as Tomalak mentions
I made a couple of changes; is this what you're looking for?
$(".hidden").hide();
$("[name=boolean]").change(function() {
var show = ($('input[name=boolean]:checked').val() == 'true') ? true : false;
$("#hidden_div").toggle(show );
});
$("[name=boolean2]").change(function() {
var show = ($(this).val() == "true") ? true : false ;
$("#hidden_div2").toggle(show );
});
http://jsfiddle.net/FzZwt/11/
According to the API, the form of toggle() where a boolean determines whether to show or hide doesn't take any other parameters. So unfortunately, I think we have to do something like:
if (myBoolean) {
$myElement.show(MY_DURATION_CONSTANT, myEasing);
} else {
$myElement.hide(MY_DURATION_CONSTANT, myEasing);
}
Not very elegant, but I think this is necessary because of the way the toggle function is overloaded.