Condition: input:checked with the same class - javascript

I would like to have a little help on an enigma that I have.
I have a button that changes according to the number of input:checked
but I would like to add a condition which is: select of the checkboxes of the same class.
for example can I have 2 or more input.
<input class="banana" type="checkbox" value="Cavendish">
<input class="banana" type="checkbox" value="Goldfinger">
<input class="chocolato" type="checkbox" value="cocoa powder">
<input class="chocolato" type="checkbox" value="milk chocolate">
<input class="apple" type="checkbox" value="honneycrisp">
<input class="apple" type="checkbox" value="granny smith">
I can't use attribute name or value. it is not possible to modify the inputs.
the condition:
$('input[type="checkbox"]').click(function(){
if($('input[type="checkbox"]:checked').length >=2){
////////
if (my classes are the same) {
$('#btn').html("click me").prop('disabled', false);
} else {
$('#btn').html("too bad").prop('disabled', true);
}
//////
}
I try with
var checkClass = [];
$.each($("input[type="checkbox"]:checked"), function() {
checkClass.push($(this).attr('class'));
});
I don't know if I'm going the right way or if I'm complicating the code but a little help would be welcome. For the moment my attempts have been unsuccessful.

The following function will reference the first checkbox that's checked className and enable each checkbox that has said className whilst disabling all other checkboxes. Details are commented in Snippet.
// All checkboxes
const all = $(':checkbox');
// Any change event on any checkbox run function `matchCategory`
all.on('change', matchCategory);
function matchCategory() {
// All checked checkboxes
const checked = $(':checkbox:checked');
let category;
// if there is at least one checkbox checked...
if (checked.length > 0) {
// ...enable (.btn)...
$('.btn').removeClass('off');
// ...get the class of the first checked checkbox...
category = checked[0].className;
// ...disable ALL checkboxes...
all.attr('disabled', true);
// ...go through each checkbox...
all.each(function() {
// if THIS checkbox has the class defined as (category)...
if ($(this).is('.' + category)) {
// ...enable it
$(this).attr('disabled', false);
// Otherwise...
} else {
// ...disable and uncheck it
$(this).attr('disabled', true).prop('checked', false);
}
});
// Otherwise...
} else {
// ...enable ALL checkboxes...
all.attr('disabled', false);
// ...disable (.btn)
$('.btn').addClass('off');
}
return false;
}
.off {
pointer-events: none;
opacity: 0.4;
}
<input class="beverage" type="checkbox" value="Alcohol">
<label>🍸</label><br>
<input class="beverage" type="checkbox" value="Coffee">
<label>☕</label><br>
<input class="dessert" type="checkbox" value="cake">
<label>🍰</label><br>
<input class="dessert" type="checkbox" value="Ice Cream">
<label>🍨</label><br>
<input class="appetizer" type="checkbox" value="Salad">
<label>🥗</label><br>
<input class="appetizer" type="checkbox" value="Bread">
<label>🥖</label><br>
<button class='btn off' type='button '>Order</button>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

some thing like that ?
const
bt_restart = document.getElementById('bt-restart')
, chkbx_all = document.querySelectorAll('input[type=checkbox]')
;
var checked_class = ''
;
bt_restart.onclick = _ =>
{
checked_class = ''
chkbx_all.forEach(cbx=>
{
cbx.checked=cbx.disabled=false
cbx.closest('label').style = ''
})
}
chkbx_all.forEach(cbx=>
{
cbx.onclick = e =>
{
if (checked_class === '') checked_class = cbx.className
else if (checked_class != cbx.className )
{
cbx.checked = false
cbx.disabled = true
cbx.closest('label').style = 'color: grey'
}
}
})
<button id="bt-restart">restart</button> <br> <br>
<label> <input class="banana" type="checkbox" value="Cavendish" > a-Cavendish </label> <br>
<label> <input class="banana" type="checkbox" value="Goldfinger" > a-Goldfinger </label> <br>
<label> <input class="chocolato" type="checkbox" value="cocoa powder" > b-cocoa powder </label> <br>
<label> <input class="chocolato" type="checkbox" value="milk chocolate"> b-milk chocolate </label> <br>
<label> <input class="apple" type="checkbox" value="honneycrisp" > c-honneycrisp </label> <br>
<label> <input class="apple" type="checkbox" value="granny smith" > c-granny smith </label> <br>

In fact it's like a Matching Pairs card game
this answer is without global checked_group variable, and respecting epascarello message about data attribute see also usage.
Adding a repentance on uncheck elements
const
bt_restart = document.getElementById('bt-restart')
, chkbx_all = document.querySelectorAll('input[type=checkbox]')
;
function clearGame()
{
chkbx_all.forEach(cbx=>
{
cbx.checked = cbx.disabled = false
cbx.closest('label').style = ''
})
}
bt_restart.onclick = clearGame
chkbx_all.forEach(cbx=>
{
cbx.onclick = e =>
{
let checkedList = document.querySelectorAll('input[type=checkbox]:checked')
if (cbx.checked)
{
let checked_group = ''
checkedList.forEach(cEl=>{ if (cEl !== cbx) checked_group = cEl.dataset.group })
if (checked_group === '') checked_group = cbx.dataset.group
else if (checked_group !== cbx.dataset.group )
{
cbx.checked = false // you need to uncheck wrong group checkboxes for preserving checkedList
cbx.disabled = true
cbx.closest('label').style = 'color: grey'
}
}
else if (checkedList.length === 0) // case of cheked repentir
clearGame()
}
})
<button id="bt-restart">restart</button> <br> <br>
<label> <input data-group="banana" type="checkbox" value="Cavendish" > a-Cavendish </label> <br>
<label> <input data-group="banana" type="checkbox" value="Goldfinger" > a-Goldfinger </label> <br>
<label> <input data-group="chocolato" type="checkbox" value="cocoa powder" > b-cocoa powder </label> <br>
<label> <input data-group="chocolato" type="checkbox" value="milk chocolate"> b-milk chocolate </label> <br>
<label> <input data-group="apple" type="checkbox" value="honneycrisp" > c-honneycrisp </label> <br>
<label> <input data-group="apple" type="checkbox" value="granny smith" > c-granny smith </label> <br>

Related

Select all checkboxes in Angular/ JavaScript

I want to Select all checkboxes in Angular/JavaScript, I tried a few ways that didn't work.
the check code that is to select all is this one:
<div class="form-groupCheckbox">
<input class="checkbox" name="confirm" id="confirm1" type="checkbox">
<label for="confirm1"> Selecionar todos </label>
</div>
I want to check all these boxes here when I click on the "select all" box
<input class="checkbox" name="confirm" id="confirm1" type="checkbox">
<label for="confirm1"> xx </label>
<input class="checkbox" name="confirm" id="confirm2" type="checkbox">
<label for="confirm1"> ff </label>
<input class="checkbox" name="confirm" id="confirm3" type="checkbox">
<label for="confirm1">rr </label>
Here is the way for javascript. Change main checkbox html as following.
<div class="form-groupCheckbox">
<input class="checkbox" name="confirmmain" onclick="selects()" id="confirmall" type="checkbox">
<label for="confirm1"> Selecionar todos </label>
</div>
Now add new script that makes checkbox check and uncheck
<script>
function selects(){
var ele=document.getElementById('confirmall');
if(ele.checked == true) {
var ele=document.getElementsByName('confirm');
for(var i=0; i<ele.length; i++){
if(ele[i].type=='checkbox')
ele[i].checked=true;
}
} else {
var ele=document.getElementsByName('confirm');
for(var i=0; i<ele.length; i++){
if(ele[i].type=='checkbox')
ele[i].checked=false;
}
}
}
</script>
What you can do is to link each of the checkboxes to some variable and then just make them all true when user select select-all checkbox.
HTML file will look like this:
<div class="form-groupCheckbox">
<input class="checkbox" name="confirm" id="confirm1" type="checkbox" #selectAll (change)="onSelectAllChange(selectAll.value)">
<label for="confirm1"> Selecionar todos </label>
</div>
<ng-container *ngFor="let checkbox of checkboxes">
<input class="checkbox" name="confirm" [(ngModel)]="checkbox.value" id="{{checkbox.id}}" type="checkbox">
<label for="confirm1"> {{checkbox.label}} </label>
</ng-container>
TypeScript file will look like this:
public checkboxes = [
{
value: false,
id: 'checkbox_1',
lablel: 'Label 1'
},
{
value: false,
id: 'checkbox_2',
lablel: 'Label 2'
},
{
value: false,
id: 'checkbox_3',
lablel: 'Label 3'
}
];
onSelectAllChange(value: boolean) {
checkboxes.forEach((checkbox: any) => {
if (value) {
checkbox.value = true;
} else {
checkbox.value = false;
}
});
}

Display different divs using input checkbox

I want to use 3 input checkbox to display 3 different div. I am using this code but the only one working is "Course 1" and I can't figure out why. I guess it is something pretty easy, but I can't see it:
document.getElementById('checkbox1');
checkbox1.onchange = function() {
if (checkbox1.checked) {
course1.style.display = 'block';
} else {
course1.style.display = 'none';
}
};
document.getElementById('checkbox2');
checkbox2.onchange = function() {
if (checkbox2.checked) {
course2.style.display = 'block';
} else {
course2.style.display = 'none';
}
};
document.getElementById('checkbox3');
checkbox3.onchange = function() {
if (checkbox3.checked) {
course3.style.display = 'block';
} else {
course3.style.display = 'none';
}
};
<form>
<label class="switch">
<input type="checkbox" id="checkbox1" checked="true"> Course 1
</label>
</form>
<form>
<label class="switch">
<input type="checkbox" id="checkbox2" checked="true"> Course 2
</label>
</form>
<form>
<label class="switch">
<input type="checkbox" id="checkbox3" checked="true"> Course 3
</label>
</form>
<br>
<div id="course1"> Text course 1
</div>
<br>
<div id="course2"> Text course 2
</div>
<br>
<div id="course2"> Text course 3
</div>
Example: https://codepen.io/antonioagar1/pen/dqGaoO
You can try this simple code instead of your own code:
document.addEventListener("change", function(ev){
if(ev.target.id.substr(0,8)=="checkbox") document.querySelector("[id='course"+ev.target.getAttribute("id").slice(-1)+"']").style.display=ev.target.checked?"block":"none";
});
you have two div with id course2. first, change it to course3 and then try.
Check result online

Allow only one checked checkbox, Angular best practice.

Im using angular.
I have Three checkboxes in a Group and i want to make sure only one of them can be checked. So if one is checked the other two has to bee unchacked. I can Think of doing this several ways with native JS or jQuery but i want to know if there is a typical Angular way of doing it.
Here is Plunker with a set up of the checkboxes and angular controll.
http://plnkr.co/edit/IZmGwktrCaYNyrWjfSqf?p=preview
<body ng-controller="MainCtrl">
<div>
{{vm.Output}}
<br>
<br>
<br>
<label>
<input type="checkbox" name="groupA" ng-model="vm.a1" ng-change="vm.changeGroupA()"> A1 </label>
<label>
<input type="checkbox" name="groupA" ng-model="vm.a2" ng-change="vm.changeGroupA()"> A2 </label>
<label>
<input type="checkbox" name="groupA" ng-model="vm.a3" ng-change="vm.changeGroupA()"> A3 </label>
<br>
<br>
<br> {{vm.Output}}
</body>
Since you can't use radio buttons, I've made this plnkr when you check one the others are deselected:
http://plnkr.co/edit/apSE3cIXA7DIvulBfNGX?p=preview
<label> <input type="checkbox" name="groupA" ng-model="vm.a1" ng-change="vm.a2 = false; vm.a3 = false; vm.changeGroupA()" > A1 </label>
<label> <input type="checkbox" name="groupA" ng-model="vm.a2" ng-change="vm.a1 = false; vm.a3 = false; vm.changeGroupA()" > A2 </label>
<label> <input type="checkbox" name="groupA" ng-model="vm.a3" ng-change="vm.a2 = false; vm.a1 = false; vm.changeGroupA()" > A3 </label>
Hope it helps =)
Edit: You can probably change the state of the other checkboxes in the controller for best practice, made in the html just to demonstrate more quickly..
Another way to do it would be: http://plnkr.co/edit/kH12pYkXfY6t6enrlSns
<br><br><br>
<label> <input type="checkbox" name="groupA" ng-model="vm.groupA[0]" ng-change="vm.changeGroupA(0)" > A1 </label>
<label> <input type="checkbox" name="groupA" ng-model="vm.groupA[1]" ng-change="vm.changeGroupA(1)" > A2 </label>
<label> <input type="checkbox" name="groupA" ng-model="vm.groupA[2]" ng-change="vm.changeGroupA(2)" > A3 </label>
<br><br><br>
The controller would look like this:
$scope.vm = {
groupA: [false, true, false],
count : 0,
changeGroupA : function (index)
{
for (i = 0, len = this.groupA.length; i < len; ++i) {
this.groupA[i] = ((1 << index) & (1 << i)) > 0;
}
this.Output = '(' + this.count + ')' + this.Output;
this.count ++;
},
Output : 'Here we go'
}
You might want to do it the hard way out. http://plnkr.co/edit/A53w4IJMRXQmvRsxa8JA and it should work
changeGroupA : function (x)
{
if (x === 'A1'){
$scope.vm.a1 = true;
$scope.vm.a2 = false;
$scope.vm.a3 = false;
}
else if (x === 'A2') {
$scope.vm.a2 = true;
$scope.vm.a1 = false;
$scope.vm.a3 = false;
}
else if (x === 'A3') {
$scope.vm.a3 = true;
$scope.vm.a1 = false;
$scope.vm.a2 = false;
}
this.Output = '(' + this.count + ')' + this.Output;
this.count ++;
},
This works perfectly fine for angular 6 or 8
HTML:
<div class="custom-control custom-checkbox custom-control-inline">
<input type="checkbox" class="custom-control-input" id="check1id"
[(ngModel)]="check1" (change)="onlyOneValue($event)"/>
<label for="check1id" class="custom-control-label">Checkbox 1</label>
</div>
<div class="custom-control custom-checkbox custom-control-inline">
<input type="checkbox" class="custom-control-input" id="check2id"
[(ngModel)]="check2" (change)="onlyOneValue($event)" />
<label for="check2id" class="custom-control-label"> Checkbox 2 </label>
</div>
.ts code:
check1=false;
check2=false;
onlyOneValue(e)
{
if (e.target.id == "Check1id") {
this.Check1= true;
this.Check2 = false;
}
else if (e.target.id == "Check1id") {
this.Check1= true;
this.Check2 = false;
}
}
Why don't you just use a radio button?
<label>
<input type="radio" name="groupA" ng-model="vm.a1" ng-change="vm.changeGroupA()"> A1 </label>
<label>
<input type="radio" name="groupA" ng-model="vm.a2" ng-change="vm.changeGroupA()"> A2 </label>
<label>
<input type="radio" name="groupA" ng-model="vm.a3" ng-change="vm.changeGroupA()"> A3 </label>

Check All checkbox should be unchecked

function toggle(source) {
checkboxes = document.getElementsByName('options[]');
for (var i = 0, n = checkboxes.length; i < n; i++) {
checkboxes[i].checked = source.checked;
}
}
<form class="unsubscribe_form" action="process.php" method="post">
<input type="checkbox" class="unsubscribe-checkbox" name="options[]" id="checkbox-1-1" value="Option1">
<label for="checkbox-1-1"></label>Option 1
<input type="checkbox" class="unsubscribe-checkbox" name="options[]" id="checkbox-1-2" value="Option2">
<label for="checkbox-1-2"></label>Option 2
<input type="checkbox" class="unsubscribe-checkbox" name="options[]" id="checkbox-1-3" value="Option2">
<label for="checkbox-1-3"></label>Option 3
<input type="checkbox" class="unsubscribe-checkbox" name="options[]" id="checkbox-1-4" value="Option3">
<label for="checkbox-1-4"></label>Option 4
<input type="checkbox" class="unsubscribe-checkbox" name="options[]" id="checkbox-1-5" value="Option3">
<label for="checkbox-1-5"></label>Option 5
<input type="checkbox" class="unsubscribe-checkbox" id="checkbox-1-6" value="All" onClick="toggle(this)" />
<label for="checkbox-1-6"></label>All
<br>
<input type="submit" name="formSubmit" value="Unsubscribe" />
</form>
When I check the All checkbox, of course, it will mark all the checkboxes, but once I uncheck one checkbox, the All checkbox is still checked. This should be unchecked. How should I do that using JS?
You will need to add onchange event handlers to every checkbox and check inside if the "All" checkbox should be checked (all checkboxes are selected) or unchecked (at least one is deselected). For example like this:
var checkboxes = [].slice.call(document.getElementsByName('options[]')),
allCheckbox = document.querySelector('input[value="All"]');
checkboxes.forEach(function(checkbox) {
checkbox.onchange = function() {
if (!this.checked) {
allCheckbox.checked = false;
}
else {
var checked = checkboxes.filter(function(check) {
return check.checked;
});
if (checked.length === checkboxes.length) {
allCheckbox.checked = true;
}
}
};
});
function toggle(source) {
for (var i = 0, n = checkboxes.length; i < n; i++) {
checkboxes[i].checked = source.checked;
}
}
<form class="unsubscribe_form" action="process.php" method="post">
<input type="checkbox" class="unsubscribe-checkbox" name="options[]" id="checkbox-1-1" value="Option1">
<label for="checkbox-1-1"></label>Option 1
<input type="checkbox" class="unsubscribe-checkbox" name="options[]" id="checkbox-1-2" value="Option2">
<label for="checkbox-1-2"></label>Option 2
<input type="checkbox" class="unsubscribe-checkbox" name="options[]" id="checkbox-1-3" value="Option2">
<label for="checkbox-1-3"></label>Option 3
<input type="checkbox" class="unsubscribe-checkbox" name="options[]" id="checkbox-1-4" value="Option3">
<label for="checkbox-1-4"></label>Option 4
<input type="checkbox" class="unsubscribe-checkbox" name="options[]" id="checkbox-1-5" value="Option3">
<label for="checkbox-1-5"></label>Option 5
<input type="checkbox" class="unsubscribe-checkbox" id="checkbox-1-6" value="All" onClick="toggle(this)" />
<label for="checkbox-1-6"></label>All
</form>
Note that I converted checkboxes collection to array with [].slice.call in order to use convenient array methods. Simple for loops can be used instead.
I'd suggest the following:
function toggle() {
// getting a reference to all the 'name="option[]" elements:
var options = document.getElementsByName('options[]'),
// a reference to the 'all' checkbox:
all = document.getElementById('checkbox-1-6');
// if the changed checkbox is the 'all':
if (this === all) {
// we iterate over all the options checkboxes (using
// Array.prototype.forEach()):
Array.prototype.forEach.call(options, function(checkbox) {
// and we set their checked property to the checked property
// state of the 'all' checkbox:
checkbox.checked = all.checked;
});
} else {
// otherwise we set the 'all' checkbox to the state of
// the Boolean returned by Array.prototype.every(),
// which returns true if all checkboxes evaluate to
// the condition within the function, otherwise false:
all.checked = Array.prototype.every.call(options, function(checkbox) {
return checkbox.checked;
});
}
}
// getting a NodeList of all the elements of 'class="unsubscribe-checkbox"':
var options = document.querySelectorAll('.unsubscribe-checkbox');
// iterating over them, again with Array.prototype.forEach()
// and assigning a change event-listener, which will execute the
// name function:
Array.prototype.forEach.call(options, function(opt) {
opt.addEventListener('change', toggle);
});
function toggle() {
var options = document.getElementsByName('options[]'),
all = document.getElementById('checkbox-1-6');
if (this === all) {
Array.prototype.forEach.call(options, function(checkbox) {
checkbox.checked = all.checked;
});
} else {
all.checked = Array.prototype.every.call(options, function(checkbox) {
return checkbox.checked;
});
}
}
var options = document.querySelectorAll('.unsubscribe-checkbox');
Array.prototype.forEach.call(options, function(opt) {
opt.addEventListener('change', toggle);
});
<form class="unsubscribe_form" action="process.php" method="post">
<input type="checkbox" class="unsubscribe-checkbox" name="options[]" id="checkbox-1-1" value="Option1">
<label for="checkbox-1-1"></label>Option 1
<input type="checkbox" class="unsubscribe-checkbox" name="options[]" id="checkbox-1-2" value="Option2">
<label for="checkbox-1-2"></label>Option 2
<input type="checkbox" class="unsubscribe-checkbox" name="options[]" id="checkbox-1-3" value="Option2">
<label for="checkbox-1-3"></label>Option 3
<input type="checkbox" class="unsubscribe-checkbox" name="options[]" id="checkbox-1-4" value="Option3">
<label for="checkbox-1-4"></label>Option 4
<input type="checkbox" class="unsubscribe-checkbox" name="options[]" id="checkbox-1-5" value="Option3">
<label for="checkbox-1-5"></label>Option 5
<input type="checkbox" class="unsubscribe-checkbox" id="checkbox-1-6" value="All" />
<label for="checkbox-1-6"></label>All
<br>
<input type="submit" name="formSubmit" value="Unsubscribe" />
</form>
You may notice that I've removed the onClick attribute from the 'all' checkbox, in preference of unobtrusive JavaScript, where the event-handlers are assigned via the JavaScript itself (which ordinarily makes for more easily-maintained code, as the arguments to be passed to a given function are assigned in the code itself, rather than having to be separately updated in the HTML).
References:
Array.prototype.every().
Array.prototype.forEach().
document.getElementsByName().
document.getElementById().
document.querySelectorAll().
EventTarget.addEventListener().
Function.prototype.call().

Automatically populate input field with data on clicking radio buttons

When the user selects a radio button in the 2 categories Plan details and Plan Duration the input field should populate with the relevant data through JavaScript.
Please check the html markup and JavaScript below and suggest corrections or an alternate method that would work.
<h3 class="fltClear">Plan Details</h3>
<div id="spryradio1">
<dt>Plan Type: <span class="required">*</span></dt>
<dd>
<label>
<input type="radio" name="RadioGroup1" value="Silver" id="RadioGroup1_0" onClick="changeplanprice();" class="RadioGroup1" />
Silver</label>
<br>
<label>
<input type="radio" name="RadioGroup1" value="Gold" id="RadioGroup1_1" onClick="changeplanprice();" class="RadioGroup1" />
Gold</label>
<br>
<label>
<input type="radio" name="RadioGroup1" value="Platinum" id="RadioGroup1_2" onClick="changeplanprice();" class="RadioGroup1" />
Platinum</label>
<br>
<label>
<input type="radio" name="RadioGroup1" value="All-in-one" id="RadioGroup1_3" onClick="changeplanprice();" class="RadioGroup1" />
All-in-one</label>
<br>
<span class="radioRequiredMsg">Please make a selection.<span class="hint-pointer"> </span></span>
</dd>
</div>
<!--Plan Duration-->
<div id="spryradio2">
<dt>Plan Duration: <span class="required">*</span></dt>
<dd>
<label>
<input type="radio" name="RadioGroup2" value="Yearly" id="RadioGroup2_0" onClick="changeplanprice();" class="RadioGroup2" />
Yearly</label>
<br>
<label>
<input type="radio" name="RadioGroup2" value="Quaterly" id="RadioGroup2_1" onClick="changeplanprice();" class="RadioGroup2" />
Quaterly</label>
<br>
<label>
<input type="radio" name="RadioGroup2" value="Monthly" id="RadioGroup2_2" onClick="changeplanprice();" class="RadioGroup2" />
Monthly</label>
<br>
<label>
<input type="radio" name="RadioGroup2" value="Other" id="RadioGroup2_3" onClick="changeplanprice();" class="RadioGroup2" />
Other</label>
<br>
<span class="radioRequiredMsg">Please make a selection.<span class="hint-pointer"> </span></span>
</dd>
</div>
<!--Plan Price-->
<div>
<script>
function changeplanprice() {
var plantype=document.getElementByClassName('RadioGroup1').value;
var planduration=document.getElementByClassName('RadioGroup2').value;
if(plantype=="Silver") {
if(planduration=="Monthly") {
document.getElementById('Price').value='£ 39.98';
document.getElementById('Price').readOnly=true;
}
else if(planduration=="Quaterly") {
document.getElementById('Price').value='£ 79.98';
document.getElementById('Price').readOnly=true;
}
else if(planduration=="Yearly") {
document.getElementById('Price').value='£ 124.98';
document.getElementById('Price').readOnly=true;
}
else if(planduration=="Other") {
document.getElementById('Price').value='';
document.getElementById('Price').readOnly=false;
}
}
else if(plantype=="Gold") {
if(planduration=="Monthly") {
document.getElementById('Price').value='£ 49.98';
document.getElementById('Price').readOnly=true;
}
else if(planduration=="Quaterly") {
document.getElementById('Price').value='£ 99.98';
document.getElementById('Price').readOnly=true;
}
else if(planduration=="Yearly") {
document.getElementById('Price').value='£ 179.98';
document.getElementById('Price').readOnly=true;
}
else if(planduration=="Other") {
document.getElementById('Price').value='';
document.getElementById('Price').readOnly=false;
}
}
else if(plantype=="Platinum") {
if(planduration=="Monthly") {
document.getElementById('Price').value='£ 59.98';
document.getElementById('Price').readOnly=true;
}
else if(planduration=="Quaterly") {
document.getElementById('Price').value='£ 199.98';
document.getElementById('Price').readOnly=true;
}
else if(planduration=="Yearly") {
document.getElementById('Price').value='£ 279.98';
document.getElementById('Price').readOnly=true;
}
else if(planduration=="Other") {
document.getElementById('Price').value='';
document.getElementById('Price').readOnly=false;
}
} }
</script>
<div>
<dt><label for="Price">Plan Price:</label></dt>
<dd class="bg"><input type="text" name="Price" id="Price" size="80" class="input" readonly="readonly" />
</dd>
</div>
First suggestion that I will give is to have single
document.getElementById('Price').readOnly=true;
This will make your code more readable.
Second suggestion is that you can have 2 arrays one for plantype and other for planduration, and the radio-buttons instead of text, have array index as value.
This will not only make your code more readable, but also more manageable.
Suppose if you have to add one planduration, you will have to add the same condition for all plantypes, where there is a possibility of missing out one case.
Your function could use a little bit of cleanup, but there is one problem that I see. You are using document.getElementByClassName(' ... ').value;. This isn't correct. The function is actually document.getElementsByClassName (note Elements is plural). This function returns an array of all elements with that class name. So you cannot call .value directly on that. You would need to loop through the array of elements to find which element is checked and take the value of that.
Given that all the radio buttons of one group have the same name, and there is another function, document.getElementsByName, there is no reason to use getElementsByClassName.
I would change your function. This is tested and works, and is more easily scalable, in case you come up with new pricing options. All you would have to do is add on to the prices object:
function changeplanprice() {
var plantype;
var plantypes = document.getElementsByName('RadioGroup1');
for (var i=0; i < plantypes.length; i++) {
if (plantypes[i].checked)
plantype = plantypes[i].value;
}
var planduration;
var plandurations = document.getElementsByName('RadioGroup2');
for (i = 0; i < plandurations.length; i++) {
if (plandurations[i].checked)
planduration = plandurations[i].value;
}
if (plantype === undefined || planduration === undefined)
return;
document.getElementById('Price').readOnly = (planduration != "Other");
var prices = {
"Silver":{
"Monthly":"£ 39.98",
"Quarterly":"£ 79.98",
"Yearly":"£ 124.98",
"Other":""
},
"Gold":{
"Monthly":"£ 49.98",
"Quarterly":"£ 99.98",
"Yearly":"£ 179.98",
"Other":""
},
"Platinum":{
"Monthly":"£ 59.98",
"Quarterly":"£ 199.98",
"Yearly":"£ 279.98",
"Other":""
},
"All-in-one":{
"Monthly":"...", /* prices weren't provided for All-in-one in the example */
"Quarterly":"...",
"Yearly":"...",
"Other":""
}
};
document.getElementById('Price').value = prices[plantype][planduration];
}

Categories