Showing Radio Button calculations in total box? - javascript

How could I make it so if a user clicks the radio button with the data-price of 5.99 then the price will show up in the total box but if the user clicks the "no charge" radio button then nothing will show up
var radio = document.querySelector("input[name=deliveryType]");
for (var i = 0; i < radio.length; i++) {
if (radio.checked) {
l_totalPrice += parseFloat(radio.dataset.price);
}
}
total.value = l_totalPrice;
<section id="collection">
<h2>Collection method</h2>
<p>Please select whether you want your chosen event ticket(s) to be delivered to your home address (a charge applies for this) or whether you want to collect them yourself.</p>
<p>
Home address - £5.99 <input type="radio" name="deliveryType" value="home" data-price="5.99" checked> | Collect from ticket office - no charge <input type="radio" name="deliveryType" value="ticketOffice" data-price="0">
</p>
</section>
<section id="checkCost">
<h2>Total cost</h2>
Total <input type="text" name="total" size="10" readonly>
</section>

Using event delegation and the dataset API, this is easy:
let total = document.querySelector("input[name='total']");
// Set the event listener up on an ancestor of both radio buttons
document.getElementById("collection").addEventListener("click", function(event){
// When the event is triggered here, check the event.target to see what element
// actually triggered the event.
if(event.target.value === "home"){
// Use the dataset API to access the data-* attribute.
total.value = event.target.dataset.price;
} else {
total.value = "";
}
});
#collection h1, #checkCost h1 { font-size:1.9em; }
<section id="collection">
<h1>Collection method</h1>
<p>Please select whether you want your chosen event ticket(s) to be delivered to your home address (a charge applies for this) or whether you want to collect them yourself.</p>
<p>
Home address - £5.99
<input type="radio" name="deliveryType" value="home" data-price="5.99" checked> |
Collect from ticket office - no charge
<input type="radio" name="deliveryType" value="ticketOffice" data-price="0">
</p>
</section>
<section id="checkCost">
<h1>Total cost</h1>
Total <input type="text" name="total" size="10" readonly>
</section>
FYI: The first heading element within a section should always be an h1. If you don't want that font-size, just modify it with CSS. Never use an HTML element because of the default styling that a browser applies to it.

Here you go
function updateTotal(ele) {
document.getElementById("total").value = ele.value;
}
<input type="radio" id="home" value="5.99" name="delivery_type" onchange="updateTotal(this)"/>
<label for="home">Home address - <b>£5.99</b></label>
<br>
<input type="radio" id="office" value="0" name="delivery_type" onchange="updateTotal(this)"/>
<label for="office">Collect from ticket office - <b>no charge</b></label>
<br>
<br>
<input type="number" id="total" name="total" placeholder="Choose a delivery address" readonly/>
Let me know if you have any confusions :)

Related

My javascript code isn't incrementing/decrementing in the if statement

