Validation input if using show hide jQuery - javascript

How do i validate if there is a div that uses display:none
$("input[name$='test']").click(function() {
var test = $(this).val();
$("div.desc").hide();
$("#test" + test).show();
});
$(".check").click(function(){
var name = $("#name").val();
var add = $("#add").val();
var hobby = $("#hobby").val();
if( name == "" ){
$("#name").css('border', '1px solid red');
return false
} else if ( add == "" ){
$("#add").css('border', '1px solid red')
} else if ( hobby == "" ){
$("#hobby").css('border', '1px solid red')
} else {
alert('success');
return true
}
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="myRadio">
<div class="condition">
<input type="radio" name="test" checked="checked" value="Y" id="first" />
<label for="first">First</label>
</div>
<div class="condition">
<input type="radio" name="test" value="N" id="second" />
<label for="second">Second</label>
</div>
<div class="condition">
<input type="radio" name="test" value="YN" id="third" />
<label for="third">Third</label>
</div>
</div>
<div id="testY" class="desc">
<label for="name">Name</label>
<input type="text" id="name" />
</div>
<div id="testN" class="desc" style="display:none">
<label for="add">Add</label>
<input type="text" id="add" />
</div>
<div id="testYN" class="desc" style="display:none">
<label for="hobby">Hobby</label>
<input type="text" id="hobby" />
</div>
<br>
<button class="check">Check</button>
When I fill in the first content and click validation, it should issue a success alert because my goal is to validate the div is showing.
Any idea?
Thank you

You can find the input need to check by checked radio value first then validate this input:
$("input[name$='test']").click(function() {
var test = $(this).val();
$("div.desc").hide();
$("#test" + test).show();
});
$(".check").click(function(){
let checked = $("input[name$='test']:checked").val();
let input = $("#test" + checked).find('input');
let val = input.val();
if(!val){
$(input).css('border', '1px solid red');
return false
}
alert('success');
return true
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="myRadio">
<div class="condition">
<input type="radio" name="test" checked="checked" value="Y" id="first" />
<label for="first">First</label>
</div>
<div class="condition">
<input type="radio" name="test" value="N" id="second" />
<label for="second">Second</label>
</div>
<div class="condition">
<input type="radio" name="test" value="YN" id="third" />
<label for="third">Third</label>
</div>
</div>
<div id="testY" class="desc">
<label for="name">Name</label>
<input type="text" id="name" />
</div>
<div id="testN" class="desc" style="display:none">
<label for="add">Add</label>
<input type="text" id="add" />
</div>
<div id="testYN" class="desc" style="display:none">
<label for="hobby">Hobby</label>
<input type="text" id="hobby" />
</div>
<br>
<button class="check">Check</button>

Related

how to enable textbox ,when uncheck a checkbox using javascript

I have 5 teachers names and corresponding checkboxes(5) I am using checkall function to check all check boxes.
now I want ,when I uncheck a checkbox now enable a textbox at right side.
how to create a textbox from unchecked function using javascript?
my code is :
HTML + PHP :
<input type="checkbox" class="check form-control" id="checkFull">
<div class="form-group{{ ($errors->has('check')) ? 'has error' : '' }}">
<label for="check" class="col-sm-4 control-label">{{$teacher->tname}}:</label>
<div class="col-sm-4">
<input type="hidden" id="{{$teacher->user_id}}" name="{{$teacher->user_id}}" value="0">
<input id="{{$teacher->user_id}}" name="{{$teacher->user_id}}" type="checkbox" value="1" class="check form-control">
</div>
<div class="col-sm-4">
<input type="text" class="textBox">
</div>
</div>
JAVASCRIPT :
$("#checkFull").click(function() {
$(".check").prop('checked', $(this).prop('checked'));
});
what is the javascript code to enable textbox?
function changeTextBoxFormCheckBox($elm){
var $textBox= $elm.closest(".form-group").find("input[type='text']");
if($elm.is(":checked")){
$textBox.attr("disabled",true);
}else{
$textBox.attr("disabled",false);
}
}
$(".checkbox").each(function(){
changeTextBoxFormCheckBox($(this));
})
$("#checkFull").click(function () {
var checkAllProp= $(this).prop('checked');
$(".checkbox").each(function(){
var $this=$(this);
$this.prop('checked', checkAllProp);
changeTextBoxFormCheckBox($(this));
})
});
$(".checkbox").click(function () {
changeTextBoxFormCheckBox($(this));
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<input type="checkbox" class="check form-control" id="checkFull">
<div class="form-group {{ ($errors->has('check')) ? 'has error' : '' }}">
<label for="check" class="col-sm-4 control-label">tname:</label>
<div class="col-sm-4">
<input type="hidden" id="{{$teacher->user_id}}" name="{{$teacher->user_id}}" value="0">
<input id="{{$teacher->user_id}}" name="{{$teacher->user_id}}" type="checkbox" value="1" class="check form-control checkbox">
</div>
<div class="col-sm-4">
<input type="text" class="textBox">
</div>
</div>
Format your html code as I mentioned. You can do change as per your need
$(document).on('change', '[type=checkbox]', function() {
if ($(this).is(":checked")) {
$("#textBox1").attr("disabled", "disabled");
} else {
$("#textBox1").removeAttr("disabled");
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="form-group">
<div class="col-sm-4 teacherContent">
<input type="hidden" id="teacherId1" name="teacherName1" value="0">
<input type="hidden" id="teacherId2" name="teacherName2" value="1">
<input id="teacherCheck_1" class="teacherCheck" name="teacherCheckName1" type="checkbox" value="1" class="check form-control">
<input id="teacherCheck_2" class="teacherCheck" name="teacherCheckName2" type="checkbox" value="1" class="check form-control">
</div>
<div class="col-sm-4">
<input type="text" id="textBox1">
</div>
</div>
$(document).on('change', '[type=checkbox]', function() {
var val = $(this).data('value');
if ($(this).is(":checked")) {
$("#textBox"+val).attr("disabled", "disabled");
} else {
$("#textBox"+val).removeAttr("disabled");
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="form-group">
<div class="col-sm-4 teacherContent">
<input type="hidden" id="teacherId1" name="teacherName1" value="0">
<input type="hidden" id="teacherId2" name="teacherName2" value="1">
<input id="teacherCheck_1" data-value="1" name="teacherCheckName1" type="checkbox" class="check form-control">
<input type="text" id="textBox1">
<input id="teacherCheck_2" data-value="2" class="teacherCheck" name="teacherCheckName2" type="checkbox" class="check form-control">
<input type="text" id="textBox2">
</div>
</div>

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 get text value from radio button and assign value to a specific div

If I am using one text box and 3 div, how can I set the entered value in that div?
Here is my code. I have to get the div value from the radio button selected. Likewise, how can I get the text box value?
Here is my code:
$(document).ready(function() {
$("#radio_submit").click(function(e) {
var check = $("input[name=user_options]:checked").parent().next().text();
if (!check) {
alert('Please select options!');
} else {
$('#valueee').html(check);
}
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form id="myform">
<div>Choose option:</div>
<div>
<input type="radio" name="user_options" value="456" />
</div>
<div name="deff" id="val1" x>123</div>
<span>CSS</span>
<br></br>
<div>
<input type="radio" name="user_options" value="456" />
</div>
<div name="deff" id="val2">456</div>
<span>html</span>
<br></br>
<div>
<input type="radio" name="user_options" value="678" />
</div>
<div name="deff" id="val3">678</div>
<span>jquery</span>
<br></br>
<div name="deff" id="val4">
<input type="radio" name="user_options" value="675" />
</div>
<input class="text-input" id="other-input" size="5" value="">
<span>JS</span>
<br></br>
<div><button id="radio_submit" type="button">Show Selected Radio</button></div>
</form>
<div id="valueee"></div>
Not sure what your meaning but may be you need to again check and try to get val() if is undefined,
View Demo jsFiddle
$(document).ready(function () {
$("#radio_submit").click(function (e) {
var check = $("input[name=user_options]:checked").parent().next().text();
if (!check) var check = $("input[name=user_options]:checked").parent().next().val();
if (!check) {
alert('Please select options!');
} else {
$('#valueee').html(check);
}
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<form id="myform">
<div>Choose option:</div>
<div>
<input type="radio" name="user_options" value="456" />
</div>
<div name="deff" id="val1" x>123</div>
<span>CSS</span>
<br></br>
<div>
<input type="radio" name="user_options" value="456" />
</div>
<div name="deff" id="val2">456</div>
<span>html</span>
<br></br>
<div>
<input type="radio" name="user_options" value="678" />
</div>
<div name="deff" id="val3">678</div>
<span>jquery</span>
<br></br>
<div name="deff" id="val4">
<input type="radio" name="user_options" value="675" />
</div>
<input class="text-input" id="other-input" size="5" value="" />
<span>JS</span>
<br></br>
<div>
<button id="radio_submit" type="button">Show Selected Radio</button>
</div>
</form>
<div id="valueee"></div>
You can use is() to check if next element is div or input. If input then use .val() to read value otherwise use .text().
$(document).ready(function() {
$("#radio_submit").click(function (e) {
var next = $("input[name=user_options]:checked").parent().next();
//check if next element is input and read value otherwise read text
var check = '';
if($(next).is('input'))
check = $(next).val();
else
check = $(next).text();
if(!check){
alert('Please select options!');
}else{
$('#valueee').html(check);
}
});
});
DEMO

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