javascript radio button form - javascript

I'm new to javascript and am trying to write a simple script that will open 1 form upon checking a radio button, and another form upon clicking on the second one (none when none is selected).
I'm positive the js code is totally wrong as I am a COMPLETE beginner with js, but I used logic and a bit of google to get to this, and I don't know where I went wrong.
var ele1 = document.getElementsByClassName("form1");
var ele2 = document.getElementsByClassName("form2");
if (document.getElementById('button1').checked)
{
ele1.style.display = "block";
}
if (document.getElementById('button2').checked)
{
ele2.style.display = "block";
}
.form1 {
display: none;
background-color: red;
width: 100px;
height: 100px;
}
.form2 {
display: none;
background-color: blue;
width: 100px;
height: 100px;
}
<input type="radio" name="role" id="button1">
<input type="radio" name="role" id="button2">
<div class="form1">
</div>
<div class="form2">
</div>
<script src="/scripts/form.java"></script>

This code isn't wrong as such, but it only ever executes once; when the page loads. You instead want the forms to be toggled whenever the inputs are changed.
To do this, the visibility code is wrapped in a function. This function is then registered as an event handler on the <input> elements so that it executes whenever the <input>s change. Whenever the selected radio button changes, by clicking or by keyboard navigation, an 'input' event will be triggered on the elements, and then handled by the function.
I've also made a few other changes:
Use only ids since this is specific functionality for a handful of specific elements.
Use <form> elements for better semantics. All forms must be wrapped in a <form> element at some level.
Change .java to .js – JavaScript and Java are (unintuitively) unrelated.
Change the name on the <input>s to better describe their role.
<input type="radio" name="formID" id="input1">
<input type="radio" name="formID" id="input2">
<form id="form1">
<!-- fields -->
</form>
<form id="form2">
<!-- fields -->
</form>
<script src="/scripts/form.js"></script>
// form.js
// Get references to important elements.
var elInput1 = document.getElementById('input1');
var elInput2 = document.getElementById('input2');
var elForm1 = document.getElementById('form1');
var elForm2 = document.getElementById('form2');
// Define an event handler function.
function updateFormVisibility(event) {
var elSelectedInput = event.target;
if (elSelectedInput.id === 'input1') {
elForm1.style.display = 'block';
elForm2.style.display = '';
} else {
elForm1.style.display = '';
elForm2.style.display = 'block';
}
}
// Register the function as a handler for any `'input'` events that occur on the
// two radio button elements.
elInput1.addEventListener('input', updateFormVisibility);
elInput2.addEventListener('input', updateFormVisibility);