I'm creating a form that will have multiple items to choose from and check in(add/increment) and checkout(minus/decrement)and it only works when the laptop variable is equal to 1. I want to set the total amount of an item and then whatever option they choose it'll either increment or decrement the variable associated with that item. I also can't figure out a way to make sure the variable won't reset every time the form closes and opens again.
function updateCount (form) {
//need to figure out way for count to not reset to total when closing
form
//only works when set to 1
var laptop=1;
if (form.option1.checked && form.optionin.checked) {
laptop++;
alert ("Your response has been recorded");
}
if (form.option1.checked && form.optionout.checked) {
laptop--;
alert ("Your response has been recorded");
}
if (form.option1.checked && form.optionout.checked && laptop===0) {
alert ("Item currently unavailable, choose another item");
}}
<h1>CS Equipment Renatal Form</h1>
<form>
<!--top of form with name and line break for text, don't need
anything with the Name: -->
Name:<br>
<!--creating the variable type for textfield and the name of it which
is fullname-->
<input type="text" name="fullname"><br>
<br>
<!--email textfield with line break after meaning new line-->
OU Email:<br>
<input type="email" name="ouemail"><br>
<br>
<!--doing the checkboxes for rental types with id since the id is
used in the script -->
Equipment Rental Type<br>
Laptop <input type="checkbox" name="option1" value="laptop"
id="option1"><br>
Tablet <input type="checkbox" name="option2" value="tablet"
id="option2"><br>
Monitor <input type="checkbox" name="option3" value="monitor"
id="option3"><br>
Camera <input type="checkbox" name="option4" value="camera"
id="option4"><br>
<br>
<!--doing checkboxes for checkout and check with id because its used
in script-->
Select One<br>
Check In <input type="checkbox" name="optionin" value="checkIn"
id="checkOut"><br>
Check Out <input type="checkbox" name="optionout" value="checkOut"
id="checkIn"><br>
<br>
<!--adding submit button and associating it with script function-->
<input type="submit" name="submit" value="submit"
onClick="updateCount(this.form)">
</form>
I assume var laptop=1; should hold the number of available laptops.
The problem here is that you're declaring it inside the function that should actually manage it - so you're basically resetting it with each call to this function.
To get around this you need to make it a global variable - one whichs is defined before and outside of function updateCount (form) { }.
Furthermore you should get rid of the onclick event on the input field and instead use the onsubmit event on the form itself. This way you can validate the form before it's actually submitted.
Take a look at this example:
var laptop = 1;
function updateCount(form) {
if (form.option1.checked && form.optionin.checked) {
laptop++;
alert("Your response has been recorded");
return true;
}
if (form.option1.checked && form.optionout.checked) {
laptop--;
alert("Your response has been recorded");
return true;
}
if (form.option1.checked && form.optionout.checked && laptop === 0) {
alert("Item currently unavailable, choose another item");
return false;
}
return false;
}
<h1>CS Equipment Renatal Form</h1>
<form onsubmit="return updateCount(this)">
<!--top of form with name and line break for text, don't need
anything with the Name: -->
Name:<br>
<!--creating the variable type for textfield and the name of it which
is fullname-->
<input type="text" name="fullname"><br>
<br>
<!--email textfield with line break after meaning new line-->
OU Email:<br>
<input type="email" name="ouemail"><br>
<br>
<!--doing the checkboxes for rental types with id since the id is
used in the script -->
Equipment Rental Type<br> Laptop <input type="checkbox" name="option1" value="laptop" id="option1"><br> Tablet <input type="checkbox" name="option2" value="tablet" id="option2"><br> Monitor <input type="checkbox" name="option3" value="monitor" id="option3"><br> Camera <input type="checkbox" name="option4" value="camera" id="option4"><br>
<br>
<!--doing checkboxes for checkout and check with id because its used
in script-->
Select One<br> Check In <input type="checkbox" name="optionin" value="checkIn" id="checkOut"><br> Check Out <input type="checkbox" name="optionout" value="checkOut" id="checkIn"><br>
<br>
<!--adding submit button and associating it with script function-->
<input type="submit" name="submit" value="submit">
Many issues here:
1- form.option1 is not a valid way of accessing the checkbox with id option1. Use document.getElementById("option1") instead. Same goes for optionin and optionout
2- Your button has type "submit", which will reload the page and reset your variable laptop (unless you save it using a cookie or localStorage). A simple way of preventing the button from refreshing the page is changing its type to "button".
3- As pointed out by #obscure's answer, you should declare your variable laptop outside of the updateCount function.
4- I believe you don't want users to select both "Check in" and "Check out" at the same time. For this, use radio buttons instead of a checkbox (note that both radio buttons have the same name attribute, so that you can't select both together).
var laptop=1; //will not reset as long as the page is not refreshed
//a way of preventing the from from refreshing the page is to change the button type to "button"
function updateCount (form) {
var laptop = document.getElementById("option1");
var option_in = document.getElementById("checkIn");
var option_out = document.getElementById("checkOut");
if (laptop.checked && option_in.checked) {
laptop++;
alert ("Your response has been recorded - Check In");
}
if (laptop.checked && option_out.checked) {
laptop--;
alert ("Your response has been recorded - Check Out");
}
if (laptop.checked && option_out.checked && laptop===0) {
alert ("Item currently unavailable, choose another item");
}
}
<!DOCTYPE html>
<html>
<h1>CS Equipment Renatal Form</h1>
<form>
<!--top of form with name and line break for text, don't need
anything with the Name: -->
Name:<br>
<!--creating the variable type for textfield and the name of it which
is fullname-->
<input type="text" name="fullname"><br>
<br>
<!--email textfield with line break after meaning new line-->
OU Email:<br>
<input type="email" name="ouemail"><br>
<br>
<!--doing the checkboxes for rental types with id since the id is
used in the script -->
Equipment Rental Type<br>
Laptop <input type="checkbox" name="option1" value="laptop"
id="option1"><br>
Tablet <input type="checkbox" name="option2" value="tablet"
id="option2"><br>
Monitor <input type="checkbox" name="option3" value="monitor"
id="option3"><br>
Camera <input type="checkbox" name="option4" value="camera"
id="option4"><br>
<br>
<!--doing checkboxes for checkout and check with id because its used
in script-->
Select One<br>
Check In <input type="radio" name="changeQty" value="checkIn"
id="checkIn"><br>
Check Out <input type="radio" name="changeQty" value="checkOut"
id="checkOut"><br>
<br>
<!--adding submit button and associating it with script function-->
<input type="button" name="submit" value="submit"
onClick="updateCount(this.form)">
</form>
</html>
In order to save the laptop variable if the page is refreshed, consider using a cookie, localStorage, or some server-side scripting.

