Radio button group appears only when first one gives output - javascript

I have three radio buttons groups i want to hide the last two radio button groups which will be displayed once appropriate output from first is given.
The code:
<div class="row">
<div>
<script type="text/javascript">
function displaytxt(e) {
var valueRadio = e;
if (valueRadio == 0)
{
document.getElementById('dynamictxt').style.display = 'none';
}
else
{
document.getElementById('dynamictxt').style.display = '';
}
}
</script>
<div>
<script type="text/javascript">
function displaytxt1(e) {
var valueRadio = e;
if (valueRadio == 2) {
document.getElementById("dynamictxt1").innerHTML = "Check if the termination is for past date or future date";
}
else
{
document.getElementById("dynamictxt1").innerHTML = "Go back to the request manager for confirming the user termination date";
}
}
</script>
Is there a way to do so using java script?
Thanks in advance.

try like this
<div id="rates">
<input type="radio" id="r1" name="rate" value="Fixed Rate"> Fixed Rate
<input type="radio" id="r2" name="rate" value="Variable Rate"> Variable Rate
<input type="radio" id="r3" name="rate" value="Multi Rate" checked="checked"> Multi Rate
</div>
if (document.getElementById('r1').checked) {
rate_value = document.getElementById('r1').value;
}

I wish I could understand your question, but based on the title of your question, perhaps, this could help
<form name="form1" method="post" action="">
<p id="rad1"><input type="radio" name="rdbutton" value="radio" id="rdbutton_0">
Radio 1</p>
<p id="rad2"><input type="radio" name="rdbutton" value="radio" id="rdbutton_1">
Radio 2</p>
<p id="rad3"><input type="radio" name="rdbutton" value="radio" id="rdbutton_2">
Radio 3</p>
</form>
<script>
$('#rad1').on('click',function(){
hideSelects();
});
function hideSelects() {
$('p#rad2').hide();
$('p#rad3').hide();
};
</script>
Demo

Related

How to check if one or more checkbox in form is selected (only when div is displayed)

I need help to validate a form on submit. It should check that one of more checkboxes are selected or else display error message. I have currently got it working but the problem is the checkbox option is displayed after selecting a radio button on the form.
The code I have now still shows an error message even if the div isn't displayed which is a big issue as users haven't seen the checkbox option.
I want the checkbox error message to show ONLY if the user has selected the radio button "NO" and therefor is required to check a checkbox. If they select the radio button "YES" and this checkbox div is not displayed, then I don't want the error message on submit.
function hide() {
document.getElementById('hidden').style.display ='none';
}
function show() {
document.getElementById('hidden').style.display = 'block';
}
function validateForm() {
var checked = false;
var elements = document.getElementsByName("tick");
for (var i = 0; i < elements.length; i++) {
if (elements[i].checked) {
checked = true;
}
}
if (!checked) {
alert('You must select why you are attending!');
}
return checked;
}
<form id="form" method="post" enctype="text/plain" name="vform">
<p>This course is identified in my Work Plan and Learning Agreement</p>
<input type="radio" name="optionOne" value="yes" onclick="hide()" required> Yes<br>
<input type="radio" id="chk" name="optionOne" value="no" onclick="show()"> No<br>
<p>
<div id="hidden" style="display: none">
<p>I am attending this session because (tick all that apply) </p>
<input type="checkbox" name="tick" value="selectone"> It will help me develop the skills and knowledge required for my current role<br>
<input type="checkbox" name="tick" value="selecttwo"> It will help me develop the skills and knowledge for a possible future role/body of work <br>
<input type="checkbox" name="tick" value="selectthree"> It was identified as a need during my performance management discussions<br>
<input type="checkbox" name="tick" value="selectfour"> My manager recommended that I attend<br>
<input type="checkbox" name="tick" value="selectfive"> I am interested in the content<br>
<p>
<p>What would you like to achieve as a result of your attendance? For example, "I would like to learn to write better emails to improve my communication skills." </p>
<input type="text" id="results" name="results">
</div>
<div class="submit-button">
<button type="submit" name="submit" onclick="validateForm()" value="send">Submit</button>
</div>
</form>
try (select "No" below)
function validateForm(e) {
let inp=[...document.getElementsByName("tick")];
if(!inp.some(i=>i.checked) && chk.checked) {
e.preventDefault();
alert('You must select why you are attending!');
}
}
function validateForm(e) {
let inp=[...document.getElementsByName("tick")];
if(!inp.some(i=>i.checked) && chk.checked) {
e.preventDefault();
alert('You must select why you are attending!');
}
}
// DISPLAY HIDDEN TEXT
function hide() {
document.getElementById('hidden').style.display ='none';
}
function show() {
document.getElementById('hidden').style.display = 'block';
}
<form id="form" method="post" enctype="text/plain" name="form">
<p>This course is identified in my Work Plan and Learning Agreement</p>
<input type="radio" name="optionOne" value="yes" onclick="hide()" required> Yes<br>
<input type="radio" id="chk" name="optionOne" value="no" onclick="show()"> No<br>
<p>
<div id="hidden" style="display: none">
<p>I am attending this session because (tick all that apply) </p>
<input type="checkbox" name="tick" value="selectone"> It will help me develop the skills and knowledge required for my current role<br>
<input type="checkbox" name="tick" value="selecttwo"> It will help me develop the skills and knowledge for a possible future role/body of work <br>
<input type="checkbox" name="tick" value="selectthree"> It was identified as a need during my performance management discussions<br>
<input type="checkbox" name="tick" value="selectfour"> My manager recommended that I attend<br>
<input type="checkbox" name="tick" value="selectfive"> I am interested in the content<br>
<p>
<p>What would you like to achieve as a result of your attendance? For example, "I would like to learn to write better emails to improve my communication skills." </p>
<input type="text" id="results" name="results">
</div>
<div class="submit-button">
<button type="submit" onclick="validateForm(event)" name="submit" value="send">Submit</button>
</div>
</form>
Here's the old school way. Just check the display attribute of the div, and only set your flag to false inside that.
function validateForm() {
var checked;
if(document.getElementById("hidden").style.display == "block") {
checked = false;
var elements = document.getElementsByName("tick");
for (var i=0; i < elements.length; i++) {
if (elements[i].checked) {
checked = true;
}
}
}
if (checked===false) {
alert('You must select why you are attending!');
}
return checked;
}

