validate inputs than close the div once filled out - javascript

I am really new to HTML,JavaScript and was just wondering how I would check to see if the input fields inside my fieldset were completed by the user, if so the fieldset collapses into its legend. Below I have created the script to collapse the fieldset into the legend, I just need to create the validation script but I don't know how to create it.
function doit2() {
if (document.getElementById('two').style.display == 'none') {
document.getElementById('two').style.display = 'block';
} else {
document.getElementById('two').style.display = 'none';
}
}
<fieldset>
<legend>Personal details</legend>
<div id="two">
<div>
<label>Surname or family name:</label>
<input type="text" name="personal" />
</div>
<div>
<label>Given name/names:</label>
<input type="text" name="personal" />
</div>
<div>
<label> Date of birth:</label>
<input type="date" name="personal" />
</div>
<div>
<label> Male </label>
<input type="radio" name="gender" value="Male" />
</div>
<div>
<label> Female </label>
<input type="radio" name="gender" value="Female" />
</div>
<div>
<label> N/A </label>
<input type="radio" name="gender" value="NA" />
</div>
</div>
</fieldset>

Try this:
function validateForm()
{
debugger;
var fields = ["surname", "name", "dob"]
var i, l = fields.length;
var fieldname;
for (i = 0; i < l; i++) {
fieldname = fields[i];
if (document.getElementsByName(fieldname)[0].value === "") {
alert(fieldname + " can not be empty");
return false;
}
}
return true;
}
function doit2() {
if(document.getElementById('two').style.display == 'none'){
document.getElementById('two').style.display = 'block';
} else {
if(validateForm()){
document.getElementById('two').style.display = 'none';
}
}
}
<fieldset id="fieldset">
<legend>Personal details</legend>
<div id="two">
<div>
<label>Surname or family name:</label>
<input type="text" name="surname"/>
</div>
<div>
<label>Given name/names:</label>
<input type="text" name="name"/>
</div>
<div>
<label> Date of birth:</label>
<input type="date" name="dob"/>
</div>
<div>
<label> Male </label>
<input type="radio" name="gender" value="Male" checked/>
</div>
<div>
<label> Female </label>
<input type="radio" name="gender" value="Female"/>
</div>
<div>
<label> N/A </label>
<input type="radio" name="gender" value="NA"/>
</div>
</div>
</fieldset>

The first step in validation you need to add to each input required inside input tag. Than if you fine with default validation you can leave it as is, other wise you can use regex. If yu decide to use any of the frameworks - bootstrap, angular - they have their own validators as well

You can use document.getElementById("[id of element]").value or document.getElementsByName("[Name of element]").value to get value of your inputs and validate them.for your case you can use document.getElementsByName Like this:
function validate() {
if (document.getElementsByName('personal')[0].value.length == 0) {
//set error
alert('error');
return false;
}
//Add other validation here
return true;
}
//....
function doit2() {
if (validate()) {
if (document.getElementById('two').style.display == 'none') {
document.getElementById('two').style.display = 'block';
} else {
document.getElementById('two').style.display = 'none';
}
}
}
<fieldset>
<legend>Personal details</legend>
<div id="two">
<div>
<label>Surname or family name:</label>
<input type="text" name="personal" />
</div>
</div>
</fieldset>

Related

Why the dom element not updating it's innerHTML?