HTML/ JavaScript radio button selections to output as summary of options

I'm trying to build a form that saves all of your selections of radio buttons and outputs as a summary upon submission. I am fairly new to JavaScript so please bear with me.
You are supposed to select between, let's say, three options per section. Depending on what was previously selected after you press Submit, it will open a lightbox and give you a summary of your choices before you submit the choices to be sent via email.
For what I have right now, there is only one section and three options to choose from.
HTML:
<div id="options">
<form method="get">
<label class ="rad">
<input type="radio" name ="O1" value="small"/>
<img src="img.jpg">
</label>
<label class ="rad">
<input type="radio" name ="O2" value="small"/>
<img src="img.jpg">
</label>
<label class ="rad">
<input type="radio" name ="O3" value="small"/>
<img src="img.jpg">
</label>
<input type="submit" value="SUBMIT"/>
</form>
</div>
JavaScript:
$(document).ready(function() {
$("#radio_submit").click(function (e) {
var checked_O1_radio = $('input:radio[name=O1]:checked').val();
var checked_O2_radio = $('input:radio[name=O2]:checked').val();
var checked_O3_radio = $('input:radio[name=O3]:checked').val();
if(checked_O1_radio===undefined || checked_O2_radio===undefined || checked_O3_radio===undefined)
{
alert('Please select a leather option then continue.');
}else{
alert('You Chose "' +checked_O1_radio);
}else{
alert('You Chose "' +checked_O2_radio);
}else{
alert('You Chose "' +checked_O3_radio);
}
});
});
Try this if i under stand your question correctly:
you can use same name then automatically only one will be selected and find the selected leather with a single check.
<label class ="rad">
<input type="radio" name ="O1" value="small"/>
</label>
<label class ="rad">
<input type="radio" name ="O1" value="medium"/>
</label>
<label class ="rad">
<input type="radio" name ="O1" value="large"/>
</label>
<input type="submit" value="SUBMIT" id = "Submitbutton"/>
$(document).ready(function() {
$("#Submitbutton").click(function (){
console.log($('input:radio[name=O1]:checked').val());
})
});
Please mark it as to answer if it helps you.

Keeping a running total with Javascript in a span element