Validating Multiple Radio Button Groups in Vanilla JS

I am trying to validate multiple groups of radio buttons with pureJS. Basically my client has a group of around 50 questions, and each one has 4 radio buttons that can be used to pick 1 of 4 answers.
They do not want to use jQuery, but pureJS, I have gotten the following to work when there is just one question, but not when there is multiples, any help would be appreciated.
document.getElementById("submit_btn").addEventListener("click", function(event){
var all_answered = true;
var inputRadios = document.querySelectorAll("input[type=radio]")
for(var i = 0; i < inputRadios.length; i++) {
var name = inputRadios[i].getAttribute("name");
if (document.getElementsByName(name)[i].checked) {
return true;
var all_answered = true;
} else {
var all_answered = false;
}
}
if (!all_answered) {
alert("Some questiones were not answered. Please check all questions and select an option.");
event.preventDefault();
}
});
The questions are all laid out like this -
<div class="each-question">
<div class="unanswered-question">
<div class="question-text">
<div class="number">33</div>
<div class="text">
<p>Troubleshoot technology issues.</p>
</div>
</div>
<div class="options" id="ans_285">
<div class="radio-button">
<input type="radio" value="3" id="ans33op1" name="ans_285">
<label for="ans33op1" class="radio-label">Very Interested</label>
</div>
<div class="radio-button">
<input type="radio" value="2" id="ans33op2" name="ans_285">
<label for="ans33op2" class="radio-label">Interested</label>
</div>
<div class="radio-button">
<input type="radio" value="1" id="ans33op3" name="ans_285" class="custom">
<label for="ans33op3" class="radio-label"> Slightly Interested</label>
</div>
<div class="radio-button">
<input type="radio" value="0" id="ans33op4" name="ans_285">
<label for="ans33op4" class="radio-label"> Not Interested</label>
</div>
</div>
</div>
This is the original jQuery used by the client which now has to be in pureJS
jQuery(document).ready(function () {
jQuery("#question_list").submit(function () {
var all_answered = true;
jQuery("input:radio").each(function () {
var name = jQuery(this).attr("name");
if (jQuery("input:radio[name=" + name + "]:checked").length == 0) {
all_answered = false;
}
});
if (!all_answered) {
alert("Some questiones were not answered. Please check all questions and select an option.");
return false;
}
});
});
Not sure if it's just an issue with the copy, but you have a return true in your for loop which will cause the entire function to simply return true if just one is answered. Removing that would help.
Ignoring that though, your solution is a bit unwieldy, as it'll loop through every single input on the page individually and will mark it false if not every radio button is unchecked.
Here is a different approach. Basically, get all of the radio buttons, then group them into arrays by question. Then, loop through each of those arrays and check that within each group, at least one is answered.
document.querySelector('form').addEventListener('submit', e => {
// Get all radio buttons, convert to an array.
const radios = Array.prototype.slice.call(document.querySelectorAll('input[type=radio]'));
// Reduce to get an array of radio button sets
const questions = Object.values(radios.reduce((result, el) =>
Object.assign(result, { [el.name]: (result[el.name] || []).concat(el) }), {}));
// Loop through each question, looking for any that aren't answered.
const hasUnanswered = questions.some(question => !question.some(el => el.checked));
if (hasUnanswered) {
console.log('Some unanswered');
} else {
console.log('All set');
}
e.preventDefault(); // just for demo purposes... normally, just put this in the hasUnanswered part
});
<form action="#">
<div>
<label><input type="radio" name="a" /> A</label>
<label><input type="radio" name="a" /> B</label>
<label><input type="radio" name="a" /> C</label>
<label><input type="radio" name="a" /> D</label>
</div>
<div>
<label><input type="radio" name="b" /> A</label>
<label><input type="radio" name="b" /> B</label>
<label><input type="radio" name="b" /> C</label>
<label><input type="radio" name="b" /> D</label>
</div>
<button type="submit">Submit</button>
</form>
First up, I get all of the radio buttons that have a type of radio (that way if there are others, I won't bother with them).
Then, I turn the NodeList returned by querySelectorAll() into an Array by using Array.prototype.slice.call() and giving it my NodeList.
After that, I use reduce() to group the questions together. I make it an array with the element's name as the key (since I know that's how they have to be grouped). After the reduce, since I don't really care about it being an object with the key, I use Object.values() just to get the arrays.
After that, I use some() over the set of questions. If that returns true, it'll mean I have at least one unanswered question.
Finally, inside that some(), I do another over the individual radio buttons of the question. For this, I want to return !some() because if there isn't at least one that is answered, then I should return true overall (that I have at least one question not answered).
The above is a bit verbose. This one is a bit more concise and is what I would likely use in my own code:
document.querySelector('form').addEventListener('submit', e => {
if (Object.values(
Array.prototype.reduce.call(
document.querySelectorAll('input[type=radio]'),
(result, el) =>
Object.assign(result, { [el.name]: (result[el.name] || []).concat(el) }),
{}
)
).some(q => !q.some(el => el.checked))) {
e.preventDefault();
console.log('Some questions not answered');
}
});
<form action="#">
<div>
<label><input type="radio" name="a" /> A</label>
<label><input type="radio" name="a" /> B</label>
<label><input type="radio" name="a" /> C</label>
<label><input type="radio" name="a" /> D</label>
</div>
<div>
<label><input type="radio" name="b" /> A</label>
<label><input type="radio" name="b" /> B</label>
<label><input type="radio" name="b" /> C</label>
<label><input type="radio" name="b" /> D</label>
</div>
<button type="submit">Submit</button>
</form>
Everything inside your for clause makes absolutely no sense. Here's why:
Since you already have inputRadios, there is no point and getting their name and then using that to get the elements by name, because you already have them.
Since you use return true, the function exits and everything beyond that is disregarded.
Instead of updating the existent all_answered variable you create a new, local one that will be lost once the current iteration ends.
What you should do:
Instead of getting all inputs, get all answers, the div.options elements that contain the inputs for each answer, and iterate over those.
Then, use the id of the answer, because it's the same as the name of the inputs, to get the related inputs.
Use some to ensure that there is a checked input among the group. Then, check whether there isn't and stop the loop. You've found an unanswered question.
Snippet:
document.getElementById("submit_btn").addEventListener("click", function(event) {
var
/* Create a flag set by default to true. */
all_answered = true,
/* Get all answers. */
answers = document.querySelectorAll(".options[id ^= ans_]");
/* Iterate over every answer. */
for (var i = 0; i < answers.length; i++) {
var
/* Use the id of the answer to get its radiobuttons. */
radios = document.querySelectorAll("[name = " + answers[i].id + "]"),
/* Save whether there is a checked input for the answer. */
hasChecked = [].some.call(radios, function(radio) {
return radio.checked;
});
/* Check whether there is a checked input for the answer or not. */
if (!hasChecked) {
/* Set the all_answered flag to false and break the loop. */
all_answered = false;
break;
}
}
/* Check whether not all answers have been answered. */
if (!all_answered) {
console.log("Some questions were not answered...");
} else {
console.log("All questions are answered!");
}
});
.question { display: inline-block }
<div class="question">
<div class="text">
<p>Troubleshoot technology issues.</p>
</div>
<div class="options" id="ans_285">
<div class="radio-button">
<input type="radio" value="3" id="ans33op1" name="ans_285">
<label for="ans33op1" class="radio-label">Very Interested</label>
</div>
<div class="radio-button">
<input type="radio" value="2" id="ans33op2" name="ans_285">
<label for="ans33op2" class="radio-label">Interested</label>
</div>
<div class="radio-button">
<input type="radio" value="1" id="ans33op3" name="ans_285" class="custom">
<label for="ans33op3" class="radio-label">Slightly Interested</label>
</div>
<div class="radio-button">
<input type="radio" value="0" id="ans33op4" name="ans_285">
<label for="ans33op4" class="radio-label">Not Interested</label>
</div>
</div>
</div>
<div class="question">
<div class="text">
<p>Troubleshoot technology issues.</p>
</div>
<div class="options" id="ans_286">
<div class="radio-button">
<input type="radio" value="3" id="ans34op1" name="ans_286">
<label for="ans34op1" class="radio-label">Very Interested</label>
</div>
<div class="radio-button">
<input type="radio" value="2" id="ans34op2" name="ans_286">
<label for="ans34op2" class="radio-label">Interested</label>
</div>
<div class="radio-button">
<input type="radio" value="1" id="ans34op3" name="ans_286" class="custom">
<label for="ans34op3" class="radio-label">Slightly Interested</label>
</div>
<div class="radio-button">
<input type="radio" value="0" id="ans34op4" name="ans_286">
<label for="ans34op4" class="radio-label">Not Interested</label>
</div>
</div>
</div>
<div class="question">
<div class="text">
<p>Troubleshoot technology issues.</p>
</div>
<div class="options" id="ans_287">
<div class="radio-button">
<input type="radio" value="3" id="ans35op1" name="ans_287">
<label for="ans35op1" class="radio-label">Very Interested</label>
</div>
<div class="radio-button">
<input type="radio" value="2" id="ans35op2" name="ans_287">
<label for="ans35op2" class="radio-label">Interested</label>
</div>
<div class="radio-button">
<input type="radio" value="1" id="ans35op3" name="ans_287" class="custom">
<label for="ans35op3" class="radio-label">Slightly Interested</label>
</div>
<div class="radio-button">
<input type="radio" value="0" id="ans35op4" name="ans_287">
<label for="ans35op4" class="radio-label">Not Interested</label>
</div>
</div>
</div>
<button id="submit_btn">Submit</button>
The following is a simplified version, but there should be enough code to get you heading in the right direction.
var answer = [];
function checkAnswerCount(e) {
// for the answer ids
var i = 0, max = answer.length;
// for the radios
var j = 0; rMax = 0;
// And a few extras
var tmp = null, answerCount = 0;
for(;i<max;i++) {
tmp = document.getElementsByName(answer[i]);
rMax = tmp.length;
for(j=0;j<rMax;j++) {
if (tmp[j].checked) {
answerCount++;
break;
}
}
}
if (answerCount == answer.length) {
console.log("All questions have an answer, submit the form");
} else {
console.log("You need to answer all the questions");
}
}
window.onload = function() {
// each answer block is surrounded by the "options" class,
// so we use that to collect the ids of the raido groups
var a = document.querySelectorAll(".options");
var i = 0, max = a.length;
for(;i<max;i++) {
answer.push(a[i].id);
}
// And we want to check if all the answers have been answered
// when the user tries to submit...
var s = document.getElementById("submitAnswers");
if (s) {
s.addEventListener("click",checkAnswerCount,false);
}
}
<p>Question 1.</p>
<div class="options" id="ans_1">
<label><input type="radio" name="ans_1" value="a1_1" /> Answer 1, op1</label>
<label><input type="radio" name="ans_1" value="a1_2" /> Answer 1, op2</label>
</div>
<p>Question 2.</p>
<div class="options" id="ans_2">
<label><input type="radio" name="ans_2" value="a2_1" /> Answer 2, op1</label>
<label><input type="radio" name="ans_2" value="a2_2" /> Answer 2, op2</label>
</div>
<p>Question 3.</p>
<div class="options" id="ans_3">
<label><input type="radio" name="ans_3" value="a3_1" /> Answer 3, op1</label>
<label><input type="radio" name="ans_3" value="a3_2" /> Answer 3, op2</label>
</div>
<button id="submitAnswers">Submit / check</button>

