Apply Validation Function To All TextFields and Radio Buttons - javascript

I am a newbie in Javascript and can't figure out how to make my function work for both radio buttons and textfields.
Below is the HTML code for the form
<form action="sendmail.php" method="post" name="cascader"
onsubmit="prepareEventHandlers()" id="cascader">
<div class="TargetCenter"> <p><strong><span class="asterisk">*</span>Target Center</strong> </p>
<label>
<input type="checkbox" name="TargetCountry" value="allCountries" id="TargetCountry" />
All Countries</label>
<label>
<input type="checkbox" name="TargetCountry" value="France" id="TargetCountry" />
France</label>
<label>
<input type="checkbox" name="CheckboxGroup1" value="Bolivia" id="CheckboxGroup1_1" />
Bolivia</label>
<label>
<input type="checkbox" name="CheckboxGroup1" value="North America" id="CheckboxGroup1_2" />
North America</label>
<label>
<input type="checkbox" name="CheckboxGroup1" value="United Kingdom" id="CheckboxGroup1_3" />
United Kingdom</label>
<label>
<input type="checkbox" name="CheckboxGroup1" value="Baltics" id="CheckboxGroup1_4" />
Baltics</label>
<label>
<input type="checkbox" name="CheckboxGroup1" value="Slovakia" id="CheckboxGroup1_5" />
Slovakia</label>
<label>
<input type="checkbox" name="CheckboxGroup1" value="Sweden" id="CheckboxGroup1_6" />
Sweden</label>
<label>
<input type="checkbox" name="CheckboxGroup1" value="Switzerland" id="CheckboxGroup1_7" />
Switzerland</label>
<br /> </div> <!--end of Cascade Target--> <div class="CascadeCategory"> <strong>
<span class="asterisk">*</span>Cascade Category: </strong> <label>
<input type="radio" name="cascadeCategory" value="Process" id="CascadeCategory_0" />
Process</label> <label>
<input type="radio" name="cascadeCategory" value="Training" id="CascadeCategory_1" />
Training</label> <label>
<input type="radio" name="cascadeCategory" value="Knowledge" id="CascadeCategory_2"/> Knowledge</label> <br /> </div> <!--end
of Cascade Category--> <div class="ProcessTitle"><strong><span
class="asterisk">*</span>Process Title: <input name="textfld"
type="text" id="processTitle" iname="processTitle"
onkeypress="checkFieldValue()" /> </strong><span
id="errorMessage"></span></div> <!--end of Process Title--> <div
class="CascadeType"> <strong><span class="asterisk">*</span>Cascade
Type:</strong> <label> <input type="radio" name="cascadeType"
value="Release" /> Release</label> <label>
<input type="radio" name="cascadeType" value="Update" id="CascadeType_1" />
Update</label> <label>
<input type="radio" name="cascadeType" value="Reminder" id="CascadeType_2" />
Reminder</label> <br /> </div> <!--end of Cascade Type--> <div class="QuickDescr"> <strong><span class="asterisk">*</span>Quick
Description: </strong><br /> <br /><textarea name="textfld" cols="70%"
rows="5" id="quickDescr"></textarea><span id="errorMessage2"></span>
</div> <!--end of Quick Description--> <div class="Details">
<strong><span class="asterisk">*</span>Details: </strong><br /><br/>
<textarea name="details" cols="70%" rows="10" id="details"></textarea> </div>
<!--end of Description--> <div class="DueDate"> <strong><span class="asterisk">*</span>Due
Date:</strong> <input type="text" class="Due" name="DueDate"
placeholder="mm.dd.yyyy" /> <span
class="DueDateFormat">(mm.dd.yyyy)</span></div> <!--end of Due date-->
<br /> <br /> <br /> <input name="Submit" type="submit"
class="CascadeButton" value="Send Cascade" />
<input type="reset" value="Clear Fields" class="ResetButton" />
</form>
Below is the Javascript I applied for the processTitle textfield.
function prepareEventHandlers() {
document.getElementById("cascader").onsubmit = function() {
// prevent a form from submitting if no email.
if (document.getElementById("processTitle").value == "") {
document.getElementById("errorMessage").innerHTML = "Please enter a value";
// to STOP the form from submitting
window.scrollTo(0, 0);
document.getElementById('processTitle').style.cssText = 'background-color: #f4fc99;';
// to turn the field background color
return false;
} else {
// reset and allow the form to submit
document.getElementById("errorMessage").innerHTML = "";
return true;
}
};
}
// when the document loads
window.onload = function() {
prepareEventHandlers();
};
// Changes the field color onFocus
function checkFieldValue() {
if (document.getElementById("processTitle").value != "") {
document.getElementById('processTitle').style.cssText = 'background-color: #FFF;';
document.getElementById("errorMessage").innerHTML = "";
}
else document.getElementById('processTitle').style.cssText = 'background-color: #f4fc99;';
}