I'm trying to write a piece of code that is supposed to keep a running total. More specifically what I would like it to do is, every time you click the button to add the sub total to the total, it should keep adding into the subtotal. The way the whole thing works now is, there is three meal items to choose from in a dropdown that each have their own price. When a food item is selected, the user types in how many of that item they want. Then user clicks the add to total button to add the food item to one text field. Under that field is a span that shows the grand total after a $3.50 delivery charge is added on. The span is where I want the running total to keep adding the sum every time the button is clicked. I am new to Javascript so I've been trying my best. I've also looked at topics here on SO to see if I can find something similar to my issue and I've seen some that are close but not quite what I'm looking for. Here"s my code...
<script>
function myTotal()
{
var meals = document.getElementById("foodItems").value;
var howMany = document.getElementById("itemTotal").value;
var shippingCost = "3.50";
var totalBill = parseFloat(meals) * howMany + parseFloat(shippingCost);
var addingTotal = parseFloat(meals) * howMany;
var runTotal = document.getElementById("runningTotal").value;
if (isNaN(totalBill)) { // Cash calculator
document.getElementById("total").value = "Invalid amount"
//alert("result of isNaN" ); //The input amount is a non numeric string. It is or contains letters and/or spaces
}
else { //adds total to the sub total field
document.getElementById("total").value = "$" + parseFloat(addingTotal).toFixed(2).replace(/(\d)(?=(\d\d\d)+(?!\d))/g, "$1,");
//Convert input value into a floating point number. toFixed() requires a number value to work with
}//end Cash Calculator
var i = ""; //This piece is where I'm trying to begin the running total
if(i=totalBill, i=howMany*totalBill, i++ ){//adds delivery charge + subtotal. But doesn't keep a running total
document.getElementById("runningTotal").innerHTML = parseFloat(totalBill).toFixed(2);
}
else {
document.getElementById("runningTotal").innerHTML = parseFloat(i++) * howMany;
}
}
</script>
<form id="survey" name="survey" method="get" action="formHandler.php" class="col-4">
<!-- enter your forms code below -->
<div id="fieldset">
<legend>Place an Order!</legend>
<h3>There is a $3.50 delivery fee</h3>
<fieldset>
<label for="foodItems">Quick Meal Food Items</label>
<select name="foodItems" id="foodItems">
<option value="6.00">Pepperoni Pizza - $6.00</option>
<option value="3.00">Bacon BBQ Burger - $3.00</option>
<option value="8.00">Steak and Eggs - $8.00</option>
</fieldset>
<!--The "input" element has "required" in the parameters so the user must fill out all fields but the email.-->
<fieldset>
<input type="text" name="itemTotal" id="itemTotal" size="25" required>How Many Orders?(Limit To 5 per Meal Type)</input>
</fieldset>
<fieldset>
<input type="button" name="click" id="button" value="Add to Order" onClick="myTotal()">
<input type="text" name="total" id="total" size="25">Grand Total</input>
<br>
<span id="runningTotal"></span> <!--runningTotal span-->
</fieldset>
<label for="name">Name: (First, Last)</label>
<input type="text" name="name" id="name" size="25" required></input>
<label for="Address">Address</label>
<input type="text" name="Address" id="address" size="25" required></input>
<label for="email">Email</label>
<input type="email" name="email" id="email" size="40" maxlength="40"></input>
<br><br>
<label for="checkbox">Sign me up for deals via email</label>
<input type="checkbox" name="checkbox" id="checkbox" value="Signup" checked="checked"></input>
<input type="submit" method="post" value="Submit" class="button"/>
<input type="reset" value="Reset" class="button"/>
</form>
</div>
Any help would be awesome! Please address any confusion please. I want to be as clear as possible to try to get the best help for me and others here on SO. I also hope my question isn't off topic. Like I said, I tried to find something pertaining to this here on SO. Thank you so much!
Do you mean something like this? (jsfiddle here)
function myTotal()
{
// Error checking removed....
// Calculate cost of current item
var itemSelect = document.getElementById("foodItems");
var mealCost = parseFloat(itemSelect.value);
var howMany = parseInt(document.getElementById("itemTotal").value);
var thisItemCost = mealCost * howMany;
var shippingCost = 3.5;
// Get running total from the "total" text box
var runTotal = parseFloat(document.getElementById("total").value);
// Only add shipping cost once
if (isNaN(runTotal) || 0 == runTotal) runTotal = shippingCost;
// Add this item to total and update "total" text box
document.getElementById("total").value = (thisItemCost + runTotal).toFixed(2);
// Add item to span
document.getElementById("runningTotal").innerHTML += "</br>" +
itemSelect.options[itemSelect.selectedIndex].innerHTML +
" x " + howMany +
" .... $" + thisItemCost.toFixed(2);
}

Custom Credit Card number lengths

