Hiding and showing html elements with radio button and javascript style=none - javascript

I am trying to write a function that will show or hide an html element (contained in a div) using javascript. Right now I have 3 radio buttons (to eventually show/hide 3 elements depending on radio button selected, but right now I am just trying to hide one element (month) if year or week is selected, and to show it if month is selected. My html is:
<div id="setting">
<input type="radio" id="year" name="view" value="year"> year<br>
<input type="radio" id="month" name="view" value="month"> month<br>
<input type="radio" id="week" name="view" value="week"> week
</div>
<div id="cal">
(element here I am trying to show/hide)
</div>
My javascript is:
function defineSetting (){
var setting = document.getElementById('setting').checked;
if(setting =='year'){
document.getElementById("cal").style.display = "none";
}else if(setting =='month'){
document.getElementById("cal").style.display = "unset";
}else if(setting =='week'){
document.getElementById("cal").style.display = "none";
}
}
I am also not super experienced with javascript and am trying to figure out how to call the function (if it works). If it is in the document ready function will it run when the page is loaded or do i need to call it somewhere.

I think this is what you're going for. You want to add an event listener to the buttons, and pass the value of the input that's checked to the defineSetting() function that hides/shows your #cal element. I also simplified your test in defineSetting()
<div id="setting">
<input type="radio" id="year" name="view" value="year" class="setting"> year<br>
<input type="radio" id="month" name="view" value="month" class="setting"> month<br>
<input type="radio" id="week" name="view" value="week" class="setting"> week
</div>
<div id="cal">
(element here I am trying to show/hide)
</div>
<style>
.hidden { display: none; }
</style>
<script>
var inputs = document.getElementsByClassName('setting'),
setting;
for (var i = 0; i < inputs.length; i++) {
var el = inputs[i];
el.addEventListener('change', function() {
defineSetting(this.value);
})
}
function defineSetting(setting) {
if (setting == 'year' || setting == 'week') {
document.getElementById("cal").classList.add('hidden');
} else {
document.getElementById("cal").classList.remove('hidden');
}
}
</script>

This will help you out:
How to get value of selected radio button?
You are trying to get the checked value of a div element, but this element doesn't have that. The input element do have that property so that's where you can get it from.

Related

On click radio button append value to div and remove from div when another radio button is clicked

Basically, I'm trying to append a radio button value to a div on click. This works as it should, but I can't seem to clear the div when clicking another radio button.
There should only ever be 1 piece of appended data within the div.
I tried to clear the div with innerHTML before appending the value but doesn't seem to work
$('input[type="radio"]').one('click', function () {
var getVal = $(this).val();
if ($('.selections').text().length < 0) {
console.log('less than');
}
else if ($('.selections').text().length > 0){
console.log('more than');
$('.selections').innerHTML = "";
$('.selections').append(getVal);
}
console.log(getVal);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form>
<label>
<span class="radio-c">
<input type="radio" name="q1" value="Between £381K and £450K" id="between381">
Between £381K and £450K
</span>
</label>
<label>
<span class="radio-c">
<input type="radio" name="q1" value="Over £450K" id="over450">
Over £450K
</span>
</label>
</form>
<div class="selections">
</div>
innerHTML is used when using vanilla JS. You should use text() on jQuery referenced object. You also do not need to append here.
I also believe you have mistakenly used .one(), which should be .on().
$('input[type="radio"]').on('click', function () {
var getVal = $(this).val();
if ($('.selections').text().length < 0) {
//console.log('less than');
} else if ($('.selections').text().length > 0){
//console.log('more than');
$('.selections').text(getVal);
}
//console.log(getVal);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form>
<label>
<span class="radio-c">
<input type="radio" name="q1" value="Between £381K and £450K" id="between381">
Between £381K and £450K
</span>
</label>
<label>
<span class="radio-c">
<input type="radio" name="q1" value="Over £450K" id="over450">
Over £450K
</span>
</label>
</form>
<div class="selections">
</div>

Remove div on changing the radio button

There are two radio buttons. (Javascript)Upon selecting 1st option the div class must be removed which is in another page and upon selecting 2nd option the div must be shown and this execution should happen only after clicking on submit button.
Any help highly appreciated.
<input type="radio" name="radio" id="radio1">Regular Shipping
<input type="radio" name="radio" id="radio2">COD Shopping
<input type="submit" class="btn" value="SUBMIT">
<!----------The following div is in another page------>
<div class="test">Lorem Ipusm</div>
You can try with below solution:
document.getElementById('submit').addEventListener('click', change_value);
function change_value(){
var radioOptions = document.getElementsByName('radio');
var selected = '';
for (var i = 0; i < radioOptions.length; i++) {
if (radioOptions[i].checked) {
selected = radioOptions[i].id
break;
}
}
if(selected == 'radio1'){
document.getElementsByClassName('test')[0].style.display = 'none';
} else if (selected == 'radio2'){
document.getElementsByClassName('test')[0].style.display = 'block';
} else {
alert('select option first!');
}
}
<input type="radio" name="radio" id="radio1">Regular Shipping
<input type="radio" name="radio" id="radio2">COD Shopping
<input type="submit" id='submit' class="btn" value="SUBMIT">
<!----------The following div is in another page------>
<div class="test">Lorem Ipusm</div>
In above code I just hidden/display the first element with className is 'test', incase you want to apply for all, you need a loop to do it.

.checked not identifying if a radio button is checked

I have some radio buttons on a page, and I need to just identify which one was checked in my JS, based on ID. I'm not sure why this isn't working. Each time, I get the "nothing checked" message in my console. Thanks!
HTML:
<input type="radio" id="aud1">elephant</input>
<input type="radio" id="aud2">prairie dog</input>
<input type="radio" id="aud3">tiger</input>
JS:
var aud;
if (document.getElementById('aud1').checked) {
var aud = document.getElementById('file1');
}else if(document.getElementById('aud2').checked) {
var aud = document.getElementById('file2');
}else if (document.getElementById('aud3').checked){
var aud = document.getElementById('file3');
}
else console.log('nothing checked');
See below. I've added a button to your code that you can click after you have some checked.
Initially, when the page loads, there is nothing clicked. Your JS is ran as soon as the page is built there which is why you were seeing the nothing clicked.
document.getElementById('check-radios').onclick = function() {
var aud;
if (document.getElementById('aud1').checked) {
var aud = document.getElementById('file1');
console.log('aud1 checked');
}
else if (document.getElementById('aud2').checked) {
var aud = document.getElementById('file2');
console.log('aud2 checked');
}
else if (document.getElementById('aud3').checked) {
var aud = document.getElementById('file3');
console.log('aud3 checked');
}
else console.log('nothing checked');
}
<input type="radio" id="aud1">elephant</input>
<input type="radio" id="aud2">prairie dog</input>
<input type="radio" id="aud3">tiger</input>
<button id="check-radios">Check for clicked</button>
do you explicitly need this code? why not use a single class, and have the filename/desc as a custom attribute like so:
<input type="radio" name="animals" class="order" data-animal="elephant" />elephant
<input type="radio" name="animals" class="order" data-animal="zebra" />zebra
<input type="radio" name="animals" class="order" data-animal="lion" />lion
<script>
$(".order").click(function () {
var choice = this.getAttribute("data-animal");
alert(choice);
/* console.log(choice); */
})
</script>
That way you dont have to manually keep adding more code, u can just add the html at the top using the same class and a different attribute value... much easier to maintain -
Also since you had an elseif i added a name to group them as individual radios as I presume you intended?
<input type="radio" name="animals" class="order" checked data-animal="zebra">zebra
bear in mind there is no closing tag for input tags - just /> at the end instead of >

Change an onclick value with javascript

I'm pretty new to JS and maybe this is a very banal questions but I still can't figure out what's wrong. I have this simple html code:
<span>1</span>
<input id="check1" type="radio" value="a1"/>
<span>2</span>
<input id="check2" type="radio" value="b2"/>
<span>3</span>
<input id="check3" type="radio" value="c3"/>
<span>4</span>
<input id="check4" type="radio" value="a4"/>
<span>5</span>
<input id="check5" type="radio" value="b5"/>
<input id="red" type="button" value="Go" onclick=""/>
What i would like to achieve is, based on the radio checked change the onclick property.
For example, if check1 and check2 are checked go to google.com, if check1 and check3 go to jsfiddle.net etcetera. So I wrote a simple Javascript:
window.onchange = function redirect(){
if (document.getElementById('check1').checked && document.getElementById('check2').checked) {
location.href='www.google.com';
// document.getElementById('red').onclick="www.google.com"
}
else if (document.getElementById('check1').checked && document.getElementById('check3').checked) {
location.href='www.jsfiddle.net';
// document.getElementById('red').onclick="window.open('www.jsfiddle.net')"
}
}
Here You can find a JS Fiddle.
What I thought to do was to set the onclick property like I did with an image, using getElementById and then setting his source, so I wrote document.getElementById('red').onclick="window.open('random page')" but for some reason that I can't understand it doesn't work.
Questions:
1) As you can see in my code i wrote a location.href='address' that obviously doen't wait for the user to click the button, so that's not a solution, how can I make this work?
2)Is there a way to make this piece of code more scalable? What I mean is, in the future if I want to add another radio, I would have to modify manually the code and insert another else if, I thought about something like:
var radio = document.getElementByName('radio') //not sure if this is the right getElement
for (var i=1; i<radio.lenght; i++){
if radio[i].checked{ //is this right?
for (var n=i+1; n<radio.lenght; n++){
if radio[n].checked{
document.getElementById('red').onclick="window.open('random page')"
}
}
}
Any suggestion to my code is welcome.
​
Try out this in JS Fiddle. It contains how you can listen the onclick event of a button and to get the checked value of a radio button.
HTML part:
<form action="">
<input type="radio" name="vehicle" value="Yes" id='yes'>Yes<br>
<input type="radio" name="vehicle" value="No" id='no'>No
</form>
<input id="red" type="button" value="let's go"/>
JS part:
document.getElementById('red').onclick = function() {
if (document.getElementById('yes').checked) {
alert('I have a Vehicle.');
} else if(document.getElementById('no').checked) {
alert('I don\'t have a Vehicle.');
} else {
alert('No answer.');
}
}
If you use radio buttons, and you want only one to be selectable to the user at a time you have to set the same name attribute to them.
You can also make use of the value property of radio buttons for storing the redirection URL.
Here is a more useful example for you.
HTML part:
<form action="">
<input type="radio" name='redirect' value='https://www.google.com/' id='google'>Google<br />
<input type="radio" name='redirect' value='http://www.jsfiddle.net/' id='jsFiddle'>JS Fiddle<br />
<input type="radio" name='redirect' value='https://www.facebook.com/' id='Facebook'>Facebook
</form>
<input id="red" type="button" value="let's go"/>
JS part:
document.getElementById('red').onclick = function() {
var options = document.getElementsByName('redirect'),
length = options.length,
i = 0;
for (i; i < length; i++) {
if (options[i].checked) {
window.open(options[i].value);
}
}
}
if (document.getElementById('check1').checked&&document.getElementById('check2').checked)
{
document.getElementById('red').onclick=function(){
window.location.href ='http://www.google.com';
};
}
This code binds the function to the onclick event of element with id='red'. So add a bunch of such conditions and change the onclick binding whenever any radio button is checked/unchecked.

Javascript Radiobutton Group Validation

I would like your help to develop a javascript function to validate if one of the following radiobutton group (IDType) is selected and which value is checked and view error message in (ValidationError) division in case no radio button selected ??
<td>
<div>
<span>
<input type="radio" name="IDType" id="IDType" value="IDtype1"/>
ID Type 1
<input type="radio" name="IDType" id="IDType" value="IDtype2"/>
ID Type 2
</span>
<div id="ValidationError" name="ValidationError">
</div>
</div>
</td>
Thanks for your help.....
First of all, as said my collegues, you cannot have the same id ("IDType") for both your radio buttons.
Here is a solution with javascript only, without any jquery.
<html>
<head>
<script type="text/javascript">
function Validate() {
var radios = document.getElementsByName('IDType')
for (var i = 0; i < radios.length; i++) {
if (radios[i].checked) {
alert("Selected Value = " + radios[i].value);
return true; // checked
}
};
// not checked, show error
document.getElementById('ValidationError').innerHTML = 'Error!!!';
return false;
}
</script>
</head>
<body>
<form>
<div>
<span>
<input type="radio" name="IDType" value="IDtype1"/>
ID Type 1
<input type="radio" name="IDType" value="IDtype2"/>
ID Type 2
</span>
<div id="ValidationError" name="ValidationError">
</div>
</div>
<input type="submit" value="Submit" onclick="return Validate();" />
</form>
</body>
</html>
function validateRadioButtons(){
var radio = $('input:radio[name="IDType"]:checked');
if(radio.length == 0)//no buttons selected
{
$('ValidationError').text("you haven't selected any buttons!");
return;
}
$('ValidationError').text(radio.val()+' is selected');
}
ps: in order for this to work, you should consider using unique id's for dom elements. you cannot have the same id ("IDType") for both your radio buttons.

Categories