Redirect form based on radio selection

So, i have a form with 3 radio buttons. Depending on which option the user selects (he can only choose one), there can be 3 situations:
if he selects the first one, when he submits the form, he gets redirected to a new URL.
if he selects the second one, a div appears (and then disappears).
if he selects the third one, a div appears (different from the previous one), and then it also disappears.
My HTML:
<form>
<div class="radio">
<label><input type="radio" name="paypal" value="paypal"</label>
</div>
<div class="radio">
<label><input type="radio" name="money" value="money"></label>
</div>
<div class="radio">
<label><input type="radio" name="mastercard" value="mastercard"></label>
</div>
</form>
<button type="button" id="button1" name="button">Check</button>
My JQuery:
$('#button1').click(function() {
var value = $(this).val();
if (value == 'paypal') {
window.location.assign("http://www.paypal.com");
}
else if (value == 'money') {
$('.div2').show('slow');
$('.div2').fadeOut(4000);
}
}
else if (value == 'mastercard') {
$('.div1').show('slow');
$('.div1').fadeOut(4000);
}
But something is not working in here, and I can't figure out what or where.
EDIT: No error, the JQuery code just doesn't work. Whatever option I choose, when I submit nothing happens.
By using var value = $(this).val(); inside the button click, you are actually taking the value of the button itself which is not you are intending to do.
Make all radio button name same. Try the following code:
$('#button1').click(function() {
var value = $('input[name=myRadio]:checked').val();
if (value == 'paypal') {
console.log(value);
window.location.assign("http://www.paypal.com");
}
else if (value == 'money') {
console.log(value);
$('.div2').show('slow');
$('.div2').fadeOut(4000);
}
else if (value == 'mastercard') {
console.log(value);
$('.div1').show('slow');
$('.div1').fadeOut(4000);
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form>
<div class="radio">
<label><input type="radio" name="myRadio" value="paypal">Pay Pal</label>
</div>
<div class="radio">
<label><input type="radio" name="myRadio" value="money">Money</label>
</div>
<div class="radio">
<label><input type="radio" name="myRadio" value="mastercard">Master Card</label>
</div>
</form>
<button type="button" id="button1" name="button">Check</button>
I would suggest using submit button along with the submit form event like below to make it work exactly as you like, and group the radio buttons by assigning similar names, and try to reduce the if else and make it more readable like the code below
let formEvents = {
paypal: function() {
console.log('redirecting');
//uncomment the following line when you use it in your script
//window.location.assign("http://www.paypal.com");
},
money: function() {
$('.div2').show('slow', function() {
setTimeout("$('.div2').fadeOut(4000)", 500);
});
},
mastercard: function() {
$('.div1').show('slow', function() {
$('.div1').fadeOut(4000);
});
}
}
$('form').on('submit', function(e) {
e.preventDefault();
var value = $(this).find('input:radio:checked').val();
if (formEvents.hasOwnProperty(value)) {
formEvents[value].call(this);
}
});
.div1,
.div2 {
display: none;
background: #c8c8c8;
border: 2px dashed #000;
text-align: center;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form>
<div class="radio">
<label><input type="radio" name="selection" value="paypal">paypal</label>
</div>
<div class="radio">
<label><input type="radio" name="selection" value="money">money</label>
</div>
<div class="radio">
<label><input type="radio" name="selection" value="mastercard">mastercard</label>
</div>
<button type="submit" id="button1" name="button">Check</button>
</form>
<div class="div1">div 1</div>
<div class="div2">div 2</div>

How to grey out other radio buttons after one is selected until refresh

Hopefully somebody can prompt me into the right direction,
I want a simple 3 radio button form, lets say 1,2,3
once 1 has been selected i want to disable options 2 and 3 until page has been refreshed
so maybe those option would grey out and not be selectable
any help appreciated cant find a thing on google
We will group radio buttons in a div:
<div class="readioBtnDiv">
<input type="radio" name="group1" value="1" />1
</div>
<div class="readioBtnDiv">
<input type="radio" name="group2" value="1" />2
</div>
<div class="readioBtnDiv">
<input type="radio" name="group3" value="1" />3
</div>
Now we will disable another radio button when one is selected:
$("input:radio").click(function() {
var $this = $(this);
var value = $this.val();
$this.closest('.readioBtnDiv')
.siblings('.readioBtnDiv')
.find('input:radio[value="' + value + '"]')
.attr("disabled","disabled");
});
Here we go, jQuery way:
HTML:
<form>
<input type="radio" value="1"> 1
<input type="radio" value="2"> 2
<input type="radio" value="3"> 3
</form>
JS:
<script>
$('input').on('click', function() {
$(this).parent().find('input:not(:checked)').attr( "disabled", "disabled" );
})
</script>
To add jQuery to your project - simply insert
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.0/jquery.min.js"></script>
inside your <head> </head> tag.
UPDATE:
To keep it after page refreshes you should modify your code to this:
<form>
<input type="radio" value="1" id="radio1"> 1
<input type="radio" value="2" id="radio2"> 2
<input type="radio" value="3" id="radio3"> 3
</form>
<script>
$('#'+localStorage.selected).trigger('click');
$('#'+localStorage.selected).parent().find('input:not(:checked)').attr( "disabled", "disabled" );
$('input').on('click', function() {
$(this).parent().find('input:not(:checked)').attr( "disabled", "disabled" );
localStorage.setItem('selected', $(this).attr('id'));
})
</script>
I think all the answers are right and accurate to your question above but according to me you would find this answer more useful and understandable if you are newbie
<!DOCTYPE html>
<html>
<head>
<script src="http://code.jquery.com/jquery-1.9.1.min.js"></script>
<script>
function myFunction1() {
document.getElementById("radio2").disabled = true;
document.getElementById("radio3").disabled = true;
}
function myFunction2() {
document.getElementById("radio1").disabled = true;
document.getElementById("radio3").disabled = true;
}
function myFunction3() {
document.getElementById("radio2").disabled = true;
document.getElementById("radio1").disabled = true;
}
</script>
</head>
<body>
<div class="block">
<input onclick="myFunction1();" type="radio" id="radio1" value="Radio1" /><label>Radio1</label>
<input onclick="myFunction2();" type="radio" id="radio2" value="Radio2" /><label>Radio2</label>
<input onclick="myFunction3();" type="radio" id="radio3" value="radio3" /><label>radio3</label>
</div>
</body>
</html>
It's a working example according to your need. Cheers :)

Hide and Show radio buttons with checkbox

Basically i'd like hide and show the radio buttons if the checkbox is checked or not, but with some conditions.
The first radio button needs to be checked by default even if hidden once the checkbox has been checked.
If the checkbox has been checked then show all the radio buttons and the user can choose another radio button if necessary.
But, if the checkbox is unchecked, set the radio button back to the first checked by default and hide all the radio buttons.
I tried to modify some solutions that i found, but without success :(
My HTML:
<input name="featured_ad" value="1" type="checkbox">condition</input>
<div class="buttons">
<input type="radio" name="ad_pack_id" value="497649">value 1<br>
<input type="radio" name="ad_pack_id" value="497648">value 2<br>
<input type="radio" name="ad_pack_id" value="497647">value 3<br>
</div>
Thanks a lot!
As we discussed does this work for you?
HTML:
<input name="featured_ad" value="1" type="checkbox" onclick="resetradio(this)">condition
<div class="buttons">
<input type="radio" name="ad_pack_id" value="497649" onclick="setcheckbox()">value 1<br>
<input type="radio" name="ad_pack_id" value="497648" onclick="setcheckbox()">value 2<br>
<input type="radio" name="ad_pack_id" value="497647" onclick="setcheckbox()">value 3<br>
</div>
JS:
function resetradio (checkbox) {
var buttons = document.querySelector('.buttons');
var radios = document.getElementsByName('ad_pack_id');
radios[0].checked = true;
if (checkbox.checked == true) {
buttons.style.display = 'block';
}
else {
buttons.style.display = 'none';
}
}
function setcheckbox () {
var checkbox = document.getElementsByName('featured_ad')[0];
if (checkbox.checked == false) {
checkbox.checked = true;
}
}
CSS:
.buttons {
display: none;
}
Fiddle: http://jsfiddle.net/dgqn5fc4/1/
You've got a few issues here. First of all, you need to make sure you close your input tags:
<input name="featured_ad" value="1" type="checkbox">condition</input>
<div class="buttons">
<input type="radio" name="ad_pack_id" value="497649">value 1</input>
<input type="radio" name="ad_pack_id" value="497648">value 2</input>
<input type="radio" name="ad_pack_id" value="497647">value 3</input>
</div>
You can then check your default radio button right in the html by adding checked="checked" to the appropriate radio element.
<div class="buttons">
<input type="radio" checked="checked" name="ad_pack_id" value="497649">value 1</input>
<input type="radio" name="ad_pack_id" value="497648">value 2</input>
<input type="radio" name="ad_pack_id" value="497647">value 3</input>
</div>
You can hide your radio buttons by default in your CSS:
.buttons {
display: none;
}
Then, you can show them using jQuery, and do your selections based on your condition:
$(document).ready(function(){
$("input[name='featured_ad']").on("change", function(){
var isChecked = $(this).prop("checked");
if(isChecked){
$(".buttons").show();
} else {
$(".buttons").hide();
$("input[name='ad_pack_id'][value='497649']").prop("checked", "checked");
}
});
});
Edit:
Here is a fiddle: http://jsfiddle.net/8q94Lvbo/
Do the following.
$('[name="featured_ad"]').on('change', function(){
var $first = $('[name="ad_pack_id"]').first();
var $rest = $('[name="ad_pack_id"]').slice(1);
if( $(this).is(':checked') ){
$first.prop('checked',true);
$first
.closest('span')
.hide();
$rest.prop({
'checked':false,
'disabled':false
});
} else {
$first
.closest('span')
.show();
$first.prop('checked',true);
$rest.prop({
'checked':false,
'disabled':true
});
}
}).change();
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script>
<input name="featured_ad" value="1" type="checkbox">condition
<div class="buttons">
<span><input type="radio" name="ad_pack_id" value="497649">value 1</span><br/>
<span><input type="radio" name="ad_pack_id" value="497648">value 2</span><br/>
<span><input type="radio" name="ad_pack_id" value="497647">value 3</span><br/>
</div>
You have to pass arguments to javaScript in quotes like onclick="Show_Div('Div_1')" not like onclick="Show_Div(Div_1)".
And for others requirement you can check the following html
<input type="checkbox" id="check" onclick="checkFun();"/>Your CheckBox<br/>
<img src="http://icons.iconarchive.com/icons/paomedia/small-n-flat/1024/flower-icon.png" alt="" onclick="Show_Div('Div_1')" width="100px">
<p>
<input id="radio1" type="radio" onclick="Show_Div('Div_1')" class="cb1" onchange="cbChange1(this)" checked="checked"/>Flower 1</p>
<div id="Div_1" style="display: none;">
Flower is pink.
</div>
<br/>
<br/>
<img src="http://www.clker.com/cliparts/0/d/w/v/V/p/pink-flower-md.png" alt="" onclick="Show_Div('Div_2')" width="100px">
<p>
<input type="radio" id="radio2" onclick="Show_Div('Div_2')" class="cb1" onchange="cbChange1(this)" disabled >Flower 2</p>
<div id="Div_2" style="display: none;">
Flower is orange.
</div>
You can apply following simple JS and jQuery to achive your goal
function checkFun(){
console.log("click");
var ch=$("#check");
if(ch.is(':checked')){
$("#radio2").attr("disabled",false);
}else{
$("#radio1").prop("checked", true);
$("#radio2").prop("checked", false);
$("#radio2").attr("disabled",true);
}
}
function Show_Div(Div_id) {
if(Div_id=="Div_1"){
$("#Div_1").show();
$("#Div_2").hide();
}else{
$("#Div_2").show();
$("#Div_1").hide();
}
}
function cbChange1(obj) {
var cb1 = document.getElementsByClassName("cb1");
for (var i = 0; i < cb1.length; i++) {
cb1[i].checked = false;
}
obj.checked = true;
}

Categories