I have a list of 5 radio buttons, with the last radio button to select a manual entry text (an "other" option). I can't seem to get the form to work for all 5 possibilities - either it returns the radio value or the written value (currently only the written value and not any of the preset radio values). Can't get it to work for all of 5 possible returns.
Here's the javascript to either select text or clear it when unselected:
<script type= "text/javascript" >
function HandleRadioOtherBox(grp, txt)
{
var x, len = grp.length;
for (x =0; x<len; ++x)
{
if (grp[x].checked) break;
}
if (x < len && grp[x].value == txt.name)
{
txt.disabled = false;
txt.select();
txt.focus();
}
else
{
txt.value = "";
txt.disabled = true;
}
return true;
}
window.onload = function ()
{
var ele = document.forms[0].elements;
return HandleRadioOtherBox(ele['OPS'], ele['Country']);
}
</script>
And here, the HTML radio button portion:
<tr valign="top">
<td class="style3">Country: </td>
<td class="copy">
<input type="radio" name="OPS" value="United States" checked="checked"
onclick="return HandleRadioOtherBox(OPS, Country)" /> United States
<input type="radio" name="OPS" value="Canada"
onclick="return HandleRadioOtherBox(OPS, Country)" /> Canada
<input type="radio" name="OPS" value="England"
onclick="return HandleRadioOtherBox(OPS, Country)" /> England
<input type="radio" name="OPS" value="Australia"
onclick="return HandleRadioOtherBox(OPS, Country)" /> Australia <br />
<input type="radio" name="OPS" value="Country"
onclick="return HandleRadioOtherBox(OPS, Country)" /> Other Country:
<input type='text' name="Country" id="Country" maxlength='80' />
</td>
</tr>
Have spent many, many hours with not much of a hole made in the cement (yet). :-)
Help!
You can write a single function for your form which checks for two events:
radio button check
text input blur
and then gives an appropriate response based on which radio button registered a check event or whether the text input registered a blur event:
var radioButtons = document.querySelectorAll('input[type="radio"]');
var otherCountryRadio = document.querySelector('.other-country input[type="radio"]');
var otherCountryText = document.querySelector('.other-country input[type="text"]');
function returnValue() {
if (this === otherCountryRadio) {
otherCountryText.focus();
}
else {
if (this.value.match(/\w/)) {
console.log(this.value);
}
}
}
for (var i = 0; i < radioButtons.length; i++) {
radioButtons[i].addEventListener('change', returnValue, false);
}
otherCountryText.addEventListener('blur', returnValue, false);
div {
margin: 12px;
}
.other-country input[type="text"] {
visibility: hidden;
}
.other-country input:checked + input[type="text"] {
visibility: visible;
}
<form>
<div class="top-countries">
<label><input type="radio" name="OPS" value="United States" checked="checked" /> United States</label>
<label><input type="radio" name="OPS" value="Canada" /> Canada</label>
<label><input type="radio" name="OPS" value="England" /> England</label>
<label><input type="radio" name="OPS" value="Australia" /> Australia</label>
</div>
<div class="other-country">
<label>
<input type="radio" name="OPS" value="Other" /> Other Country
<input type="text" name="Country" />
</label>
</div>
</form>
Related
I am struggling to find a way how to display information based on two options in a forms.
What I mean is, there are two options in "Select Gender". If they choose "Male", then a paragraph should appear. If they choose "Female", then another paragraph should appear on the website. How can I do this?
This is the forms code:
<form>
Select Gender
<br />
<input type="radio" name="gender" id="male">
<label for="male">Male</label>
<br />
<input type="radio" name="gender" id="female">
<label for="female">Female</label>
<br />
<br />
</form>
Use CSS only
Note that I added divs around your inputs and the .popup-descriptions, otherwise this does not work.
.popup-description{
display: none;
}
[type="radio"]:checked ~ label ~ .popup-description{
display: block;
}
<form>
Select Gender
<div>
<input type="radio" name="gender" id="male">
<label for="male">Male</label>
<p class="popup-description">
This text is shown when the user selects <b>male</b>.
</p>
</div>
<div>
<input type="radio" name="gender" id="female">
<label for="female">Female</label>
<p class="popup-description">
This text is shown when the user selects <b>female</b>.
</p>
</div>
</form>
Use javascript with jQuery
Note that I added a value to your inputs, otherwise this does not work.
$(document).ready(function(){
$("[name='gender']").on("change", function(){
var v = $(this).val();
var n = $(this).attr("name");
$(".popup-description[data-for='" + n + "']").hide();
$(".popup-description[data-for='" + n + "'][data-selected-value='" + v + "']").show();
});
});
.popup-description{
display: none;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form>
Select Gender
<br />
<input type="radio" name="gender" id="male" value="male">
<label for="male">Male</label>
<p class="popup-description" data-for="gender" data-selected-value="male">
This text is shown when the user selects <b>male</b>.
</p>
<br />
<input type="radio" name="gender" id="female" value="female">
<label for="female">Female</label>
<p class="popup-description" data-for="gender" data-selected-value="female">
This text is shown when the user selects <b>female</b>.
</p>
<br />
</form>
Use plain javascript
Note that I added a value to your inputs, otherwise this does not work.
(function(){
var radios = document.querySelectorAll("[name='gender']");
if(radios !== null){
for(var i = 0; i < radios.length; i++){
var el = radios.item(i);
el.addEventListener("change", function(){
if(this.checked){
var v = this.value;
var n = this.name;
var h = document.querySelectorAll(".popup-description[data-for='" + n + "']");
if(h !== null){
for(var j = 0; j < h.length; j++){
var e = h.item(j);
if(e.getAttribute("data-selected-value") == v){
e.style.display = "block";
}
else{
e.style.display = "none";
}
}
}
}
});
}
}
})();
.popup-description{
display: none;
}
<form>
Select Gender
<br />
<input type="radio" name="gender" id="male" value="male">
<label for="male">Male</label>
<p class="popup-description" data-for="gender" data-selected-value="male">
This text is shown when the user selects <b>male</b>.
</p>
<br />
<input type="radio" name="gender" id="female" value="female">
<label for="female">Female</label>
<p class="popup-description" data-for="gender" data-selected-value="female">
This text is shown when the user selects <b>female</b>.
</p>
<br />
</form>
I really don't know how to program in Javascript, yet I've tried to do some stuff. I have values to be summed if some are selected. The following function does sum operation and show result at once without clicking a button only for checkbox fields, not for the dropdown list and text fields.
However, I need to involve the selected values as well from the dropdown lists and entered both text fields in the same manner of the checkboxes and their immediate responses(output).
I think change method can be used in the same manner.
#Edit:
Sorry, I forgot the tell but, I need to multiply the m2 entered value by before summing with 3134,204499 and Bina Yasi with -566,2202888.
function calcAndShowTotal() {
var total = 55435.04798; // it is constant value which must be the beginning value.
$('#housepriceguesslist :checkbox:checked').each(function() {
total += parseFloat($(this).attr('price')) || 0;
});
$('#total').val(total);
}
$('#housepriceguesslist :checkbox').change(calcAndShowTotal).change();
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="housepriceguesslist">
<select id="ilce">
<option value="0">Choose a state</option>
<option value="63999.50712318567">Adalar</option>
<option value="6259.918435398593">Ataşehir</option>
<option value="46285.35729304834">Beykoz</option>
<option value="54258.92953697798">Kadıköy</option>
<option value="-3500.620905653726">Kartal</option>
<option value="12889.41219909602">Maltepe</option>
<option value="-33711.83156847153">Pendik</option>
<option value="-34577.42485251657">Sancaktepe</option>
<option value="-52183.1608811019">Sultanbeyli</option>
<option value="-34760.71735007784">Tuzla</option>
<option value="-27379.87966213786">Çekmeköy</option>
<option value="-5332.203990418937">Ümraniye</option>
<option value="26485.33532820411">Üsküdar</option>
<option value="-18732.62070553167">Şile</option>
</select>
<select id="odasalon">
<option value="0">Choose room number</option>
<option value="5940.027623576261">1+0</option>
<option value="-1399.625767475593">1+1</option>
<option value="-3033.638999060459">2+1</option>
<option value="11519.83954756076">3+1</option>
<option value="-7018.52116545078">4+1</option>
<option value="-6008.081239150166">5+1</option>
</select>
m2: <input type="text" id="m2" /> Bina Yasi: <input type="text" id="binayasi" />
<br/>
<br/> Features:
<br/>
<br/>
<input type="checkbox" id="Bati" value="Bati" price="-783.4452683566533" /> <label for="Bati">Bati</label>
<br/>
<input type="checkbox" id="Dogu" value="Dogu" price="-4895.732009084263" /> <label for="Dogu">Dogu</label>
<br/>
<input type="checkbox" id="Guney" value="Guney" price="-2599.001349652765" /> <label for="Guney">Guney</label>
<br/>
<input type="checkbox" id="Kuzey" value="Kuzey" price="3832.013070771234" /> <label for="Kuzey">Kuzey</label>
<br/>
<input type="checkbox" id="Amerikan Mutfak" value="Amerikan Mutfak" price="2346.347889828301" /> <label for="Amerikan Mutfak">Amerikan Mutfak</label>
<br/>
<input type="checkbox" id="Dusakabin" value="Dusakabin" price="-176.5092353740256" /> <label for="Dusakabin">Dusakabin</label>
<br/>
<input type="checkbox" id="Akilli Ev" value="Akilli Ev" price="-4756.206384200719" /> <label for="Akilli Ev">Akilli Ev</label>
<br/>
<input type="checkbox" id="Ebeveyn Banyosu" value="Ebeveyn Banyosu" price="10135.50644456019" /> <label for="Ebeveyn Banyosu">Ebeveyn Banyosu</label>
<br/>
<input type="checkbox" id="Kiler" value="Kiler" price="-10693.49979821809" /> <label for="Kiler">Kiler</label>
<br/>
<input type="checkbox" id="Kuvet" value="Kuvet" price="-941.0629741243247" /> <label for="Kuvet">Kuvet</label>
<br/>
<input type="checkbox" id="Parke Zemin" value="Parke Zemin" price="-8453.847199707092" /> <label for="Parke Zemin">Parke Zemin</label>
<br/>
<input type="checkbox" id="Seramik Zemin" value="Seramik Zemin" price="1545.025601000643" /> <label for="Seramik Zemin">Seramik Zemin</label>
<br/>
<input type="checkbox" id="Sauna" value="Sauna" price="8677.708176289747" /> <label for="Sauna">Sauna</label>
<br/>
<input type="checkbox" id="Spor Salonu" value="Spor Salonu" price="1159.884679563385" /> <label for="Spor Salonu">Spor Salonu</label>
<br/>
<input type="checkbox" id="Tenis Kortu" value="Tenis Kortu" price="16065.26794172257" /> <label for="Tenis Kortu">Tenis Kortu</label>
<br/>
</div>
<input type="text" id="total" value="0" />
You can loop over all the <select> boxes and text inputs with:
function calcAndShowTotal() {
var total = 55435.04798; // it is constant value which must be the beginning value.
$('#housepriceguesslist :checkbox:checked').each(function() {
total += parseFloat($(this).attr('price')) || 0;
});
$("#housepriceguesslist select, #housepriceguesslist :text").each(function() {
let multiplier = 1;
if (this.id == "m2") {
multiplier = 3134.204499;
}
else if (this.id == "binayasi") {
multiplier = -566.2202888;
}
if (this.value) {
total += parseFloat(this.value) * multiplier;
}
});
$('#total').val(total);
}
And if you change the checkboxes to use value instead of price, you can do them all in one loop:
function calcAndShowTotal() {
var total = 55435.04798; // it is constant value which must be the beginning value.
$('#housepriceguesslist :checkbox:checked').each(function() {
total += parseFloat($(this).attr('price')) || 0;
});
$("#housepriceguesslist select, #housepriceguesslist :text, #housepriceguesslist :checkbox:checked").each(function() {
let multiplier = 1;
if (this.id == "m2") {
multiplier = 3134.204499;
else if (this.id == "binyasi") {
multiplier = -566.2202888;
}
if (this.value) {
total += parseFloat(this.value) * multiplier;
}
});
$('#total').val(total);
}
And call the function when any of the inputs are changed:
$('#housepriceguesslist input, #housepriceguesslist select').change(calcAndShowTotal).change();
This solution is simple, just the get the list of all the inputs (i.e. checkbox, and dropdown) using the .find() method and the selector 'input:checkbox, input:text, select'. Then verify if each one of these inputs elements has the attribute checked or select for the checkbox and select input types respectively, or it is a multiplier for the text inputs. This verification ca be done inside of the each() method callback. Finally, just convert then the value to a number, using the parseFloat() method and add it to the total accumulator.
Finally, sum the value to the total input. Like this:
let container;
let inputs;
let total;
function calcAndShowTotal() {
let sum = 55435.04798; // it is constant value which must be the beginning value.
let value;
inputs.each(function() {
if ($(this).is('input:checkbox:checked')) {
// If is a checkbox
value = parseFloat($(this).attr('price')) || 0;
sum += value;
} else if ($(this).is('input:text:not(#total)')) {
// If is a text wait until you move to another element
let factor = 1;
if (this.id == 'm2') {
factor = 3134.204499;
} else if (this.id == 'binayasi') {
factor = -566.2202888;
}
value = parseFloat($(this).val()) * factor || 0;
sum += value;
} else if ($(this).is('select')) {
// If is a option from the select element
value = parseFloat($('option:selected', this).val()) || 0;
sum += value;
}
});
total.val(sum);
}
function initHandlers() {
inputs.on('keydown', function(e) {
let focusable, next;
if (e.keyCode == 13) {
focusable = inputs.filter(':visible');
next = focusable.eq(focusable.index(this) + 1);
if (next.length) {
next.focus();
}
return false;
}
});
inputs.change(calcAndShowTotal);
calcAndShowTotal();
}
$(function() {
console.log('ready!');
total = $('#total');
container = $('#housepriceguesslist');
inputs = container.find('input:checkbox, input:text, select');
initHandlers();
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="housepriceguesslist">
Total: <input type="text" id="total" value="0" />
<br/>
<br/>
<select id="ilce">
<option value="0">Choose a state</option>
<option value="63999.50712318567">Adalar</option>
<option value="6259.918435398593">Ataşehir</option>
<option value="46285.35729304834">Beykoz</option>
<option value="54258.92953697798">Kadıköy</option>
<option value="-3500.620905653726">Kartal</option>
<option value="12889.41219909602">Maltepe</option>
<option value="-33711.83156847153">Pendik</option>
<option value="-34577.42485251657">Sancaktepe</option>
<option value="-52183.1608811019">Sultanbeyli</option>
<option value="-34760.71735007784">Tuzla</option>
<option value="-27379.87966213786">Çekmeköy</option>
<option value="-5332.203990418937">Ümraniye</option>
<option value="26485.33532820411">Üsküdar</option>
<option value="-18732.62070553167">Şile</option>
</select>
<select id="odasalon">
<option value="0">Choose room number</option>
<option value="5940.027623576261">1+0</option>
<option value="-1399.625767475593">1+1</option>
<option value="-3033.638999060459">2+1</option>
<option value="11519.83954756076">3+1</option>
<option value="-7018.52116545078">4+1</option>
<option value="-6008.081239150166">5+1</option>
</select>
m2: <input type="text" id="m2" />
Bina Yasi: <input type="text" id="binayasi" />
<br/>
<br/> Features:
<br/>
<br/>
<input type="checkbox" id="Bati" value="Bati" price="-783.4452683566533" /> <label for="Bati">Bati</label>
<br/>
<input type="checkbox" id="Dogu" value="Dogu" price="-4895.732009084263" /> <label for="Dogu">Dogu</label>
<br/>
<input type="checkbox" id="Guney" value="Guney" price="-2599.001349652765" /> <label for="Guney">Guney</label>
<br/>
<input type="checkbox" id="Kuzey" value="Kuzey" price="3832.013070771234" /> <label for="Kuzey">Kuzey</label>
<br/>
<input type="checkbox" id="Amerikan Mutfak" value="Amerikan Mutfak" price="2346.347889828301" /> <label for="Amerikan Mutfak">Amerikan Mutfak</label>
<br/>
<input type="checkbox" id="Dusakabin" value="Dusakabin" price="-176.5092353740256" /> <label for="Dusakabin">Dusakabin</label>
<br/>
<input type="checkbox" id="Akilli Ev" value="Akilli Ev" price="-4756.206384200719" /> <label for="Akilli Ev">Akilli Ev</label>
<br/>
<input type="checkbox" id="Ebeveyn Banyosu" value="Ebeveyn Banyosu" price="10135.50644456019" /> <label for="Ebeveyn Banyosu">Ebeveyn Banyosu</label>
<br/>
<input type="checkbox" id="Kiler" value="Kiler" price="-10693.49979821809" /> <label for="Kiler">Kiler</label>
<br/>
<input type="checkbox" id="Kuvet" value="Kuvet" price="-941.0629741243247" /> <label for="Kuvet">Kuvet</label>
<br/>
<input type="checkbox" id="Parke Zemin" value="Parke Zemin" price="-8453.847199707092" /> <label for="Parke Zemin">Parke Zemin</label>
<br/>
<input type="checkbox" id="Seramik Zemin" value="Seramik Zemin" price="1545.025601000643" /> <label for="Seramik Zemin">Seramik Zemin</label>
<br/>
<input type="checkbox" id="Sauna" value="Sauna" price="8677.708176289747" /> <label for="Sauna">Sauna</label>
<br/>
<input type="checkbox" id="Spor Salonu" value="Spor Salonu" price="1159.884679563385" /> <label for="Spor Salonu">Spor Salonu</label>
<br/>
<input type="checkbox" id="Tenis Kortu" value="Tenis Kortu" price="16065.26794172257" /> <label for="Tenis Kortu">Tenis Kortu</label>
<br/>
</div>
Note:
Remember to round the numbers to get more precision. The text modification will apply after you tab, or move to another element. So I added an enter listener so when you press enter is gonna move to the next element like when you press tab. Also, I moved the total to the top so you can see the results in the preview.
Update:
I recommend you to use the $(function(){}); to get the document when is ready. Inside you can assign the values of your elements. I notice that there was a bug in my code whenever ever you uncheck a checked element the Total should be 55435.04798, but it shows the double it is because total is also a text input.
Similar to Barmar's, I added all elements to the .each() loop but also added the .change() handler to all elements:
var context = $('#housepriceguesslist');
var elems = $('input:checkbox, input:text, select', context);
function calcAndShowTotal() {
var total = 55435.04798; // it is constant value which must be the beginning value.
elems.each(function() {
if ( $(this).is('input:checkbox:checked') ) {
total += parseFloat($(this).attr('price')) || 0;
} else if ( $(this).is('#m2') ) {
total += parseFloat($(this).val()) * 3134.204499 || 0;
} else if ( $(this).is('#binayasi') ) {
total += parseFloat($(this).val()) * -566.2202888 || 0;
} else if ( $(this).is('select') ) {
total += parseFloat($('option:selected',this).val()) || 0;
}
});
$('#total').val(total);
}
elems.change(calcAndShowTotal); // handlers
calcAndShowTotal(); // first run
See example here: https://jsfiddle.net/qgvsern4/1/
I have radiobuttons like below:
Apple
<input type="radio" id="one" name="apple" data-price="10" value="light"/> Light
<input type="radio" id="two" name="apple" data-price="20" value="dark" /> Dark
<input type="text" id="appleqty" name="appleqty" value="" />
Mango
<input type="radio" id="three" name="Mango" data-price="30" value="light"/> Light
<input type="radio" id="one" name="Mango" data-price="40" value="dark" /> Dark
<input type="text" id="Mangoqty" name="Mangoqty" value="" />
Pine Apple
<input type="radio" id="four" name="Pineapple" data-price="50" value="light"/> Light
<input type="radio" id="five" name="Pineapple" data-price="60" value="dark" /> Dark
<input type="text" id="Pineappleqty" name="Pineappleqty" value="" />
Grape
<input type="radio" id="six" name="Grape" data-price="70" value="light"/> Light
<input type="radio" id="seven" name="Grape" data-price="80" value="dark" /> Dark
<input type="text" id="Pineappleqty" name="Pineappleqty" value="" />
The radiobuttons are separated in a Group as (Apple,Mango,Pineapple,Grape).
I need to add the Price with the Quantity he needs.
Example:
If a user clicked Dark Apple in the radiobutton with 1 Qty the Price should be 20 and if the user changed the clicked Radio to the Light Apple radiobutton then the price should be 10 - 20(Previous Price If Checked) = 10 .
Is this possible using JavaScript?
My code that I have tried:
function upprice(ref)
{
var elname = ref.getAttribute("name");
var qtyname = elname+"qty";
var price = ref.getAttribute("proprice");
var qty = parseInt(document.getElementById(qtyname).value)
var newprice = parseInt(price*qty);
var olprice = parseInt(document.getElementById("orderpagepriceinstant").innerHTML);
var totalprice = parseInt(olprice+newprice);
document.getElementById("orderpagepriceinstant").innerHTML = parseInt(totalprice)
}
Your inputs should be something like:
<input type="radio" name="apple" value="10">Light
<input type="radio" name="apple" value="20">Dark
<input type="text" name="appleqty" value="">
You can put a click listener on the radio buttons and a change listener on the quantity to update the price:
<input type="radio" onclick="updatePrice(this)" ...>
<input type="text" onclick="updatePrice(this)" ...>
and the update function is:
function updatePrice(el) {
var priceEach, quantity, itemValue;
if (el.type == 'radio') {
priceEach = getRBValue(el);
quantity = el.form[el.name + 'qty'].value;
} else if (el.type == 'text') {
quantity = el.value;
priceEach = getRBValue(el.form[el.name.replace(/qty$/,'')]);
}
/*
code here to validate the value of quantity
*/
itemValue = quantity * priceEach;
/*
do something with itemValue
*/
alert(itemValue);
}
// Get the value of a radio button set
function getRBValue(el) {
var buttons;
// See if have been passed a button or button set (NodeList)
if (el.type == 'radio') {
buttons = el.form[el.name];
} else if (typeof el.length == 'number') {
buttons = el;
}
if (buttons) {
for (var i=0, iLen=buttons.length; i<iLen; i++) {
if (buttons[i].checked) {
return buttons[i].value;
}
}
}
}
</script>
The markup, you can also add a click listener to the form to do updates rather than on each radio button. You should also have a reset button so the user can clear the form.
<form ... >
<input type="radio" name="apple" value="10" onclick="updatePrice(this)">Light
<input type="radio" name="apple" value="20" onclick="updatePrice(this)">Dark
<input type="text" name="appleqty" value="" onchange="updatePrice(this)">
<br>
<input type="reset">
</form>
Here's a quick jQuery example: http://jsfiddle.net/FTscC/
(laptop dying, I'll elaborate when I can tomorrow!)
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];
}
I would like to build a javascript so a user can choose only one option between the the mentioned below. Could you give me some pointers how to do this since I am a javascript noob.
Thank you!
This is the picture of the part of a menu
<td><label for="dock_books_search_visible_online"> Visible online?</label></td>
<td><input type="checkbox" name="option" value="checkedVisibleOk" id="dock_books_visible_ok" /> </td>
<td><label for="dock_books_search_visible_online_yes"> Yes</label></td>
<td><input type="checkbox" name="option" value="checkedVisibleNok" id="dock_books_visible_nok" /> </td>
<td><label for="dock_books_search_visible_online_no"> No</label></td>
For single selection from multiple options we use Radio Buttons not CheckBoxes.
You should use some thing like this.
<input type="radio" name="option" value="Yes" id="yes" />
<input type="radio" name="option" value="No" id="no" />
But still if you want to go the other way round, Just add the following script in your head tag:
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"></script>
<script>
$(document).ready(function(){
$(':checkbox').bind('change', function() {
var thisClass = $(this).attr('class');
if ($(this).attr('checked')) {
$(':checkbox.' + thisClass + ":not(#" + this.id + ")").removeAttr('checked');
}
else {
$(this).attr('checked', 'checked');
}
});
});
</script>
Here is the fiddle for above.
Hope this helps.
This looks like a job for radio buttons, not checkboxes.
you got a point to use radio buttons any way here is the javascript solution
i used it in my project when there is search criteria and search result in data grid by
ajax having 13 records when i check one record it disables the rest
code for javascript enable disable check boxes jsfiddle
<form name="mainForm" method="GET">
Visible online?
<input type="checkbox" name="option" value="checkedVisibleOk" id="option" onclick="changeCheckBox();"/>
yes
<input type="checkbox" name="option" value="checkedVisibleNok" id="option" onclick="changeCheckBox();"/>
no
</form>
<script>
var serNoChecked="";
function changeCheckBox() {
try {
var max = document.mainForm.option.length;
var count = 0;
for (var i = 0; i < max; i++) {
if (document.mainForm.option[i].checked == true) {
count++;
serNoChecked = i;
}
}
if (count == 1) {
for (var i = 0; i < max; i++) {
if (document.mainForm.option[i].checked == false) {
document.mainForm.option[i].disabled = true;
}
}
}
else if (count == 0) {
for (var i = 0; i < max; i++) {
document.mainForm.option[i].disabled = false;
}
}
if (null == max) return false;
if (count == 0) {
return true;
}
else if (count > 0) {
return false;
}
}
catch (e) {
alert(e.message);
}
}
</script>
Try using Radio Button's, Give them the same name to group them and only allow 1 to be selected:
<td>
<label for="dock_books_search_visible_online"> Visible online?</label>
</td>
<td>
<input type="radio" name="option" value="checkedVisibleOk" id="dock_books_visible_ok" />
</td>
<td>
<label for="dock_books_search_visible_online_yes"> Yes</label>
</td>
<td><input type="radio" name="option" value="checkedVisibleNok" id="dock_books_visible_nok" />
</td>
<td>
<label for="dock_books_search_visible_online_no"> No</label>
</td>
Check this JSFiddle.
Hi why are you using checkbox? Checkboxes are not for the functionality that you want. Radio buttons are exact what you want to use.
<form>
<input type="radio" name="sex" value="male" /> Male<br />
<input type="radio" name="sex" value="female" /> Female
</form>
For further details look here
function toggle(chkBox, field) {
for ( var i = 0; i < field.length; i++) {
field[i].checked = false;
}
chkBox.checked = true;
}
<td>
<INPUT type="checkbox" name="xyz" onClick="toggle(this,document.myform.xyz);" value="${incident.incidentID}">
</td>
Use radio buttons and ensure that the name tag is consistent with all options and it'll automatically select just one w/o the need for additional code or JS.