I'm working on a pizza website for school.
Here's the question I need to answer.
*Allow users to choose from three types of credit card: Visa, MasterCard and American  Express. Based on the type of credit card, limit the length of the credit card number, 16  digits for Visa and MasterCard, 15 digits for American Express. 
*
Currently, the page is setup so the user chooses whether he or she wants to pay when picking up the pizza or pay online using a credit card.
When online radiobox is checked, more radioboxes with credit card names appear.
html codes
<p> Payment Method</p>
<input id="paypickup" type="radio" name="rbRating"
value="Pick Up" checked />Pay on pickup
<input id="online" type="radio" name="rbRating"
value="online" />Online
<div id="hidden2" class="textinput">
<input id="visa" type="radio" name="cardtype"
value="Visa" onclick="showMe('visanum')"/>Visa
<input id="mastercard" type="radio" name="cardtype"
value="MasterCard" onclick="showMe('masternum')"/>MasterCard
<input id="americanexpress" type="radio" name="cardtype"
value="American Express" onclick="showMe('americaninfo')"/>American Express
</div>
<div id="visainfo">
<label for="visanum">Credit Card Number</label>
<input id="visanum" type="text" name="cardnum" maxlength="16" />
</div>
<div id="masterinfo">
<label for="masternum">Credit Card Number</label>
<input id="masternum" type="text" name="cardnum" maxlength="16" />
</div>
<div id="americaninfo">
<label for="americannum">Credit Card Number</label>
<input id="americannum" type="text" name="cardnum" maxlength="15" />
</div>
<button type="submit" value="Submit">Submit</button>
<button type="reset" value="Reset">Reset</button>
JS code for hiding the credit card radio box until delivery is checked
$(document).ready(function() {
$('input[type="radio"]').click(function() {
if($(this).attr('id') == 'paypickup') {
$('#hidden2').hide();
}
if($(this).attr('id') == 'online') {
$('#hidden2').show();
}
});
});
As you can see in the html codes, I tried to attempt this by creating multiple textboxes with maxlength. But I immediately realised this is inefficient and confusing.
I'm very new to these kind of stuff.
Create one input box for credit card number,initially disable the input box and on selection of the radio button for credit card enable the input box. HEre is change for both HTML and JS
HTML
<div>
Credit Card Number
<input id="creditCardNumber" type="text" name="cardnum" disabled/>
</div>
JS
function showMe(type) {
// clear previous value
$("#creditCardNumber").val('');
// enable the input and accept 16 digits for amex
if (type == "americaninfo") {
$("#creditCardNumber").attr({
maxlength: 16,
disabled: false
});
} else {
$("#creditCardNumber").attr({
maxlength: 15,
disabled: false
})
}
}
DEMO
If I were you, I wouldn't use all of those input:text. Instead, I'd use the data attribute to store all of the necessary data in it.
For example:
<input type="radio" name="cardtype" value="visa" data-maxLength="16"/>Visa
That way, you don't have to worry about hiding and showing several different boxes. Then, when the user clicks a new radio buttion, then you just have to set the maxlength attribute in the cardnumber input to the value of the data-attr
DEMO: https://jsbin.com/nufamixisi/edit?html,js,output
// Hide input
$(".cardInput").hide();
// User clicks on radio button so we need to show the input for card info
$('input:radio[name=cardtype]').click(function() {
// Show the input for card and delete old value
$("input:text[name=cardnum]").val("");
$(".cardInput").show();
// Get the maxLength set in the selected radio button
var ml = $(this).attr("data-maxLength");
$("input:text[name=cardnum]").attr("maxlength", ml);
});
I didn't throw logic in there to show/hide the card stuff based on cardpickup, etc. I think you can get that one ;)

jQuery to Validate an Input Text Control based on Radio Selection