The dom element stays the same even if I change the height or weight to make bmi underweight. How can I make the p element change dynamically when the BMI changes?
Here is the JS:
let heightEl = document.getElementById("height");
let weightEl = document.getElementById("weight");
let bmidisplayEl = document.getElementById("bmi-value");
let bmisubmitEl = document.getElementById("bmi-submit");
bmisubmitEl.addEventListener("click",bmiCalc);
export default function bmiCalc(){
let heightSquare =Math.pow(Number(heightEl.value), 2);
let bmiResult = Math.floor(Number(weightEl.value)*703/heightSquare);
let bmiStatus = document.createElement("p");
bmiStatus.setAttribute("id","bmistatus");
bmidisplayEl.innerHTML =`Your bmi is ${bmiResult}`;
if (bmiResult <= 18.5){
bmiStatus.innerHTML=`Underweight`;
}else if(bmiResult =>25){
bmiStatus.innerHTML=`Overweight`;
}
else{
bmiStatus.innerHTML=`Healthy`;
}
const bmiBody = document.getElementById("bmi");
bmiBody.appendChild(bmiStatus);
}
and here is the html:
<div id="bmi">
<h1>BMI Calculator</h1>
<div id="bmi-form-container">
<form action="" onsubmit="event.preventDefault()" >
<div id="top-row">
<div id="gender">
<p>Please select your gender:</p>
<input type="radio" id="male" name="gender" value="Male" required>
<label for="male">Male</label><br>
<input type="radio" id="female" name="gender" value="Female">
<label for="female">Female</label><br>
</div>
<div id="bmi-age">
<label for="">Age</label>
<input type="text" placeholder="" required>
</div>
</div>
<div id="form-inputs">
<label for="">Height(inches)</label><br>
<input type="text" placeholder="height" id="height" required>
<label for="">Weight(lb)</label>
<input type="text" placeholder="weight" id="weight" required>
</div>
<button id="bmi-submit">Submit</button>
</form>
</div>
<p id="bmi-value"></p>
</div>
Could it be the form submission issue as well?
I want it to display the proper bmi status as the bmi value changes. Instead, it never update the innerHTML after the first submission.
You need to check if the "bmistatus" p exist, if not then we create a new p, else we editing the existing one
let heightEl = document.getElementById("height");
let weightEl = document.getElementById("weight");
let bmidisplayEl = document.getElementById("bmi-value");
let bmisubmitEl = document.getElementById("bmi-submit");
bmisubmitEl.addEventListener("click",bmiCalc);
function bmiCalc(){
let heightSquare =Math.pow(Number(heightEl.value), 2);
let bmiResult = Math.floor(Number(weightEl.value)*703/heightSquare);
//get the bmistatus p element
let bmiStatus = document.querySelector("#bmistatus");
//if no bmiStatus element is found, then we create a new p
if (bmiStatus == undefined){
bmiStatus = document.createElement("p");
bmiStatus.setAttribute("id","bmistatus");
let bmiBody = document.getElementById("bmi");
bmiBody.appendChild(bmiStatus);
}
bmidisplayEl.innerHTML =`Your bmi is ${bmiResult}`;
if (bmiResult <= 18.5){
bmiStatus.innerHTML=`Underweight`;
}else if(bmiResult >= 25){
bmiStatus.innerHTML=`Overweight`;
}
else{
bmiStatus.innerHTML=`Healthy`;
}
}
<div id="bmi">
<h1>BMI Calculator</h1>
<div id="bmi-form-container">
<form action="" onsubmit="event.preventDefault()">
<div id="top-row">
<div id="gender">
<p>Please select your gender:</p>
<input type="radio" id="male" name="gender" value="Male" required>
<label for="male">Male</label><br>
<input type="radio" id="female" name="gender" value="Female">
<label for="female">Female</label><br>
</div>
<div id="bmi-age">
<label for="age">Age</label>
<input type="text" placeholder="" id="age" required>
</div>
</div>
<div id="form-inputs">
<label for="height">Height(inches)</label><br>
<input type="text" placeholder="height" id="height" required>
<label for="weight">Weight(lb)</label>
<input type="text" placeholder="weight" id="weight" required>
</div>
<button id="bmi-submit">Submit</button>
</form>
</div>
<p id="bmi-value"></p>
</div>
Edit : I add a gif where we see that the bmiStatus changes as expected

How do i disable textboxes based on what radio button is clicked in JavaScript?

I am trying to disable text the text boxes according to the radio button clicked but I can't figure out why they wouldn't disable.
HTML CODE (containing Textboxes and HTML)
if (document.getElementById("cashbtn").checked)
{
document.getElementById("cardam").disabled = true;
}
else if (document.getElementById("cardbtn").checked)
{
document.getElementById("casham").disabled = true;
}
else if (document.getElementById("cashwcardbtn").checked)
{
document.getElementById("giftcheck").disabled = true;
}
<div class="container">
<h1>Payment Details</h1>
<h3>Amount</h3>
<input type="text" id="amounttxt">
<h3>Payment Type</h3>
<input type="radio" name="radAnswer" id="cashbtn">
<label for="cash">Cash</label></br>
<input type="radio" name="radAnswer" id="cardbtn">
<label for="card">Card</label></br>
<input type="radio" name="radAnswer" id="cashwcardbtn">
<label for="cashwcard">Cash and Card</label></body></br>
<h3>Gift Check</h3>
<input type="text" id="giftcheck" >
<h3>Cash Amount</h3>
<input type="text" id="casham">
<h3>Card Amount</h3>
<input type="text" id="cardam"></br>
<button onclick="submit()">Submit</button>
</div>
You need event listeners to listen for the radio options.
let radioBtns = document.getElementsByName('radAnswer')
Array.from(radioBtns).forEach(function (el) {
el.onchange = function (e) {
if (document.getElementById("cashbtn").checked)
{
document.getElementById("cardam").disabled = true;
}
else if (document.getElementById("cardbtn").checked)
{
document.getElementById("casham").disabled = true;
}
else if (document.getElementById("cashwcardbtn").checked)
{
document.getElementById("giftcheck").disabled = true;
}
}
})
<div class="container">
<h1>Payment Details</h1>
<h3>Amount</h3>
<input type="text" id="amounttxt">
<h3>Payment Type</h3>
<input type="radio" name="radAnswer" id="cashbtn">
<label for="cash">Cash</label></br>
<input type="radio" name="radAnswer" id="cardbtn">
<label for="card">Card</label></br>
<input type="radio" name="radAnswer" id="cashwcardbtn">
<label for="cashwcard">Cash and Card</label></body></br>
<h3>Gift Check</h3>
<input type="text" id="giftcheck" >
<h3>Cash Amount</h3>
<input type="text" id="casham">
<h3>Card Amount</h3>
<input type="text" id="cardam"></br>
<button onclick="submit()">Submit</button>
</div>

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>

Apply Validation Function To All TextFields and Radio Buttons

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";
}
}
}

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