style visibility and javascript - javascript

I would like a certain 'div' to be visible when i select a radio button and would like the same div to get hidden when i select the other radio button. How can i achieve this. Below is my attempt. Please let know what is wrong here.
<label>For State govt. Ex- Employee
<span class="small">Select if you are a state govt. ex-employee</span>
</label>
<p>
<label>Yes</label>
<input type="radio" name="stateGov" id="stategov" value="yes" class="choice" onClick="stateGovOptions()"/>
<label>No</label>
<input type="radio" name="stateGov" id="stategov" value="no" class="choice" onClick="stateGovOptions()"/>
</p>
<!-- State govt. ex- employees -->
<div id="stateOptions" style="visibility:hidden">
<label>
<span class="small">Select </span>
</label>
<p>
<select title="stateGovExEmp" name="stateGovExEmp" id="fdivision">
<option value="state_gov_lev_not_sel">--Select Level At Which Worked At State --</option>
<option value="less">Less than or equal to one year</option>
<option value="between">More then one but less than two years</option>
<option value="more">More than two years</option>
</select>
</p>
</div>
when the 'yes' radio button is selected the div with the id 'stateoptions' should be visible and when the 'no' radio button is pressed it should get hidden again. To achieve this below is my js attempt.
/* displays the contents when state gov ex-employee selected and removes it when not selected */
function stateGovOptions()
{
if(document.getElementById('stategov').value == 'yes')
document.getElementById('stateOptions').setAttribute('style','visibility:visible');
else
document.getElementById('stateOptions').setAttribute('style','visibility:hidden');
}
Pressing the yes button displays the required div, but pressing the no button also makes it visible, despite the 'else' block in the js function.
Please explain what am i missing out here.

Your html is invalid because you've used the same id on multiple elements. Which in turn means that it doesn't really make sense to try to select those elements using document.getElementById(), since that method returns a single element (or null) - so how would it know which element you mean?
A minimal change to your existing code to get it to work would be to pass the value of the clicked item to your function:
<input type="radio" name="stateGov" value="yes" class="choice"
onClick="stateGovOptions(this.value)"/>
<label>No</label>
<input type="radio" name="stateGov" value="no" class="choice"
onClick="stateGovOptions(this.value)"/>
...and then use it like this:
function stateGovOptions(val)
{
if(val == 'yes')
document.getElementById('stateOptions').setAttribute('style','visibility:visible');
else
document.getElementById('stateOptions').setAttribute('style','visibility:hidden');
}
Demo: http://jsfiddle.net/ryxCM/
Note that normally one wouldn't overwrite the entire style attribute to set one property, one would set just the property in question:
document.getElementById('stateOptions').style.visibility = 'visible';
Demo: http://jsfiddle.net/ryxCM/1/

Do you even need JS for this?
Unwrapping the elements allows you to do this with pure CSS.
Codepen Example
CSS
#stategov1 ~ #stateOptions {
visibility:hidden;
}
#stategov1:checked ~ #stateOptions {
visibility:visible;
}
HTML
<form>For State govt. Ex- Employee
<span class="small">Select if you are a state govt. ex-employee</span>
<label>Yes</label>
<input type="radio" name="stateGov" id="stategov1" value="yes" class="choice"/>
<label>No</label>
<input type="radio" name="stateGov" id="stategov2" value="no" class="choice"/>
<!-- State govt. ex- employees -->
<div id="stateOptions">
<label>
<span class="small">Select </span>
</label>
<select title="stateGovExEmp" name="stateGovExEmp" id="fdivision">
<option value="state_gov_lev_not_sel">--Select Level At Which Worked At State --</option>
<option value="less">Less than or equal to one year</option>
<option value="between">More then one but less than two years</option>
<option value="more">More than two years</option>
</select>
</div>
</form>
Then it's a matter of basic styling

Try this after removing the duplicate IDS
document.getElementById('stateOptions').style.visibility=document.getElementsByName('stategov')[0].checked?"visible":"hidden";
You may want to use display block/none to not have the div take up any space

Try this
function stateGovOptions(){
if(document.getElementById('stategov').value =='yes')
document.getElementById('stateOptions').setAttribute('style','visibility:visible');
else
document.getElementById('stateOptions').setAttribute('style', 'display:none');
}