According to #Mehdi Brillaud's answer here: https://stackoverflow.com/a/42488571/13695248, you could try this with JQuery:
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<label><input type="radio" class="form-switch" name="colorCheckbox" value="red" data-id="a" checked> red</label>
<label><input type="radio" class="form-switch" name="colorCheckbox" value="green" data-id="b"> green</label>
<label><input type="radio" class="form-switch" name="colorCheckbox" value="blue" data-id="c"> blue</label>
<div class="form form-a active"> form a </div>
<div class="form form-b"> form b </div>
<div class="form form-c"> form c</div>
.form {
display: none;
}
.form.active {
display: block
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script>
$(document).ready(function() {
$('.form-switch').on('change', function() {
$('.form').removeClass('active');
var formToShow = '.form-' + $(this).data('id');
$(formToShow).addClass('active');
});
});
</script>

Is this what you want?
For modern browsers:- (Not recommend)
<input type="radio" name="role" id="button1" onchange = "form1.style.display ='block'; form2.style.display ='none'">
<input type="radio" name="role" id="button2" onchange = "form1.style.display ='none'; form2.style.display ='block'">
<div class="form1" id ="form1" style="display:none">Form 1
</div>
<div class="form2" id ="form2" style="display:none">Form 2
</div>
<script src="/scripts/form.js"></script>
Update
Recommend
<input type="radio" name="role" id="button1" onchange = "Show('form1')">
<input type="radio" name="role" id="button2" onchange = "Show('form2')">
<div class="form1" id ="form1" style="display:none">Form 1
</div>
<div class="form2" id ="form2" style="display:none">Form 2
</div>
<script src="/scripts/form.js"></script>
<script>
var selected = document.getElementById("form1");
function Show(curr_sel) {
selected.style.display = "none";
   selected = document.getElementById(curr_sel);
   selected.style.display = "block";
}
</script>

Related

Fade on Checkbox for Multiple Div Sections

I have a client that wants to have a checkbox that says "Mark as Compete" and once marked it makes the div with content fade. They basically want a step by step list like a recipe where users can check the box when they are done with a step and have it fade out.
I have been able to do so but not in a friendly way that someone who doesn't know code would be comfortable with editing. I am looking for some help simplifying it.
Current Code:
function ShowHideDivOne(chk_one) {
var one = document.getElementById("one");
one.style.opacity = chk_one.checked ? "0.5" : "1";
}
function ShowHideDivTwo(chk_two) {
var two = document.getElementById("two");
two.style.opacity = chk_two.checked ? "0.5" : "1";
}
function ShowHideDivThree(chk_three) {
var three = document.getElementById("three");
three.style.opacity = chk_three.checked ? "0.5" : "1";
}
div {font-wieght:bold;font-size:30px; margin-top:30px;}
<div id="one">One</div>
<input type="checkbox" id="chk_one" onclick="ShowHideDivOne(this)"/>Mark as done
<div id="two">Two</div>
<input type="checkbox" id="chk_two" onclick="ShowHideDivTwo(this)"/>Mark as done
<div id="three">Three</div>
<input type="checkbox" id="chk_three" onclick="ShowHideDivThree(this)"/>Mark as done
Right now if they wanted to add a "Four," I would have to have the ShowHideDivFour(chk_four) function preprogrammed and then they would have to go in and change all of the ids and onclicks in the div and the checkbox.
I am ok with showing them how to edit the id in the div. What I would prefer is to have a JavaScript code that works for an unlimited number of items in their list and they would only have to change the div id. I understand if they would also have to change the checkbox code but it would be preferable if they didn't.
Any help would be much appreciated.
If, somehow, your headers can come after the checkboxes, you can use the CSS sibling + selector to select it:
div {
font-size: 30px;
margin-bottom: 30px;
}
input:checked+div {
opacity: 0.5;
}
<label for="chk_one">Mark as done</label>
<input type="checkbox" id="chk_one" />
<div id="one">One</div>
<label for="chk_two">Mark as done</label>
<input type="checkbox" id="chk_two" />
<div id="two">Two</div>
<label for="chk_three">Mark as done</label>
<input type="checkbox" id="chk_three" />
<div id="three">Three</div>
Here is a complete, CSS-only solution that uses the above and a little CSS flexbox hack to reverse the display order of the header and checkbox, if you're fine with wrappers:
div.wrapper {
display: flex;
/* 👇 display elements in reverse order */
flex-direction: column-reverse;
}
div.item {
font-size: 30px;
margin-top: 30px;
}
input {
width: fit-content;
}
input:checked~div {
opacity: 0.5;
}
<!-- 👇 notice that the checkboxes come BEFORE
the text, but are displayed as if they are after -->
<div class="wrapper">
<label for="chk_one">Mark as done</label>
<input type="checkbox" id="chk_one" />
<div id="one" class="item">One</div>
</div>
<div class="wrapper">
<label for="chk_two">Mark as done</label>
<input type="checkbox" id="chk_two" />
<div id="two" class="item">Two</div>
</div>
<div class="wrapper">
<label for="chk_three">Mark as done</label>
<input type="checkbox" id="chk_three" />
<div id="three" class="item">Three</div>
</div>
Any "normal" solution (not as hacky as this) would only be attainable through JavaScript.
EDIT: if you're OK with using JS, here's something that looks marginally better by using direct element references in inline event listeners:
div {
font-size: 30px;
margin-top: 30px;
}
<div id="one">One</div>
<input type="checkbox" id="chk_one" onclick="one.style.opacity = (one.style.opacity == 0.5 ? 1 : 0.5)" />
<label for="chk_one">Mark as done</label>
<div id="two">Two</div>
<input type="checkbox" id="chk_two" onclick="two.style.opacity = (two.style.opacity == 0.5 ? 1 : 0.5)" />
<label for="chk_two">Mark as done</label>
<div id="three">Three</div>
<input type="checkbox" id="chk_three" onclick="three.style.opacity = (three.style.opacity == 0.5 ? 1 : 0.5)" />
<label for="chk_three">Mark as done</label>
You can simplify the code by adding a class name to the checkbox and adding an event listener to all elements of that class:
document.querySelectorAll('.markChk').forEach(el => {
el.addEventListener('click', function(event) {
var divID = this.parentElement.previousElementSibling;
divID.style.opacity = el.checked ? "0.5" : "1";
});
});
div {font-weight: bold; font-size: 30px; margin-top: 30px;}
<div id="one">One</div>
<label><input type="checkbox" id="chk_one" class="markChk" /> Mark as done </label>
<div id="two">Two</div>
<label><input type="checkbox" id="chk_two" class="markChk" /> Mark as done </label>
<div id="three">Three</div>
<label><input type="checkbox" id="chk_three" class="markChk" /> Mark as done </label>
Notes:
this.parentElement.previousElementSibling traverses from the checkbox to the previous div
notice the <label>, which allows the user to click on the label, not just the checkbox
to further simplify you likely want to generate the div and checkbox list dynamically
jQuery makes it easier than native JS to manipulate the DOM

Remove part of form when checkbox is checked

I'm trying to make a form that will hide and show some parts of the form. It working correctly in some tries. But when the user chooses and checks an option with class badCheckbox which is showing badField subsequently then user checks option without class badCheckbox which should showing 'goodField' than 'badField' is not hiding and still is shown.
And when a user tries to check options separately all work correctly only in upper mentioned case.
Is there any way to do it?
//Script to hide and show div
$('.badCheckbox').change(function() {
let checked = 0;
$('.badCheckbox').each(function() {
if (this.checked) {
checked += 1;
}
});
if (checked != 0) {
$('#badField').show();
$('#goodField').hide();
} else {
$('#badField').hide();
$('#goodField').show();
}
});
//script to check only one of three
$(".oneChecked").on('click', function() {
// in the handler, 'this' refers to the box clicked on
var $box = $(this);
if ($box.is(":checked")) {
var group = "input:checkbox[name='" + $box.attr("name") + "']";
$(group).prop("checked", false);
$box.prop("checked", true);
} else {
$box.prop("checked", false);
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input name="checkin" type="checkbox" class="oneChecked badCheckbox" />
<input name="checkin" type="checkbox" class="oneChecked badCheckbox" />
<input name="checkin" type="checkbox" class="oneChecked" />
<div id="badField" style="display:none;">
<p>:((</p>
<input type="submit" />
</div>
<div id="goodField">
<p>NICE!!!</p>
<input type="submit" />
</div>
here is a short version
$('#checks').on('change', 'input[name="checkin"]', function (){
if( $(this).is(':checked') ){
$('#checks .oneChecked:checked').prop('checked', false);
$(this).prop('checked', true);
} else {
$('#checks .oneChecked:checked').prop('checked', false);
$(this).prop('checked', false);
}
if( $('#checks .badCheckbox:checked').is(':checked') ){
$('#badField').show();
$('#goodField').hide();
} else {
$('#badField').hide();
$('#goodField').show();
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="checks">
<input name="checkin" type="checkbox" class="oneChecked badCheckbox"/>
<input name="checkin" type="checkbox" class="oneChecked badCheckbox"/>
<input name="checkin" type="checkbox" class="oneChecked"/>
</div>
<div id="badField" style="display:none;">
<p>:((</p>
<input type="submit"/>
</div>
<div id="goodField">
<p>NICE!!!</p>
<input type="submit"/>
</div>
Consider the following improvements.
$(function() {
function checkStuff(checked) {
if (checked) {
$('#badField').show();
$('#goodField').hide();
} else {
$('#badField').hide();
$('#goodField').show();
}
}
//script to check only one of three
$(".boxes").on('change', ".oneChecked", function() {
if ($(this).is(":checked")) {
$(".boxes input[type='checkbox']").prop("checked", false);
$(this).prop("checked", true);
checkStuff($(this).is(".badCheckbox"));
}
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="boxes">
<input name="checkin" type="checkbox" class="oneChecked badCheckbox" />
<input name="checkin" type="checkbox" class="oneChecked badCheckbox" />
<input name="checkin" type="checkbox" class="oneChecked" />
</div>
<div id="badField" style="display:none;">
<p>:((</p>
<input type="submit" />
</div>
<div id="goodField">
<p>NICE!!!</p>
<input type="submit" />
</div>
it's because you don't have an event when user click and the third checkbox.
Your function to show/hide message work when there are an update (change) on an input with the class .badCheckbox but when you click on the third (where doesn't have the class) your function is not called.
I think you should have a class on all your checkbox and use it in your function who lister the change.
Something like this :
$('.checkbox').change(function() {
let checked = 0;
$('.badCheckbox').each(function() {
// ...
});
And your html
<input name="checkin" type="checkbox" class="checkbox oneChecked badCheckbox"/>
<input name="checkin" type="checkbox" class="checkbox oneChecked badCheckbox"/>
<input name="checkin" type="checkbox" class="checkbox oneChecked"/>
There is a lot of optimization that can be done to improve your code, like using the radio to remove your oneChecked function or printing the right message when the checkbox is checked instead of using show/hide two div but i think you should see it in the future
I hope this can help you and welcome to StackOverflow
First of all, obviously your checkboxes have to act like radios. As I understand, that is what you want to do. So, I modifyed your script a little bit to make checkboses to act as they are radio inputs, and in the same time to show/hide paragraph, depending on if clicked element has class badCheckbox and it's state (checkd or not). Here is the result:
//Script to hide and show div
$('.oneChecked').click( (everyOne) => {
//handles click (and change) on every element with class oneChecked
//they all has it in your example
$('.oneChecked').each( (ind, currentOne) => {
//iterate to all elements with class oneChecked
//and compare if matches clicked one
if ( !$(currentOne).is($(everyOne.target)) ) {
//other instance, not clisked one, so clear it
//to simulate behaviour of radio input
$(currentOne).prop('checked', false);
}
});
//checks if clicked element is bad or not and show/hide your p
if ($(everyOne.target).hasClass('badCheckbox') && $(everyOne.target).prop('checked')){
console.log('b-s/h');
$('#badField').show();
$('#goodField').hide();
} else {
console.log('s/b-h');
$('#badField').hide();
$('#goodField').show();
}
});
Here is an workign example in CodePen: https://codepen.io/kalatchev/pen/gOpJBOv

How can I modify an HTML element from an external Javascript File?

I want to show an input when a checkbox is checked. So, I have created a js function to do it and when I write that function on the HTML file it works. But I want to write that function into an external Javascript file an use it from there. How can I do it?
HTML Code:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Complement Selection</title>
</head>
<body>
<form class="formComplement" action="../php/complementSelectionSave.php" method="POST">
<div class="mainContainer">
<input type="checkbox" name="hood" id="hood" onclick="showInput()">
<label for="hood">Hood</label><br>
<div class="inputBox" id="hoodNum" style="display:none">
<input type="number" name="hoodNumber" id="hoodNumber" required="" value="">
<label for="hoodNumber">Number of Hoods</label>
<br>
</div>
</div>
<br><br><br>
<input type="submit" value="Next" class="nextButton"/>
</form>
<script src="showInput.js"></script>
</body>
</html>
Javascript file:
function showInput() {
var checkBox = document.getElementById("hood");
var inputBox = document.getElementById("hoodNum");
if (checkBox.checked == true) {
inputBox.style.display = "block";
} else {
inputBox.style.display = "none";
}
}
EDIT: It appears this error:
showInput.js:4 Uncaught TypeError: Cannot read property 'checked' of
null
at showInput.js:4
If only thing why you need javascript here is to change class, to show / hide element than instead what you can do is to write code in pure css and html, using input:checked to change visibility.
Also nextButton should be targetable by css, like element or its parent is same lvl and after input
#hood:checked ~ .nextButton {
display: block;
}
.nextButton {display: none;}
<input type="checkbox" name="hood" id="hood">
<label for="hood">Hood</label><br>
<input type="submit" value="Next" class="nextButton"/>
Try onchange instead of onclick, and clear up the HTML - the function works as intended! :)
function showInput() {
var checkBox = document.getElementById("hood");
var inputBox = document.getElementById("hoodNum");
if (checkBox.checked == true) {
inputBox.style.display = "block";
} else {
inputBox.style.display = "none";
}
}
<form class="formComplement" action="" method="POST">
<div class="mainContainer">
<input type="checkbox" name="hood" id="hood" onchange="showInput()">
<label for="hood">Hood</label><br>
<div class="inputBox" id="hoodNum" style="display:none">
<input type="number" name="hoodNumber" id="hoodNumber" required="" value="">
<label for="hoodNumber">Number of Hoods</label>
<br>
</div>
</div>
<br><br><br>
<input type="submit" value="Next" class="nextButton" />
</form>
(I deleted the action from the form, as it made no sense in the snippet.)

How to use Javascript/JQuery to verify that at least two fields in a checkbox are selected?

I am trying to create Javascript verification code for a form, so that each section of the form is verified after hitting "submit". I am having trouble writing the code so that the checkbox section of the form verifies that two or more boxes have been selected. I tried to start simple by writing the code so that a div, errorcheckbox, would display a message if no checkbox is selected at all. However it does not work. Here is the HTML and script for the code pertaining to the checkbox:
HTML:
<form action="#" method="POST">
<div class="contactForm">
<label for="checkbox" id="checkbox" name="checkbox">Contactee Type: </label><br>
<div id="errorcheckbox" class="error"></div>
<input type="checkbox" name="type1" value="Individual">Individual<br>
<input type="checkbox" name="type2" value="Catering">Business:Catering<br>
<input type="checkbox" name="type3" value="Partner">Business:Partner<br>
</div>
<div class="button"><input type="button" name="submit" id="submit" value="Submit"></div>
</form>
and the Javascript:
$("document").ready(function(){
console.log("Loaded");
$("#submit").click(function(){
checkContactee();
});
$("#checkbox").change(function(){
console.log("Something in contactee changed");
checkContactee();
});
function checkContactee(){
if (document.getElementById("checkbox").checked == false){
$("#errorcheckbox").html("<p>You missed this field</p>");
$("#errorcheckbox").addClass("showerror");
}
else{
$("#errorregarding").html("");
$("#errorregarding").removeClass("showerror");
}
}
Right now, the code does nothing. The errorcheckbox div doesn't appear, and there is no change in the console log if a checkbox item is selected. So, this is one problem I'm having. I still need to verify that two or more of the boxes are checked. I'm hoping to do this by adding an if else statement to the checkContactee function, but am not sure how.
Looking at your code I would recommend a couple of things. Your check boxes look like you want to capture multiple values for a contact type, so they should have the same name attribute. Each check box should have it's own label and where you have a label now you should use a fieldset and legend.
By wrapping the checkboxes in a fieldset we can then use that as part of the validation process.
$("document").ready(function() {
console.log("Loaded");
$("fieldset[data-mincheckboxchecked] [type=checkbox]").on("click", function() {
console.log("Click")
//Get the parent fieldset
let $parent = $(this).closest("fieldset[data-mincheckboxchecked]");
validateMultiCheckBox($parent);
});
});
function validateMultiCheckBox($parent) {
console.log($parent)
//Get minimum checked from the data attribute
let minCheked = $parent.data("mincheckboxchecked");
minChecked = parseInt(minCheked, 10);
//Get the number of checked checkboxes in the parent
let numCheked = $parent.find("[type=checkbox]:checked").length;
//Validation Logic
if (numCheked < minCheked) {
$parent.find(".error").html("<p>Please select at least " + minChecked + " option" + (minCheked !== 1 ? "s" : "") + "</p>");
$parent.find(".error").addClass("showerror");
return false;
} else {
$parent.find(".error").html("");
$parent.find(".error").removeClass("showerror");
return true;
}
}
$("#submit").click(function() {
var isValid = false;
var multiCheckValid = true;
//Validate each group of multi checkboxes
$("fieldset[data-mincheckboxchecked]").each(function() {
console.log(this);
if (!validateMultiCheckBox($(this))) {
multiCheckValid = false;
}
})
//Normally you'e set this to return false, leaving like
//this for demo purposes
console.log(multiCheckValid);
return isValid;
});
.error {
display: none;
color: red;
}
.error.showerror {
display: block;
}
fieldset label {
display: block;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form action="#" method="POST">
<div class="contactForm">
<fieldset data-mincheckboxchecked="2">
<legend>Contactee Type: </legend>
<div id="errorcheckbox" class="error"></div>
<label><input type="checkbox" name="contactType" value="Individual">Individual</label>
<label><input type="checkbox" name="contactType" value="Catering">Business:Catering</label>
<label><input type="checkbox" name="contactType" value="Partner">Business:Partner</label>
</fieldset>
<fieldset data-mincheckboxchecked="1">
<legend>One Required: </legend>
<div id="errorcheckbox" class="error"></div>
<label><input type="checkbox" name="oneReq" value="1">A Thing</label>
<label><input type="checkbox" name="oneReq" value="2">Another Thing</label>
<label><input type="checkbox" name="oneReq" value="3">Yet another thing</label>
</fieldset>
<fieldset data-mincheckboxchecked="3">
<legend>Top 3 Movies: Three required</legend>
<div id="errorcheckbox" class="error"></div>
<label><input type="checkbox" name="movie" value="Top Gun">Top Gun</label>
<label><input type="checkbox" name="movie" value="Terminator">Terminator</label>
<label><input type="checkbox" name="movie" value="Sound Of Music">Sound OF Music</label>
<label><input type="checkbox" name="movie" value="Mission Impossible">Mission Impossible</label>
</fieldset>
</div>
<div class="button"><input type="button" name="submit" id="submit" value="Submit"></div>
</form>
This way it's extensible and not reliant on Ids.
You can use the :checked which the selector to get the checked items.
function validate() {
console.log('Total Checked = ' + $('.contactForm input[type="checkbox"]:checked').length);
}
<script src="https://code.jquery.com/jquery-3.4.1.min.js" integrity="sha256-CSXorXvZcTkaix6Yvo6HppcZGetbYMGWSFlBw8HfCJo=" crossorigin="anonymous"></script>
<div class="contactForm">
<label for="checkbox" id="checkbox" name="checkbox">Contactee Type: </label><br>
<div id="errorcheckbox" class="error"></div>
<input type="checkbox" name="type1" value="Individual">Individual<br>
<input type="checkbox" name="type2" value="Catering">Business:Catering<br>
<input type="checkbox" name="type3" value="Partner">Business:Partner<br>
<button onclick="validate()">Validate</button>
</div>
use a class for your checkboxes and select that or use tag name and type to select tags,
you are using the id of a label tag for checking checkboxes
, use .is() method in jquery to check is checked
$("document").ready(function(){
console.log("Loaded");
$("#submit").click(function(){
checkContactee();
});
$("input[type='checkbox']").change(function(){
console.log("Something in contactee changed");
checkContactee();
});
function checkContactee(){
if ($("input[type='checkbox']").is(':checked'){
$("#errorcheckbox").html("<p>You missed this field</p>");
$("#errorcheckbox").addClass("showerror");
}
else{
$("#errorregarding").html("");
$("#errorregarding").removeClass("showerror");
}
}
var checkedCount=$("input[name^='type']:checked).length - this pulls all inputs, looks for those with the name beginning with "type", keep the ones that are checked, and returns how many are check (here, assigned to the checkedCount variable). I'll leave further validation/scolding of the user up to you

toggle textbox if checkbox is true for CMS

I try to make something like that work, implementing it in my CMS:
Fixed CMS part:
<div class="RadioList" id="radioListId">
<div class="TxtLbl" id="textLblId"> Question </div>
<span id="spanId">
<input value="yes"></input>
<input value="no"></input>
</span>
</div>
<div class="TxtBox" id="txtBoxId">
some text
</div>
own JS part someting like:
function EnableTextbox(radioListId,spanId)
{
if(document.getElementById(radioListId).inputValue == "yes")
document.getElementById(textBoxId).visibility = visible;
else
document.getElementById(textBoxId).visibility = hidden;
}
But I am not quite sure how to put it correctly - my understanding of js is not really high enough.
Any helping comments are highly appreciated!
try this
HTML
<div class="RadioList" id="radioListId">
<div class="TxtLbl" id="textLblId">Question</div> <span id="spanId">
<input type="radio" value="yes" name="showhide"> Show</input>
<input type="radio" value="no" name="showhide"> Hide</input>
</span>
</div>
<div class="TxtBox" id="txtBoxId">some text</div>
Script
$(document).ready(function () {
$("#txtBoxId").hide();
$("input[name='showhide']").on("click", function () {
var option = $(this).attr('value');
if (option == "yes") {
$("#txtBoxId").show();
} else {
$("#txtBoxId").hide();
}
});
});
Fiddle Sample
There are a few changes you need to make:
the inputs need to have a type="radio" to indicate that those are radio buttons.
the inputs need to have a common name="whatever" to indicate that both belong to same group and cannot be checked simultaneously.
the inputs need to have a text between the opening/closing tags, this text appears next to the radio button.
you need to call the javascript function when you click/change the buttons, and inside you check which radio was selected.
you pass the radio button reference into the javascript function by writing this as the function variable.
inside the function you retrieve the radio button reference, you can name the variable whatever you want.
you are using visible and hidden as variables, but those are not defined. it supposed to be either a string, or a boolean value. i prefer to use css for that purpose.
here is an Example Fiddle
HTML:
<div class="RadioList" id="radioListId">
<div class="TxtLbl" id="textLblId">Question</div> <span id="spanId">
<input type="radio" value="yes" onclick="EnableTextbox(this);" name="Answer">Yes</input>
<input type="radio" value="no" onclick="EnableTextbox(this);" name="Answer">No</input>
</span>
</div>
<div class="TxtBox" id="txtBoxId">some text</div>
JS:
function EnableTextbox(radioList) {
if (radioList.value == "yes") document.getElementById("txtBoxId").style.visibility = "visible";
else document.getElementById("txtBoxId").style.visibility = "hidden";
}
Since onclick="" is outdated you should use the element.addEventListener();!
Here is an Example in Fiddle!
HTML:
<div class="RadioList" id="radioListId">
<div class="TxtLbl" id="textLblId"> Question </div>
<span id="spanId">
<label><input type="radio" name="answer" id="yes" value="yes" />Yes</label>
<label><input type="radio" name="answer" id="no" value="no"/>No</label>
</span>
</div>
<div class="TxtBox" id="txtBoxId">
some text
</div>
JS:
var yes = document.getElementById('yes');
var no_ = document.getElementById('no');
if (yes.addEventListener) {
yes.addEventListener ("RadioStateChange", OnChange, false);
no_.addEventListener ("RadioStateChange", OnChange, false);
}
function OnChange(){
if (yes.checked) {
document.getElementById('txtBoxId').style.display = 'inline';
}
else {
document.getElementById('txtBoxId').style.display = 'none';
}
}
Greetings from Vienna
In jQuery
<span id="spanId">
<input type="radio" name="radiobutton" value="yes" />
<input type="radio" name="radiobutton" value="no" />
</span>
$('#spanId input:radio[name="radiobutton"]').change(function(){
if($(this).val() === 'yes'){
$('#txtBoxId').show();
} else {
$('#txtBoxId').hide();
}
});
Explanation
$('#txtBoxId').show() = display:block;
$('#txtBoxId').hide() = display:none;
If you want visibility instead.
$('#txtBoxId').css('visibility','visible');
$('#txtBoxId').css('visibility','hidden');
Let me know if you have any question.

Categories

Resources