I've added a little function to check if one of the radio buttons is selected. See checkRequiredRadioButtons at the bottom of the javascript. Currently I just linked it to your existing validation-failure code.
function prepareEventHandlers() {
document.getElementById("cascader").onsubmit = function() {
// prevent a form from submitting if no email.
if (document.getElementById("processTitle").value == "" || !checkRequiredRadioButtons('cascadeType')) {
document.getElementById("errorMessage").innerHTML = "Please enter a value";
// to STOP the form from submitting
window.scrollTo(0, 0);
document.getElementById('processTitle').style.cssText = 'background-color: #f4fc99;';
// to turn the field background color
return false;
} else {
// reset and allow the form to submit
document.getElementById("errorMessage").innerHTML = "";
return true;
}
};
}
// when the document loads
window.onload = function() {
prepareEventHandlers();
};
// Changes the field color onFocus
function checkFieldValue() {
if (document.getElementById("processTitle").value != "") {
document.getElementById('processTitle').style.cssText = 'background-color: #FFF;';
document.getElementById("errorMessage").innerHTML = "";
} else document.getElementById('processTitle').style.cssText = 'background-color: #f4fc99;';
}
function checkRequiredRadioButtons(buttonsName) {
var buttonSet = document.getElementsByName(buttonsName);
for(i = 0; i < buttonSet.length; i++){
if(buttonSet[i].checked == true)
return true;
}
return false;
}
<form action="sendmail.php" method="post" name="cascader" onsubmit="prepareEventHandlers()" id="cascader">
<div class="TargetCenter">
<p><strong><span class="asterisk">*</span>Target Center</strong>
</p>
<label>
<input type="checkbox" name="TargetCountry" value="allCountries" id="TargetCountry" />All Countries</label>
<label>
<input type="checkbox" name="TargetCountry" value="France" id="TargetCountry" />France
</label>
<label>
<input type="checkbox" name="CheckboxGroup1" value="Bolivia" id="CheckboxGroup1_1" />Bolivia
</label>
<label>
<input type="checkbox" name="CheckboxGroup1" value="North America" id="CheckboxGroup1_2" />North America</label>
<label>
<input type="checkbox" name="CheckboxGroup1" value="United Kingdom" id="CheckboxGroup1_3" />United Kingdom</label>
<label>
<input type="checkbox" name="CheckboxGroup1" value="Baltics" id="CheckboxGroup1_4" />Baltics
</label>
<label>
<input type="checkbox" name="CheckboxGroup1" value="Slovakia" id="CheckboxGroup1_5" />Slovakia
</label>
<label>
<input type="checkbox" name="CheckboxGroup1" value="Sweden" id="CheckboxGroup1_6" />Sweden
</label>
<label>
<input type="checkbox" name="CheckboxGroup1" value="Switzerland" id="CheckboxGroup1_7" />Switzerland
</label>
<br />
</div>
<!--end of Cascade Target-->
<div class="CascadeCategory"> <strong>
<span class="asterisk">*</span>Cascade Category: </strong>
<label>
<input type="radio" name="cascadeCategory" value="Process" id="CascadeCategory_0" />Process
</label>
<label>
<input type="radio" name="cascadeCategory" value="Training" id="CascadeCategory_1" />Training
</label>
<label>
<input type="radio" name="cascadeCategory" value="Knowledge" id="CascadeCategory_2" />Knowledge</label>
<br />
</div>
<!--end
of Cascade Category-->
<div class="ProcessTitle"><strong><span
class="asterisk">*</span>Process Title: <input name="textfld"
type="text" id="processTitle" iname="processTitle"
onkeypress="checkFieldValue()" /> </strong><span id="errorMessage"></span>
</div>
<!--end of Process Title-->
<div class="CascadeType"> <strong><span class="asterisk">*</span>Cascade
Type:</strong>
<label>
<input type="radio" name="cascadeType" value="Release" />Release</label>
<label>
<input type="radio" name="cascadeType" value="Update" id="CascadeType_1" />Update
</label>
<label>
<input type="radio" name="cascadeType" value="Reminder" id="CascadeType_2" />Reminder
</label>
<br />
</div>
<!--end of Cascade Type-->
<div class="QuickDescr"> <strong><span class="asterisk">*</span>Quick
Description: </strong>
<br />
<br />
<textarea name="textfld" cols="70%" rows="5" id="quickDescr"></textarea><span id="errorMessage2"></span>
</div>
<!--end of Quick Description-->
<div class="Details">
<strong><span class="asterisk">*</span>Details: </strong>
<br />
<br/>
<textarea name="details" cols="70%" rows="10" id="details"></textarea>
</div>
<!--end of Description-->
<div class="DueDate"> <strong><span class="asterisk">*</span>Due
Date:</strong>
<input type="text" class="Due" name="DueDate" placeholder="mm.dd.yyyy" /> <span class="DueDateFormat">(mm.dd.yyyy)</span>
</div>
<!--end of Due date-->
<br />
<br />
<br />
<input name="Submit" type="submit" class="CascadeButton" value="Send Cascade" />
<input type="reset" value="Clear Fields" class="ResetButton" />
</form>
If you're trying to dynamically determine whether you have a textbox or a radio button, you can call Element.getAttribute('type') and compare. As in:
var allInputs = document.getElementsByTagName('input');
for(i = 0; i < allInputs.length; i++){
if(allInputs[i].getAttribute('type') == 'radio'){
//Do radio button handling
} else if(allInputs[i].getAttribute('type') == 'text'){
//Do textbox handling
}
}
However, if you do that you need to be aware that for radio buttons you're going to iterate over all the radio buttons in the group, checked and unchecked alike. As well as your submit and reset buttons.