ById('stategovfunction stateGovOptions(){
if(document.getElementById('stategov').value =='yes')
document.getElementById('stateOptions').setAttribute('style','visibility:visible');
else

Related

How to elegantly add and remove elements from DOM

So I have a dynamic form where certain inputs should only become available (and visible) based upon what a user has already entered. The way I'm starting to go about it has a wrong smell.
It is straightforward enough to add material to the DOM
<script>
function addStuffToTheDOM(s1, s2){
var s1 = document.getElementById(s1);
var s2 = document.getElementById(s2);
s2.innerHTML = "";
if (s1.value==="job_1"){
s2.insertAdjacentHTML('afterend', '<p><select name="scholarship" id="scholarship"><option value="" disabled="disabled" selected="selected">*Position</option> <option value="" disabled="disabled" > </option> <option value="HR">HR</option> <option value="CTO">CTO</option> <option value="test">test</option> <option value="test2">test2</option> <option value="test3">test3</option> <option value="test4">test4</option> </select> </p> <select name="previous_experience" class="hidden"
id="new_to_demo"><option value="0" disabled="disabled" selected="selected"></option> <p> <p> <input type="text" name="supervisor" id="supervisor" maxlength="50" size="30"> <label for="supervisor">*Supervisor</label> </p> <p> <input type="text" name="office_location" id="office_location" maxlength="50" size="30"> <label for="office_location">Office location</label> </p> <p> <input type="text" name="programme_start_date" id="programme_start_date" maxlength="50" size="30"> <label for="programme_start_date">programme_start_date</label> </p>');
}
}
</script>
<!-- .... -->
<form>
<!-- ... -->
<select name="type" id="type" onchange="addStuffToTheDOM(this.id, 'alma_mater')">
<option value="" disabled="disabled" selected="selected">*Job Interest?</option>
<option value="" disabled="disabled" > </option>
<option value="job_1">The really big job</option>
<option value="job_2">The other job</option>
</select>
And while this insertion in itself could be better (instead of jamming an enormous string into insertAdjacentHTML() ) an immediate problem presents itself in that
If the user has made a mistake and selects the other option (for which all that inserted HTML is irrelevant) then some other code will have to be run to remove all those new elements. Yuck.
Without this removal process if the user selects the other option and then goes back and selects option "job_1" again, then the form is immediately broken by the duplication of all that content. Yikes.
The backend checking has to be extra careful to do proper checking: are inputs empty because they haven't been filled in, or because they simply don't exist?
What would be the ideal methodology for implementing this dynamic content?
Yes, that has a worrying smell. You could create a check-function that runs each time someone clicks/types (depending on what you want to include in your form) a field. That functions itself needs certain conditions that are going to be checked.
This is a quick example I put together. Use jQuery (or regular javascript if you want) and put together something like this. Hope this helps!
$(document).ready(function(){
$('#checkbox').click(function(){
if($("#checkbox").is(':checked'))
$("#textbox").hide();
else
$("#textbox").show();
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<form>
<input id="checkbox" type="checkbox">I want to hide a textbox</input><br>
<input id="textbox" type="textbox" placeholder="This can be hidden"></input>
</form>
EDIT: To add, if you want to check for textbox values or textareas, in jQuery you use for example:
$('#textbox').val();

I have a form that I want to hide some textfields until one option y selected on a dropdown menu

I have a dropdown with 3 options option1, option2 and option3 then I have 3 text fields for each option, I want the text fields to be hidden until 1 option is selected then I want to show only those 3 fields.
I have been searching and trying a lot of javascript functions but they are not working at all or they only show 1 of the text fields but they don't hide back if they switch option.
I gave up and ask.
You can try jQuery. Start by wrapping your fields within divs, (each se group of textboxes in each div)
use this to hide them
CSS
}
.hidden {
display:none;
}
then use this function
jQuery
$(function(){
$("select[name='option1']").change(function(){
if ($(this).val() == "value1"){
$("div[name='group1']").show();
$("div[name='group2']").hide();
$("div[name='group3']").hide();
}
});
and your form elements should be something like this
HTML
<select name="option1" id="option1">
<option value="value1">value</option>
<option value="value2">value</option>
<option value="value3">value</option>
</select>
<div id="group1" name="group1" class="hidden" style="display: block; ">
<label>text:</label>
<input type="text" name="text1"><br><br>
<label>text:</label>
<input type="text" name="text2"><br><br>
<label>text:</label>
<input type="text" name="text3">
</div>
Put a class on the select and input tags
<select class="opts">...</select>
// Other select tags
<input class="inputs" style="display: none; " ...>
// Other input tags
// Somewhere in a script tag
$('.opts').on('change', function() {
$('.inputs').show()
$('.opts').hide()
});

jquery show and hide divs

I have a form with a yes|no question displayed by radio selectors. I have two divs each one containing different drop downs based on the yes|no response. I cannot figure out how to show one and hide the other.
jsFiddle of this code
$(document).ready(function(){
$("input[name=radio_button]").change(function() {
var test1= $(this).val();
$("#"+test1).show();
$("div.test2").hide();
});
$("input[name=radio_button]").select(function() {
var test2= $(this).val();
$("#"+test2).show();
$("div.test1").hide();
});
});
<p>
<label class="required"> </label>
Yes <input name="radio_button" id="radio_button" type="radio" value="test2" onChange="" />
No <input name="radio_button" id="radio_button" type="radio" value="test1" />
</p>
<p>
<label class="required">Device: </label><br />
<div id="test1" class="test1_div">
<label style="font-weight:600;">test1</label>
<select name="order.item" id="item" >
<option value="default">Please Select item</option>
</select>
</div>
<div id="test2" class="test2_div">
<label style="font-weight:600;">item2</label>
<select name="order.item" id="device">
<option value="default">Please Select Device</option>
</select>
</div>
</p>
To make one hidden and other visible , you have to first hide both the blocks then add show() on the block you want to see. This will work for you.
Assuming your markup (html) is correct, try the following. It binds to click-events of those radio buttons (both of them), always hides both divs first, and then shows the appropiate div only (the one that belongs to the radio button clicked).
$(document).ready(function(){
$("input[name=radio_button]").click(function() {
var test= $(this).val();
$("div.test1, div.test2").hide(); //Hide both divs
$("#"+test).show();
});
});

Accessing the value of a radio button sliding among html tags

There is this code that apears several times in my page:
<div>
<input type="hidden" name="product" id="productF3" value="7">
<div>
<input type="radio" name="size" id="size_s" value="3"> small size
</div>
<div>
<input type="radio" name="size" id="size_n" value="4"> regular size
</div>
</div>
I have a problem getting the selected value, starting from the productF3 element.
Right now I'm using this code to solve my problem:
if($("#productF3").next().children("input[#name=size]:checked").val() != undefined) do something
else if($("#productF3").next().next().children("input[#name=size]:checked").val() != undefined) do something
else alert("Select a size");
But I want a more robust solution, any suggestions?
Thanks!
Firstly change $("productF3") to $("#productF3"). Secondly why don't you use
$("#productF3").parent().find("input[type='radio'][name='size']:checked").val()
to get selected radio value?

Show (Visible/Hidden NOT Show/Hide) HTML Element based on form select box selection

The following worked perfectly for my needs. Took the state of a checkbox and did wonderful things for me; Made 3 different form elements visible (vs. show/hide) based on checkbox checked or not checked. Simple, I guess. Then again, I base "simple" on how symmetrical the code looks and if it's less that 10 lines. Other than that, I'm lost. However, I've officially given up on messing around with IE's checkbox border issue and X-browser alignment yippeedoodles. I want pixel perfect the hard way. But I lost that battle. But rather than get into any discussion about that, I need to accomplish the same thing using a form select box as I was able to do with the checkboxes (below):
<form id="form">
<input id="checkbox" name="checkbox" type="checkbox" onclick="showhideid" />
</form>
#IdOne, #IdTwo, #IdThree (visibility:hidden;}
function showhideid()
{
if (document.form.checkbox.checked)
{
document.getElementById("IdOne").style.visibility = "visible";
document.getElementById("IdTwo").style.visibility = "visible";
document.getElementById("IdThree").style.visibility = "visible";
document.getElementById("IdFour").setAttribute("class", "required");
}
else
{
document.getElementById("IdOne").style.visibility = "hidden";
document.getElementById("IdTwo").style.visibility = "hidden";
document.getElementById("IdThree").style.visibility = "hidden";
document.getElementById("IdFour").setAttribute("class", "");
}
}
Now, if I can accomplish the same thing using a select box (below), I will die a happy man.
This is as far as I've gotten. I'm super dizzy from reading Jquery/CSS man pages and I just can't put it all together.
<html>
<form id="form">
<select name="SelectBox">
<option>Make a Choice</option>
<option value="Value1">Selection1</option>
<option value="Value2">Selection2</option>
<option value="Value3">Selection3</option>
</select>
<label id="IdOne" for="input1">MeAndMyInputAreInvisibleByDesign</label>
<input id="IdTwo" name="input1" type="text">
<span id="IdThree">Im Not In display:none Mode I'm In visibility:hidden Mode. Big difference."
</span>
<input id="IdFour" name="input2" type="text" class="I have none, but I will soon. I hope" />
</form>
</html>
take a look at the select tag:
<select name="SelectBox">
<option>Make a Choice</option>
<option value="IdTwo">Selection1</option> <!-- the value should be the id of the input field -->
<option value="IdThree">Selection2</option>
<option value="IdFour">Selection3</option>
</select>
Now you must give a selector class to each element you want to show/hide:
<input id="IdTwo" name="input1" type="text" class="toggle">
<span id="IdThree" class="toggle">
Im Not In display:none Mode I'm In visibility:hidden Mode. Big difference."
</span>
<input id="IdFour" name="input2" type="text" class="toggle" />
Now look at the javascript:
jQuery(document).ready(function(){
jQuery('input[name="SelectBox"]').change(function(){
jQuery('.toggle').css({"visibility":"hidden"});//Hide all
jQuery("#" + jQuery(this).val()).css({"visibility":"visible"});
});
});
You can do something like this:
<html>
<form id="form">
<input type="text" id="IdOne" class="toggle" />
<input type="text" id="IdTwo" class="toggle" />
<input type="text" id="IdThree" class="toggle" />
<select name="SelectBox" id="selectBox">
<option value="0">Make a Choice</option>
<option value="IdOne">First element</option>
<option value="IdTwo">Second element</option>
<option value="IdThree">Third element</option>
</select>
</html>
this in javascript:
jQuery(document).ready(function(){
jQuery("#selectBox").change(function(){
jQuery(".toggle").hide();
jQuery("#" + jQuery(this).val()).show();
});
});

Categories

Resources