How do I validate that the input text corresponding to the radio option is checked?
For example, using the image above:
If Contact 1's E-Mail radio option is selected, Contact 1's E-Mail text field cannot be blank, but Contact 1's Phone and US Mail text fields are still permitted.
If Contact 2's US Mail radio option is selected, Contact 2's US Mail text field cannot be blank, but Contact 2's Phone and E-Mail text fields are still permitted.
I have built the form above using the HTML below, but you can play with my Fiddle here: fiddle.
BEGIN UPDATE: I have a newer fiddle with better code here:
fiddle2
It has more instructions in the HTML and a closer attempt at my jQuery. For some reason, though, it still does not seem to be doing anything.
END UPDATE
I have tried naming the fields so that my jQuery can parse them, but that does not mean there is not a better way.
<body>
<form name="jp2code" action="#" method="POST">
<fieldset>
<legend>Contact 1</legend>
<span>
<input type="radio" id="group1_PhoneRadio" name="group1"/>
<label for="group1_PhoneText">Phone:</label>
<input type="text" id="group1_PhoneText" name="group1_PhoneText"/>
<br/>
<input type="radio" id="group1_EMailRadio" name="group1"/>
<label for="group1_EMailText">E-Mail:</label>
<input type="text" id="group1_EMailText" name="group1_EMailText"/>
<br/>
<input type="radio" id="group1_USMailRadio" name="group1"/>
<label for="group1_USMailText">US Mail:</label>
<input type="text" id="group1_USMailText" name="group1_USMailText"/>
</span>
</fieldset>
<fieldset>
<legend>Contact 2</legend>
<span>
<input type="radio" id="group2_PhoneRadio" name="group2"/>
<label for="group2_PhoneText">Phone:</label>
<input type="text" id="group2_PhoneText" name="group2_PhoneText"/>
<br/>
<input type="radio" id="group2_EMailRadio" name="group2"/>
<label for="group2_EMailText">E-Mail:</label>
<input type="text" id="group2_EMailText" name="group2_EMaiText"/>
<br/>
<input type="radio" id="group2_USMailRadio" name="group2"/>
<label for="group2_USMailText">US Mail:</label>
<input type="text" id="group2_USMailText" name="group2_USMailText"/>
</span>
</fieldset>
<div>
<input type="submit" name="submit" value="submit" />
</div>
</form>
</body>
What is the best way to write the jQuery?
I am new to jQuery, but I attempted my hand at it based on some Show/hide examples.
What I created below does not work, but hopefully indicates what I am trying to accomplish.
$(function() {
$("input[type='radio']").change(function() { // when a radio button in the group changes
var id = $(this).id;
var index = id.indexOf('group');
if (index == 0) { // is there a better way to do this?
var groupN_Len = 7; // Length of 'groupN_'
var radio_Len = 5; // Length of 'radio'
var preStr = id.substring(0, groupN_Len);
$"input[name*='preStr']".validate = null; // clear validation for all text inputs in the group
var postStr = id.substring(groupN_Len + 1, id.Length() + 1 - radio_Len); // extract Phone, EMail, or USMail
$(preStr+postStr+'Text').validate({ rules: { name: { required: true } } });
}
});
});
To make sure that the radiobutton is checked for each field, add attribute required="" in one of the radiobuttons for each fieldset.
demo
OK, whatever radio button is selected in the Contact Group's Contact Preferences, that corresponding text field is required.
Here is where I am so far on my jQuery checking:
EDIT:
Modified with tilda's important detail about adding '.' to the class name.
Added Required Attribute: how to dynamically add REQUIRED attribute to textarea tag using jquery?
Removed Required Attribute: jquery removing html5 required attribute
Final code works and looks like this:
<script type="text/javascript" src="http://ajax.aspnetcdn.com/ajax/jquery.validate/1.11.1/jquery.validate.js"></script>
<script type="text/javascript">
$(function() {
jQuery.validator.setDefaults({
debug: true,
success: "valid"
});
$("input[type='radio']").change(function() {
$('.'+$(this).attr('name')).each(function(index) {
$(this).removeAttr('required');
});
if($(this).is(':checked')) {
$('.'+$(this).attr('id')).each(function(index) {
$(this).prop('required',true);
});
}
});
$('#submit').click(function() {
$(this).validate();
});
});
Back to the HTML of the document: I did a lot of subtle editing to the text by creating specific ids and names for the radio buttons that matched up with the class names for the text controls.
Here is that end result:
<body>
<form name="jp2code" action="#" method="POST">
<div>For each field below, provide the Phone Number, E-Mail Address, and Street Address. <b>Indicate the preferred contact method using the radio button.</b></div>
<fieldset>
<legend>Contact 1</legend>
<span>
<input type="radio" id="group1_Phone" name="group1"/>
<label for="group1_Phone">Phone:</label>
<input type="text" name="group1_PhoneText" class="group1 group1_Phone" />
<br/>
<input type="radio" id="group1_EMail" name="group1"/>
<label for="group1_EMail">E-Mail:</label>
<input type="text" name="group1_EMailText" class="group1 group1_EMail" />
<br/>
<input type="radio" id="group1_USMail" name="group1"/>
<label for="group1_USMail">US Mail:</label>
<input type="text" name="group1_USMailText" class="group1 group1_USMail" />
</span>
</fieldset>
<fieldset>
<legend>Contact 2</legend>
<span>
<input type="radio" id="group2_Phone" name="group2"/>
<label for="group2_Phone">Phone:</label>
<input type="text" name="group2_PhoneText" class="group2 group2_Phone" />
<br/>
<input type="radio" id="group2_EMail" name="group2"/>
<label for="group2_EMail">E-Mail:</label>
<input type="text" name="group2_EMailText" class="group2 group2_EMail" />
<br/>
<input type="radio" id="group2_USMail" name="group2"/>
<label for="group2_USMail">US Mail:</label>
<input type="text" name="group2_USMailText" class="group2 group2_USMail" />
</span>
</fieldset>
<div>
<input type="submit" value="Send" id="submit"/>
</div>
</form>
</body>
Let me explain what is going on in the jQuery, using the HTML above:
When a radio button's checked state changes, each control with a class name that matches the radio button's name attribute has the required property removed.
If a radio button is checked (i.e. checked=true), then each control with a class name that matches the radio button's id attribute has the required property added.
Finally, the validator seems to have to be run on a single form control (not on individual text controls like I was doing).
Here is the sample Fiddle that I ended with: Fiddle v8
At tilda: You didn't say much, but what you did say helped a lot!

Categories