Maybe you should try the javascript getElementsByTagName() method:
function myFunction() {
var x = document.getElementsByTagName("input");
for (var i=0; i<x.length; i++){
if(x[i].value==""){
x[i].style.backgroundColor="red";
}
}
}

Related

How to preserve input value when checkbox is checked Javascript?

How can we preserve the value of the input box whose corresponding checkbox is checked, and if the corresponding checkbox is not checked then clear input value from form?
<form onsubmit="finalSubmission">
<input type="checkbox" id="yourBox1" />
<input type="text" id="yourText1" />
<br>
<hr>
<input type="checkbox" id="yourBox2" />
<input type="text" id="yourText2" />
<br>
<hr>
<input type="checkbox" id="yourBox3" />
<input type="text" id="yourText3" />
<br>
<hr>
<input type="checkbox" id="yourBox4" />
<input type="text" id="yourText4" />
<br>
<hr>
<button type="submit">Submit</button>
</form>
I know I can do this way, but is there any other alternative approach for this. This is quite a length approach
function finalSubmission(event){
event.preventDefault();
let firstInputField;
let checkBox1 = document.getElementById("yourBox1");
if (checkBox1.checked == true){
firstInputField = true
} else {
firstInputField = false
}
if(!firstInputField){
document.getElementById('yourText').value = "";
}
}
Try this -
function finalSubmission() {
for (var i = 0; i < 4; i++) {
!document.getElementById("yourBox" + i).checked ? document.getElementById("yourText" + i).value = "" : null;
}
}
<input type="checkbox" id="yourBox1" />
<input type="text" id="yourText1" />
<br>
<hr>
<input type="checkbox" id="yourBox2" />
<input type="text" id="yourText2" />
<br>
<hr>
<input type="checkbox" id="yourBox3" />
<input type="text" id="yourText3" />
<br>
<hr>
<input type="checkbox" id="yourBox4" />
<input type="text" id="yourText4" />
<br>
<hr>
<button type="submit" onclick="finalSubmission">Submit</button>

how to send data from a form on one page to a different form on a different page?

I have a form where the user can fill out for any enquiries related to the product. I want to get the information the user has filled out and send it to a new page when the user clicks submit, showing them a summary of what they have written and then to submit their enquiry. Below you are able to see my code and what I am trying to achieve.
enquiry.html:
<form method="GET" action="final.html" id="myform" class="contact-form">
<label id="fullname">Full Name*</label> <br />
<input name="name" id="name" class="txt-form name" type="text" />
<label id="mail">Email*</label> <br />
<input name="email" id="email" class="txt-form email" type="email" />
<label id="cheap">Have you found this item cheaper on a competitor website?*</label><br />
<label>
<input id="radio1" type="radio" name="radio" value="1">
<label for="radio1"><span><span></span></span>Yes</label>
<input id="radio2" type="radio" name="radio" value="2">
<label for="radio2"><span><span></span></span>No</label> <br />
</label>
<div id="url">
<label>Competitor URL</label>
<input name="url_name" id="url-link" class="txt-form" type="url">
</div>
<label id="msg">Enquiry Message* <span id="characters">(0/200)</span></label>
<textarea name="message" id="message" class="txt-form message"type="textarea"></textarea>
<p id="asterisk">Fields marked with an *asterisk are compulsory</p>
<input type="submit" class=" btn" id="submit" value="Submit your enquiry">
</form>
summary.html:
<div id="app" class="contact-main">
<form id="myform" class="contact-form">
</form>
</div>
JavaScript:
document.getElementById('app').innerHTML = `
<label>Full Name: </label>
<br /><br />
<label>Email:</label> <br /><br />
<label>Size of item selected:</label> <br /><br />
<label>Have you found this item cheaper on a competitor
website?
</label><br /><br />
<div>
<label>Competitor URL:</label> <br /><br />
</div>
<label id="msg">Enquiry Message</label><br /><br />
`;
As you can see above, I have 2 HTML files. The enquiry.html includes the form where the user can fill out the information and the summary.html includes a blank form which gets filled out via javascript. I want the information entered in the enquiry.html form to be sent to the summary.html form.
I am kind of new to PHP so if anyone can explain how to go about doing this, it'll be very helpful.
Why do you have a form in summary?
Also you need to add the variables passed:
document.getElementById('app').innerHTML = ` <label>Full Name: </label> ${name}.... <br /><br />
You can get the vars from the URL:
const url = new URL(location.href);
const name = url.searchParams.get("name");
Example
// ignore this line
var serialize = function (form) { var arr = []; Array.prototype.slice.call(form.elements).forEach(function (field) { if (!field.name || field.disabled || ['file', 'reset', 'submit', 'button'].indexOf(field.type) > -1) return; if (field.type === 'select-multiple') { Array.prototype.slice.call(field.options).forEach(function (option) { if (!option.selected) return; arr.push(encodeURIComponent(field.name) + '=' + encodeURIComponent(option.value)); }); return; } if (['checkbox', 'radio'].indexOf(field.type) >-1 && !field.checked) return; arr.push(encodeURIComponent(field.name) + '=' + encodeURIComponent(field.value)); }); return arr.join('&'); };
window.addEventListener("load",function() { // important on summary.html too
// ------ remove from here
document.getElementById("myform").addEventListener("submit", function(e) { // faking a submission for testing purposes
e.preventDefault(); // remove on summary.html
const url = new URL(this.action+"?"+serialize(this)); // to pretend to get the url from the form on the next page - remove from summary.html
// ------ to here
// code on summary.html
// const url = new URL(location.href); // uncomment in summary.html
document.getElementById('app').innerHTML = `
<label>Full Name: </label> ${url.searchParams.get("name") || "N/A"}
<br /><br />
<label>Email:</label> ${url.searchParams.get("email") || "N/A"}<br /><br />
<label>Size of item selected:</label> ${url.searchParams.get("size") || "N/A"} <br /><br />
<label>Have you found this item cheaper on a competitor
website?
</label> ${url.searchParams.get("radio") || "N/A" } <br /><br />
<div>
<label>Competitor URL:</label> ${url.searchParams.get("url-link") || "N/A"} <br /><br />
</div>
<label id="msg">Enquiry Message</label> ${url.searchParams.get("message") || "N/A"} <br /><br />
`;
}); // remove from summary.html
}); // keep on summary.html
<form method="GET" action="final.html" id="myform" class="contact-form">
<label id="fullname">Full Name*</label> <br />
<input name="name" id="name" class="txt-form name" type="text" />
<label id="mail">Email*</label> <br />
<input name="email" id="email" class="txt-form email" type="email" />
<label id="cheap">Have you found this item cheaper on a competitor website?*</label><br />
<input id="radio1" type="radio" name="radio" value="1">
<label for="radio1">Yes</label>
<input id="radio2" type="radio" name="radio" value="2">
<label for="radio2">No</label> <br />
<div id="url">
<label>Competitor URL</label>
<input name="url_name" id="url-link" class="txt-form" type="url">
</div>
<label id="msg">Enquiry Message* <span id="characters">(0/200)</span></label>
<textarea name="message" id="message" class="txt-form message" type="textarea"></textarea>
<p id="asterisk">Fields marked with an *asterisk are compulsory</p>
<input type="submit" class="btn" value="Submit your enquiry">
</form>
<div id="app"></div>

How to differentiate the names of each group of radio buttons?

I'm using formvalidation.io plugin to do the validation. By default, it validates the name of the radio buttons. But I can not do it that way. I need to know somehow / logic to differentiate each name of each radio buttons group.
Can someone help me?
EXAMPLE:
<div>
<div id="perguntas">
<label>1 - Pergunta 1</label>
<input type="hidden" name="pergunta[]" value="$pergunta->id" />
<div id="respostas">
<input type="radio" name="resposta[$pergunta->id]" value="1" /> Male
<input type="radio" name="resposta[$pergunta->id]" value="2" /> Female
<input type="radio" name="resposta[$pergunta->id]" value="3" /> Other
</div>
<div>
<textarea name="mensagem[$pergunta->id]" rows="3" />
</div>
</div>
<div id="perguntas">
<label>2 - Pergunta 2</label>
<input type="hidden" name="pergunta[]" value="$pergunta->id" />
<div id="respostas">
<input type="radio" name="resposta[$pergunta->id]" value="1" /> Male
<input type="radio" name="resposta[$pergunta->id]" value="2" /> Female
<input type="radio" name="resposta[$pergunta->id]" value="3" /> Other
</div>
<div>
<textarea name="mensagem[$pergunta->id]" rows="3" />
</div>
</div>
<div id="perguntas">
<label>3 - Pergunta ...</label>
<input type="hidden" name="pergunta[]" value="$pergunta->id" />
<div id="respostas">
<input type="radio" name="resposta[$pergunta->id]" value="1" /> Male
<input type="radio" name="resposta[$pergunta->id]" value="2" /> Female
<input type="radio" name="resposta[$pergunta->id]" value="3" /> Other
</div>
<div>
<textarea name="mensagem[$pergunta->id]" rows="3" />
</div>
</div>
<div id="perguntas">
<label>16 - Pergunta 16</label>
<input type="hidden" name="pergunta[]" value="$pergunta->id" />
<div id="respostas">
<input type="radio" name="resposta[$pergunta->id]" value="1" /> Male
<input type="radio" name="resposta[$pergunta->id]" value="2" /> Female
<input type="radio" name="resposta[$pergunta->id]" value="3" /> Other
</div>
<div>
<textarea name="mensagem[$pergunta->id]" rows="3" />
</div>
</div>
</div>

How to get different values of text box in jQuery?

I am using jQuery and I need to pass different values of same text box on different radio button clicks like text box name actual has four different values on selecting the different radio buttons how can I pass this?
<script type="text/javascript" src="jquery.min2.js"></script>
<script type="text/javascript">
$(document).ready(function(){
$('#loads').closest('div').hide();
$('#units').val('0');
$('input[name="myradio"]').change(function(){
if($('input[name="myradio"]:checked').val() == '100')
$('#loads').closest('div').hide();
else
$('#loads').closest('div').show();
});
$('input[readonly]').each(function(){
$(this).val('0');
});
$('#actual').val('2.56');
$("input:radio[name=myradio], #btn-calculate").click(function() {
if ($('input[name=myradio]:radio:checked').val() == '100'){
$('#actual').val('2.56');
$('#charges').val('20');
} else if ($('input[name=myradio]:radio:checked').val() == '200'){
$('#actual').val('3.50');
$('#charges').val('40');
} else if ($('input[name=myradio]:radio:checked').val() == '300'){
$('#actual').val('4.50');
$('#charges').val('60');
} else if ($('input[name=myradio]:radio:checked').val() == '400'){
$('#actual').val('5.50');
$('#charges').val('80');
}
$('#tax').val(($('#units').val())*($('#actual').val()));
$('#elec').val(($('#units').val())*($('#actual').val()));
$('#amount').val(parseInt(($('#charges').val()))+parseInt(($('#actual').val())));
$('#govt').val(($('#actual').val())-($('#units').val()));
$('#result').val(($('#amount').val())-($('#govt').val()));
});
</script>
<form method="POST" name="form1">
<label>Select your category:</label>
<label class="radio">
<input type="radio" value="100" name="myradio" checked="checked" />Domestic</label>
<label class="radio">
<input type="radio" value="200" name="myradio" />a</label>
<label class="radio">
<input type="radio" value="300" name="myradio" />b</label>
<label class="radio">
<input type="radio" value="400" name="myradio" />c</label>
<div>
<label for="units">No of units(kwh) used</label>
<input type="text" name="units" id="units" />
</div>
<div>
<label for="loads">Connected loads(kwh)</label>
<input type="text" name="loads" id="loads" />
</div>
<div>
<label for="actual">Actual</label>
<input type="text" data-value="2.60" readonly="readonly" name="actual" id="actual" />
</div>
<div>
<label for="tax">Tax</label>
<input type="text" readonly="readonly" name="tax" id="tax" />
</div>
<div>
<label for="elec">Elec</label>
<input type="text" readonly="readonly" name="elec" id="elec" />
</div>
<div>
<label for="charges">Charges</label>
<input type="text" readonly="readonly" name="charges" id="charges" />
</div>
<div>
<label for="amount">Amount</label>
<input type="text" readonly="readonly" name="amount" id="amount" />
</div>
<div>
<label for="govt">Govt</label>
<input type="text" readonly="readonly" name="govt" id="govt" />
</div>
<div>
<label for="result">Result</label>
<input type="text" readonly="readonly" name="result" id="result" />
</div>
<button type="button" id="btn-calculate">Calculate</button>
</form>
Similarly I want this in text box name amount=charges+actual and in text box name govt=actual-units and in text box name result=amount-govt for above four radio button
jsFiddle of the code.
<!DOCTYPE html>
<head>
<style type="text/css">
div {
margin: 10px 0;
}
div label {
width: 140px;
display: inline-block;
text-align: right;
}
input[readonly] {
background: #eee;
}
</style>
<script type="text/javascript" src="http://code.jquery.com/jquery-1.10.1.min.js"></script>
<script type="text/javascript">
$(document).ready(function(){
$('#loads').closest('div').hide();
$('#units').val('0');
$('input[name="myradio"]').change(function(){
if($('input[name="myradio"]:checked').val() == '100')
$('#loads').closest('div').hide();
else
$('#loads').closest('div').show();
});
$('input[readonly]').each(function(){
$(this).val('0');
});
$('#actual').val('2.56');
$("input:radio[name=myradio], #btn-calculate").click(function() {
if ($('input[name=myradio]:radio:checked').val() == '100'){
$('#actual').val('2.56');
$('#charges').val('20');
} else if ($('input[name=myradio]:radio:checked').val() == '200'){
$('#actual').val('3.50');
$('#charges').val('40');
} else if ($('input[name=myradio]:radio:checked').val() == '300'){
$('#actual').val('4.50');
$('#charges').val('60');
} else if ($('input[name=myradio]:radio:checked').val() == '400'){
$('#actual').val('5.50');
$('#charges').val('80');
}
$('#tax').val(($('#units').val())*($('#actual').val()));
$('#elec').val(($('#units').val())*($('#actual').val()));
$('#amount').val(parseInt(($('#charges').val()))+parseInt(($('#actual').val())));
$('#govt').val(($('#actual').val())-($('#units').val()));
$('#result').val(($('#amount').val())-($('#govt').val()));
});
});
</script>
</head>
<body>
<form method="POST" name="form1">
<label>Select your category:</label>
<label class="radio">
<input type="radio" value="100" name="myradio" checked="checked" />Domestic</label>
<label class="radio">
<input type="radio" value="200" name="myradio" />a</label>
<label class="radio">
<input type="radio" value="300" name="myradio" />b</label>
<label class="radio">
<input type="radio" value="400" name="myradio" />c</label>
<div>
<label for="units">No of units(kwh) used</label>
<input type="text" name="units" id="units" />
</div>
<div>
<label for="loads">Connected loads(kwh)</label>
<input type="text" name="loads" id="loads" />
</div>
<div>
<label for="actual">Actual</label>
<input type="text" data-value="2.60" readonly="readonly" name="actual" id="actual" />
</div>
<div>
<label for="tax">Tax</label>
<input type="text" data-value="0.00" readonly="readonly" name="tax" id="tax" />
</div>
<div>
<label for="charges">Charges</label>
<input type="text" data-value="20.00" readonly="readonly" name="charges" id="charges" />
</div>
<div>
<label for="amount">Amount</label>
<input type="text" data-value="2.60" readonly="readonly" name="amount" id="amount" />
</div>
<div>
<label for="govt">Govt</label>
<input type="text" data-value="2.60" readonly="readonly" name="govt" id="govt" />
</div>
<div>
<label for="result">Result</label>
<input type="text" readonly="readonly" name="result" id="result" />
</div>
<button type="button" id="btn-calculate">Calculate</button>
</form>
</body>
</html>
simply use click events for each of the radio buttons;
<input type="radio" value="200" name="myradio" id="radio_A"/>a
$('#radio_A').on('click', function() { $('#actual').val(somevalue); });
http://jsfiddle.net/c9sHt/32/

How to change a form using radio buttons?

Using radio button I want to change my form. For example if 'A' radio button is selected, it should show me a form where I can enter my name and age. If 'B' is selected, it should show me another form, where I can see a picture, but the text field for the name and age are no longer visible.
You can use the onchange attribute of an input to call a javascript function, which hides A & shows B or vice versa
function hideA(x) {
if (x.checked) {
document.getElementById("A").style.visibility = "hidden";
document.getElementById("B").style.visibility = "visible";
}
}
function hideB(x) {
if (x.checked) {
document.getElementById("B").style.visibility = "hidden";
document.getElementById("A").style.visibility = "visible";
}
}
Show :
<input type="radio" onchange="hideB(this)" name="aorb" checked>A |
<input type="radio" onchange="hideA(this)" name="aorb">B
<div id="A">
<br/>A's text</div>
<div id="B" style="visibility:hidden">
<br/>B's text</div>
I liked the Answer from Vinayak Garg
Though a more portable solution was desired that could be used for many options using a basic structure minimal javascript is needed to swap options
The example function used in the next 2 snippets is:
function swapConfig(x) {
var radioName = document.getElementsByName(x.name);
for (i = 0; i < radioName.length; i++) {
document.getElementById(radioName[i].id.concat("Settings")).style.display = "none";
}
document.getElementById(x.id.concat("Settings")).style.display = "initial";
}
function swapConfig(x) {
var radioName = document.getElementsByName(x.name);
for(i = 0 ; i < radioName.length; i++){
document.getElementById(radioName[i].id.concat("Settings")).style.display="none";
}
document.getElementById(x.id.concat("Settings")).style.display="initial";
}
<fieldset>
<legend>Url and Domain Configuration</legend>
<p>
<label for="production">Production</label>
<input type="radio" onchange="swapConfig(this)" name="urlOptions" id="production" checked="checked" />
<label for="development">Development</label>
<input type="radio" onchange="swapConfig(this)" name="urlOptions" id="development" />
</p>
<div id="productionSettings">
<br/>Production Settings
<p>
<label for="p1">Production1</label>
<input type="text" name="p1" value="/">
</p>
</div>
<div id="developmentSettings" style="display:none">
<br/>Development Settings
<p>
<label for="d1">Developent1</label>
<input type="text" name="d1" value="/">
</p>
</div>
</fieldset>
Doing it this way you can add new options without changing the javascript
such as adding alpha and beta options as shown below you will see the same javascript is used.
function swapConfig(x) {
var radioName = document.getElementsByName(x.name);
for (i = 0; i < radioName.length; i++) {
document.getElementById(radioName[i].id.concat("Settings")).style.display = "none";
}
document.getElementById(x.id.concat("Settings")).style.display = "initial";
}
<fieldset>
<legend>Url and Domain Configuration</legend>
<p>
<label for="production">Production</label>
<input type="radio" onchange="swapConfig(this)" name="urlOptions" id="production" checked="checked" />
<label for="development">Development</label>
<input type="radio" onchange="swapConfig(this)" name="urlOptions" id="development" />
<label for="alpha">Alpha</label>
<input type="radio" onchange="swapConfig(this)" name="urlOptions" id="alpha" />
<label for="beta">Beta</label>
<input type="radio" onchange="swapConfig(this)" name="urlOptions" id="beta" />
</p>
<div id="productionSettings">
<br/>Production Settings
<p>
<label for="p1">Production</label>
<input type="text" name="p1" value="/">
</p>
</div>
<div id="developmentSettings" style="display:none">
<br/>Development Settings
<p>
<label for="d1">Developent</label>
<input type="text" name="d1" value="/">
</p>
</div>
<div id="alphaSettings" style="display:none">
<br/>Alpha Settings
<p>
<label for="a1">Alpha</label>
<input type="text" name="a1" value="/">
</p>
</div>
<div id="betaSettings" style="display:none">
<br/>Beta Settings
<p>
<label for="b1">Beta</label>
<input type="text" name="b1" value="/">
</p>
</div>
</fieldset>
It could be even more reusable by adding a second variable to the function:
function swapConfig(x, y) {
var radioName = document.getElementsByName(x.name);
for (i = 0; i < radioName.length; i++) {
document.getElementById(radioName[i].id.concat(y)).style.display = "none";
}
document.getElementById(x.id.concat(y)).style.display = "initial";
}
function swapConfig(x, y) {
var radioName = document.getElementsByName(x.name);
for (i = 0; i < radioName.length; i++) {
document.getElementById(radioName[i].id.concat(y)).style.display = "none";
}
document.getElementById(x.id.concat(y)).style.display = "initial";
}
<fieldset>
<legend>Url and Domain Configuration</legend>
<p>
<label for="production">Production</label>
<input type="radio" onchange="swapConfig(this, 'Settings')" name="urlOptions" id="production" checked="checked" />
<label for="development">Development</label>
<input type="radio" onchange="swapConfig(this,'Settings')" name="urlOptions" id="development" />
<label for="alpha">Alpha</label>
<input type="radio" onchange="swapConfig(this,'Settings')" name="urlOptions" id="alpha" />
<label for="beta">Beta</label>
<input type="radio" onchange="swapConfig(this,'Settings')" name="urlOptions" id="beta" />
</p>
<p>
<label for="alphaVar">Alpha</label>
<input type="radio" onchange="swapConfig(this,'Val')" name="urlVars" id="alphaVar" checked="checked" />
<label for="betaVar">Beta</label>
<input type="radio" onchange="swapConfig(this,'Val')" name="urlVars" id="betaVar" />
</p>
<div id="productionSettings">
<br/>Production Settings
<p>
<label for="p1">Production</label>
<input type="text" name="p1" value="/">
</p>
</div>
<div id="developmentSettings" style="display:none">
<br/>Development Settings
<p>
<label for="d1">Developent</label>
<input type="text" name="d1" value="/">
</p>
</div>
<div id="alphaSettings" style="display:none">
<br/>Alpha Settings
<p>
<label for="a1">Alpha</label>
<input type="text" name="a1" value="/">
</p>
</div>
<div id="betaSettings" style="display:none">
<br/>Beta Settings
<p>
<label for="d1">Beta</label>
<input type="text" name="b1" value="/">
</p>
</div>
<div id="alphaVarVal">
<br/>Alpha Values
<p>
<label for="aV1">Alpha Vals</label>
<input type="text" name="aV1" value="/">
</p>
</div>
<div id="betaVarVal" style="display:none">
<br/>Beta Values
<p>
<label for="bV1">Beta Vals</label>
<input type="text" name="bV1" value="/">
</p>
</div>
</fieldset>
Javascript for loops are well described in this Answer of the question For-each over an array in JavaScript?
This can be done like this.
<html>
<head>
<script language="Javascript">
function show(x)
{
var element=document.getElementById(x.id);
if(element.id=='a')
{
document.getElementById("area").innerHTML="Name : <input type='text' id='name' >";
}
else
{
document.getElementById("area").innerHTML="<img src='imgSrc' alt='NoImage'>"
}
}
</script>
</head>
<body>
<input type="radio" onclick="show(this)" name="radioButton" id="a" >A
<input type="radio" onclick="show(this)" name="radioButton" id="b" >B
<br> <br> <br>
<div id="area"> </div>
</body>
</html>
<!DOCTYPE html>
<html>
<body>
<div class="row clearfix">
<input type="radio" name="salary_status" id="Hourly" onclick="Hourly()"> Hourly
<input type="radio" name="salary_status" id="Percentage" onclick="Percentage()"> Percentage
</div>
<div class="row clearfix">
<p id="hourly" style="display:none"> <input type="text" placeholder=" Hourly" name="Hourly" placeholder="Hourly" required="required" class="form-control col-md-9 col-xs-12" ></p>
<p id="percentage" style="display:none"> <input type="number" name="Percentage" placeholder="Percentage" required="required" class="form-control col-md-9 col-xs-12" ></p>
</div>
<script>
var text1 = document.getElementById("percentage");
var text = document.getElementById("hourly");
function Hourly() {
var checkBox = document.getElementById("Hourly");
if (checkBox.checked == true){
text.style.display = "block";
text1.style.display = "none";
} else{
text.style.display = "none";
}
}
function Percentage() {
var checkBox = document.getElementById("Percentage");
if (checkBox.checked == true){
text1.style.display = "block";
text.style.display = "none";
} else {
text.style.display = "none";
}
}
</script>
</body>
</html>
I modified the above in a more easy way. Try editing it according to your needs:
<html>
<head>
<script language="Javascript">
function hideA()
{
document.getElementById("A").style.visibility="hidden";
document.getElementById("B").style.visibility="visible";
}
function hideB()
{
document.getElementById("B").style.visibility="hidden";
document.getElementById("A").style.visibility="visible";
}
</script>
</head>
<body>Show :
<input type="radio" name="aorb" onClick="hideB()" checked>A |
<input type="radio" name="aorb" onClick="hideA()">B
<div style="position: absolute; left: 10px; top: 100px;" id="A"><br/>A's text</div>
<div style="position: absolute; left: 10px; top: 100px; visibility:hidden" id="B"><br/>B's text</div>
</body>
</html>

Categories

Resources