I have 2 radio button with 2 group.
The structure is like this
Main Radio 1
Main Radio 2
Under Main Radio 2, there's two more sub radio button.
Main Radio 1
Main Radio 2
Sub Radio 1
Sub Radio 2
What am I doing is, in default stage, it will only show Main Radio 1 and Main Radio 2 button. When choose Main Radio 2, two sub radio button of Main Radio 2 appear.
When choose back to Main Radio 1, it will hide the list of Main Radio 2.
The one that I want to achieve is,
When click Main Radio 1, the selection that I made for Sub Radio 1 or Sub Radio 2, want to be uncheck / reset too.
I tried with this javascript, but no success.
document.getElementById("subradiobuttons").reset();
Please kindly help me the solutions. Thank you.
With Regards,
I think the best approach for a simple task like this does not needs a full JavaScript library like jQuery.
document.getElementById("main2").addEventListener("click", function()
{
document.getElementById("subCheckButtons").style.opacity = 1;
}, false);
document.getElementById("main1").addEventListener("click", function()
{
document.getElementById("subCheckButtons").style.opacity = 0;
document.getElementById("sub1").checked = false;
document.getElementById("sub2").checked = false;
}, false);
<input type="radio" id="main1" name="main" />
<input type="radio" id="main2" name="main" />
<div id="subCheckButtons" style="opacity:0;">
<input type="radio" id="sub1" name="sub" class="subCheck" />
<input type="radio" id="sub2" name="sub" class="subCheck" />
</div>
Or see the fiddle.
Here is another approach that will reset all inputs to their default position if someone clicks on "Main Radio 1."
//Clear all inputs.
function clearInputs(form) {
"use strict";
//Gather all inputs within selected form.
const inputs = form.querySelectorAll("input");
//Clear the inputs.
inputs.forEach(function (input) {
if (input.hasAttribute("checked") === true) {
input.checked = true;
} else {
input.checked = false;
}
});
}
//Monitor "Main Radio 1" for clicks.
function monitorMainRadio1() {
"use strict";
const form = document.getElementById("form");
const mainRadio1 = document.getElementById("main-radio1");
mainRadio1.addEventListener("click", function () {
clearInputs(form);
});
}
//Invoke the monitorMainRadio1 function.
monitorMainRadio1();
Not tested this but...
<input type="radio" onclick="document.getElementById("subradiobuttons").Checked = false;" />
Or you could call a Javascript function to do a bit more work/logic
This page has what you need
It is much, much quicker to do this with jQuery than JavaScript. I recommend you do something like this;
Give the radio boxes something like this
<input type="radio" name="main1">
<input type="radio" name="main2">
<input type="radio" name="sub">
<input type="radio" name="sub">
Then with jQuery you can do this
$('input[name=main1]').on('click', function() {
$('input[name=sub]').attr('checked', false);
});
I've assumed here that you've figured out a way to hide the sub radio buttons.
See a fiddle of this here
Also, make sure that you include jQuery at the top of the <script></script> tags containing this code.
script src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"
Reset the radiobutton or RadiobuttonList in the form:
private void ResetFormControlValues(Control parent)
{
foreach (Control c in parent.Controls)
{
if (c.Controls.Count > 0)
{
ResetFormControlValues(c);
}
else
{
switch ((c.GetType().ToString()))
{
case "System.Web.UI.WebControls.TextBox":
((TextBox)c).Text = "";
break;
case "System.Web.UI.WebControls.CheckBox":
((CheckBox)c).Checked = false;
break;
case "System.Web.UI.WebControls.RadioButton":
((RadioButton)c).Checked = false;
break;
case "System.Web.UI.WebControls.DropDownList":
((DropDownList)c).SelectedIndex = 0;
break;
}
}
}
}
Related
How do I deal with this behaviour:
Relevant HTML:
<p>
Player 1: <input type="text" name="player1Name">
<input type="radio" name="option1" value="X" id='option1X'/> X
<input type="radio" name="option1" value="O" id='option1O' /> O
</p>
<p>
Player 2: <input type="text" name="player2Name">
<input type="radio" name="option2" value="X" id='option2X' /> X
<input type="radio" name="option2" value="O" id='option2O'/> O
</p>
Here's what I have tried:
const option2X = document.getElementById('option2X');
const option2O = document.getElementById('option2O');
const option1X = document.getElementById('option1X');
const option1O = document.getElementById('option1O');
function checkRadios(option1, option2, option3) {
option1.addEventListener('click', function () {
if(option1.checked && option2.checked)
option3.setAttribute('checked', 'true');
});
}
checkRadios(option1X, option2X, option2O);
checkRadios(option1O, option2O, option2X);
checkRadios(option2X, option1X, option1O);
checkRadios(option2O, option1O, option1X);
This works for the first time and then it stops working.
I checked the debugger, and the reason is that option3's value changes somehow.
Player1's radios are option1X and option1O.
What I want:
If an option is clicked by user A and the same option has already been taken by another user (B), then the other user's (B's) radio should change.
I tried changing the 'click' event to 'change' and that also didn't work.
Is this what you want?
I have used addEventListener method for calling a function that checks another radio button. There exists no need for clearing selected checkbox. This is because as soon as you check one radio button out of the two, other automatically gets deselected.
I have also used a function to check if both the two options are selected or not. If they are not, null is returned and then nothing happens. But if both of them are selected, manipulation of selected radio button takes place.
const option2X = document.getElementById('option2X');
const option2O = document.getElementById('option2O');
const option1X = document.getElementById('option1X');
const option1O = document.getElementById('option1O');
check = () => document.querySelector('input[name="option1"]:checked') && document.querySelector('input[name="option2"]:checked');
option1X.addEventListener("change", function() {if (check()) option2O.checked = true});
option2X.addEventListener("change", function() {if (check()) option1O.checked = true});
option1O.addEventListener("change", function() {if (check()) option2X.checked = true});
option2O.addEventListener("change", function() {if (check()) option1X.checked = true});
Note: This starts working from MS Edge 12. For lower versions, change the check function to
function check() {
return document.querySelector('input[name="option1"]:checked') && document.querySelector('input[name="option2"]:checked');
}
You may simply allow only the first player to choose the letter.
Anyway, you can simply change the checked property of the radio buttons:
switch (player1.choice) {
case "X":
player2RadioX.checked = false;
player2RadioX.enabled = false;
player2RadioO.checked = true;
player2RadioO.enabled = true;
break;
case "O":
player2RadioO.checked = false;
player2RadioO.enabled = false;
player2RadioX.checked = true;
player2RadioX.enabled = true;
break;
}
I've got the following jQuery script correctly displaying and checking two hidden checkboxes. The only problem is that I'm trying to hide both of these checkboxes but when I uncheck my visible checkbox they remain checked?
<input type="checkbox" name="JobType[]" class="visiChk" id="nineteen" value="19" <?php echo (isset($_GET["JobType"]) && !empty($_GET["JobType"]) && in_array("19", $_GET["JobType"])) ? "checked": ""; ?> /> Plumbing
<label id="hiddenLabel" style="display:none">
<input type="checkbox" name="JobType[]" class="visiChk" id="seventeen" value="17" <?php echo (isset($_GET["JobType"]) && !empty($_GET["JobType"]) && in_array("17", $_GET["JobType"])) ? "checked": ""; ?> /> Plumbing
<input type="checkbox" name="JobType[]" class="visiChk" id="eighteen" value="18" <?php echo (isset($_GET["JobType"]) && !empty($_GET["JobType"]) && in_array("18", $_GET["JobType"])) ? "checked": ""; ?> /> Plumbing
</label>
<script>
// update if any are checked/unchecked
$('.visiChk').change(function() {
var hiddenLabel = $('#hiddenLabel')[0];
var seventeen = $('#seventeen')[0];
var eighteen = $('#eighteen')[0];
// Are any of them checked ?
if ($('.visiChk:checked').length > 0) {
hiddenLabel.style.display = 'block';
seventeen.checked = true;
eighteen.checked = true;
} else {
hiddenLabel.style.display = 'none';
seventeen.checked = false;
eighteen.checked = false;
}
});</script>
There's a logical error occurring here that might not be readily obvious with the hidden fields. When you are checking to see if any of the checkboxes are marked, you're checking all of them, even the hidden ones.
So, walk through the cycle once more. The page loads, no checkboxes have been checked. A user checks the visible one. All three are checked. The user then unchecks only the visible one. Your logic check here
if ($('.visiChk:checked').length > 0) {
is looking at all three of them. Are there any checked? Yes, the two hidden ones still are! So, all three will be set to checked again. You'll need a way to only look at the visible checkbox and then update the invisible ones accordingly. A unique ID or different class would work well.
I wrote up an example jsfiddle that helps to illustrate what's going on. Instead of hiding the checkboxes, I set the font color to grey to show which ones should actually be hidden.
https://jsfiddle.net/sm1215/d9geaog4/1/
Edit: Also, I set up a console log to show the result of the logic check going on. When the page first loads (no checkboxes are checked) and the user checks one, it evaluates to 1. Uncheck the visible one, and it evaluates to 2 - showing the 2 hidden checkboxes are still being counted.
Edit 2: Here's the code from the jsfiddle for reference in case the fiddle is ever lost.
HTML
<input type="checkbox" name="JobType[]" id="nineteen" class="visiChk" value="19" /> Plumbing
<label id="hiddenLabel" style="color:silver; /*display:none*/">
<input type="checkbox" name="JobType[]" class="visiChk" id="seventeen" value="17" /> Plumbing
<input type="checkbox" name="JobType[]" class="visiChk" id="eighteen" value="18" /> Plumbing
</label>
JS
// update if any are checked/unchecked
$('.visiChk').change(function() {
var hiddenLabel = $('#hiddenLabel')[0];
var seventeen = $('#seventeen')[0];
var eighteen = $('#eighteen')[0];
// Are any of them checked ?
console.log($('#nineteen:checked').length);
if ($('#nineteen:checked').length > 0) {
hiddenLabel.style.display = 'block';
seventeen.checked = true;
eighteen.checked = true;
} else {
// Commenting this out so the hidden fields stay visible for demo purposes
//hiddenLabel.style.display = 'none';
seventeen.checked = false;
eighteen.checked = false;
}
});
I have a problem with validating the form in function validate() method. This line of code:
if(radios[i].value == "yes" && radios[i].checked == true) //DEBUG INFO: skips this step to else.
is being skipped because one or both of the conditions are false, but I'm not sure which one and as well as if the condition is proper to execute. I was thinking that radios[i].value == "yes" will correspond to the value attribute of that input radio button (In other words, the correct answer regarding that question).
When the submit button is clicked, I simply want javascript to tell me whether it's correct or not and to check if the radio button is checked.
Problem: I checked in the radio button, when submit button is clicked the alert for Please make sure you answer every question pops up 3 times and after that displays that I have the correct answer.
Here's the full code:
JavaScript:
// called when "Take Quiz" button is clicked
function takeQuiz()
{
// hide the intro
document.getElementById('intro').style.display = 'none';
// display the quiz
document.getElementById('message').style.overflow = 'auto';
document.getElementById('quiz').style.visibility = 'visible';
document.getElementById('gl_banner').style.display = 'block';
document.getElementById('gl_banner').style.visibility = 'visible';
}
//document.getElementById('submit').onclick = validateQuiz; //calls the function "validateQuiz" when submit button is clicked
// check for validation in the quiz
function validateQuiz()
{
var radios; // access elements by object name (DOM)
var i; // int variable
var right; // boolean variable to determine correct answer
radios = document.getElementById('question1').getElementsByTagName('input');
/*radios = document.getElementById('question2').getElementsByTagName('input');
radios = document.getElementById('question3').getElementsByTagName('input');
radios = document.getElementById('question4').getElementsByTagName('input');
radios = document.getElementById('question5').getElementsByTagName('input');*/
right = true;
// loop to check each radio button for validation
for(i = 0; i < radios.length; i++)
{
if(radios[i].value == "yes" && radios[i].checked == true) //DEBUG INFO: skips this step to else.
{
right = true;
}
else if(radios[i].checked == false)
{
right = false;
alert("Please check to make sure you have answered every question.");
}
}
if(right)
{
alert("You have answered correctly!");
}
else
{
alert("Wrong answer");
}
}
HTML Code:
<div id="message" style="overflow:hidden;"><div id="intro">Why not go ahead and take the quiz to test your knowledge based on what you've learned in Smartphone Photography.
There are only 5 questions surrounding the content of this site.
<br/>
<button id="takeQuiz" type="button" name="name" onclick="takeQuiz()" style="cursor:pointer;">Take Quiz!</button></div>
<div id="gl_banner" style="display:none; visibility:hidden;">Good Luck! :)</div>
<form id="quiz" action="#" method="post" style="visibility:hidden;" autocomplete="off">
<!--QUIZ-->
<h3>1. How many percent of modern camera phones use CMOS?</h3>
<div id="question1">
<input type="radio" name="question-1-answers" id="question-1-answers-A" value="A" />
<label for="question-1-answers-A">A) 20%</label>
<br/>
<input type="radio" name="question-1-answers" id="question-1-answers-B" value="B" />
<label for="question-1-answers-B">B) 80%</label>
<br/>
<input type="radio" name="question-1-answers" id="question-1-answers-C" value="C" />
<label for="question-1-answers-C">C) 50%</label>
<br/>
<input type="radio" name="question-1-answers" id="question-1-answers-D" value="yes" />
<label for="question-1-answers-D">D) 90%</label>
</div>
**Edited for a pure javascript solution.
I got the function to get the select value from this post.
I don't think you need to do a loop here, as you only actually need to check one value- the value of the checked radio.
At the moment your looping through all the radios, so you'll always get three wrong answers.
**Edited again to fix some code errors. I have tested the following, it is working for me.
function getRadioValue(name) {
var group = document.getElementsByName(name);
for (var i=0;i<group.length;i++) {
if (group[i].checked) {
return group[i].value;
}
}
return '';
}
document.getElementById('submit').onclick = validateQuiz; //calls the function "validateQuiz" when submit button is clicked
// check for validation in the quiz
function validateQuiz(){
right = true;
radio = getRadioValue("question-1-answers");
if(!radio.length) {
right = false;
alert("Please check to make sure you have answered every question.");
return;
}
if(radio == 'yes')
{
alert("You have answered correctly!");
}
else {
right = false;
alert("Wrong answer");
}
}
I have this view with 2 radiobuttons strongly-typed to a model, and I wish to enable / disable textbox fields depending on the state of those radiobuttons.
Here is the view and the script I've been working on right now:
#model IList<MyApp.Models.ObjInfo>
#{
ViewBag.Title = "SendItems";
}
<h2>Ebay Items</h2>
<script src="/Scripts/jquery-1.7.1.min.js"
type="text/javascript"></script>
<script type="text/javascript">
function dostate1() {
$("#textfield1").attr("disabled", "disabled");
$("#textfield2").removeAttr("disabled");
$("#textfield3").removeAttr("disabled");
}
function dostate2() {
$("#textfield1").removeAttr("disabled");
$("#textfield2").attr("disabled", "disabled");
$("#textfield3").attr("disabled", "disabled");
}
$(document).ready(function ()
{
alert("The document is ready");
if ($("#state1").is(":checked")) {
dostate1();
} else {
dostate2();
}
$("#state1").click(function (){
alert("Auction radio button has been clicked");
dostate1();
});
$("#state2").click(function () {
alert("Buy It Now radio button has been clicked");
dostate2();
});
});
</script>
<p>
#using (Html.BeginForm("ManageItems", "Item Inventory"))
{
(...)
#for (int i = 0; i < Model.Count; i++)
{
<p>
<tr>
<td>#Html.DisplayFor(x => x[i].m_OtrObj.m_ObjName)</td>
<td>#Html.RadioButtonFor(x => x[i].m_State, "State 1", new {id = "state1", style ="width: 50px"})</td>
<td>#Html.RadioButtonFor(x => x[i].m_State, "State 2", new {id = "state2", style ="width: 50px"})</td>
<td>
#Html.TextBoxFor(x => x[i].m_Field1, new{id = "textField1", style = "width:200px"})
</td>
<td>
#Html.TextBoxFor(x => x[i].m_Field2, new {id = "textField2", style = "width:200px"})
</td>
<td>
#Html.TextBoxFor(x => x[i].m_Field3, new {id ="textField3", style = "width:200px" })
</td>
</tr>
</p>
}
</table>
<input type="submit" value="Do Something"/>
}
</p>
Right now I have 2 main problems:
Clicking on each radiobutton actually disable the fields I wish to have disabled, but do not activate the other fields;
The script actually runs only when a button is clicked, but should run at start to avoid field 1 being active since by default the "state 1" radio button is enabled.
I'm REALLY a newbie as to javascript, so can anyone help me out? Thanks!!
EDIT **
I've modified the script to show you the evolution so far, thanks to everyone who helped out, the script works, but only for the first item in the list. Taking into account that it's a list of object (see #model), how can I affect each items in the list individually?
Change your script to
$(document).ready(function ()
{
alert("The document is ready");
$("#state1").change(function (){ // use change event instead of click
alert("state1 radio button has been changed");
// use prop instead of attr and always use the disabled attribute
// (there is not enabled). Use true/false to alter its state
$("#textField1").prop("disabled", true);
$("#textField2").prop("disabled", false);
$("#textField3").prop("disabled", false);
}).trigger('change'); // trigger a change event since it is the default
$("#state2").change(function() { // use change event instead of click
alert("state2 radio button has been changed");
$("#textField1").prop("disabled", false);
$("#textField2").prop("disabled", true);
$("#textField3").prop("disabled", true);
});
});
Ok, so:
you need to enable the radio buttons by using jQuery's removeAttr function (http://api.jquery.com/removeAttr/):
alert("state1 radio button has been clicked");
$("#textField1").attr("disabled", "disabled");
$("#textField2").removeAttr("disabled");
$("#textField3").removeAttr("disabled");
this is because it's the presence of the "disabled" attribute that disables controls.
if you break your enable/disable code out into functions:
function doState1() {
$("#textField1").attr("disabled", "disabled");
$("#textField2").removeAttr("disabled");
$("#textField3").removeAttr("disabled");
}
function doState2() {
$("#textField1").removeAttr("disabled");
$("#textField2").attr("disabled", "disabled");
$("#textField3").attr("disabled", "disabled");
}
$(document).ready(function () {
doState1();
$("#state1").change(function (){
doState1();
});
$("#state2").change(function() {
doState2();
});
});
you can then call them when the doc is ready, and hook them into the click actions.
Edit
To repeat this for sets of buttons + fields, I would have your loop generate ids that are unique to each element, e.g.
<input type="radio" id="state_1_1">State 1_1
<input type="radio" id="state_2_1">State 2_1
<input type="text" id="textField_1_1">Text 1_1
<input type="text" id="textField_2_1">Text 2_1
<input type="text" id="textField_3_1">Text 3_1
<input type="radio" id="state_1_2">State 1_2
<input type="radio" id="state_2_2">State 2_2
<input type="text" id="textField_1_2">Text 1_2
<input type="text" id="textField_2_2">Text 2_2
<input type="text" id="textField_3_2">Text 3_2
and then change the code to use a "search start of id" selector and split the id to obtain the set and state/text field number:
function doState1(theid) {
var idarr = theid.split("_");
var state = idarr[1];
var idval = idarr[2];
$("#textField_1_" + idval).attr("disabled", "disabled");
$("#textField_2_" + idval).removeAttr("disabled");
$("#textField_3_" + idval).removeAttr("disabled");
}
function doState2(theid) {
var idarr = theid.split("_");
var state = idarr[1];
var idval = idarr[2];
$("#textField_1_" + idval).removeAttr("disabled");
$("#textField_2_" + idval).attr("disabled", "disabled");
$("#textField_3_" + idval).attr("disabled", "disabled");
}
$(document).ready(function () {
if ($("#state_1_1").is(":checked")) {
doState1("state_1_1");
} else {
doState2("state_2_1");
}
$('input[id^="state_1_"]').change(function () {
doState1(this.id);
});
$('input[id^="state_2_"]').change(function () {
doState2(this.id);
});
});
See http://jsfiddle.net/raad/4vHBv/17/
First , You have to understand the there is no such attribute by the name of 'enable'. For enable the html element , you have to remove the disabled attribute from fields.
If you want to change your field from disabled to enable state , then just do as i am writing:
$("#textField2").removeAttr("disabled");
$("#textField3").removeAttr("disabled");
Above code will enable the the Textbox with id "#textField2" and "#textField3"
Your first question is already answered above. As for the second one I would suggest moving the state checking to a function like this:
function checkState(){
if($('#state1').is(':checked')){
//do stuff...
}
}
And then run the function once on document ready and every time the state of the radio buttons is changed.
I want to select a particular RadioButton based on its value
<input id="RadioJ" type="radio" name="grp1" value="AAA" />
<input id="FaroK" type="radio" name="grp1" value="BBB" />
<input id="MartreLK" type="radio" name="grp1" value="CCC" />
Something like this:
var radio = radio button whose value is BBB
Another thing i am looking is that if a button is clicked, all the radiobuttons which are hidden should be visible.
You can select based on the value directly, e.g.:
var radio = $("input[type='radio'][value='BBB']")
Assuming you have a <form> element surrounding your radio buttons:
function getRadioWithValue(form, groupName, val) {
var radios = form.elements[groupName];
var i = radios.length, radio;
while (i--) {
radio = radios[i];
if (radio.value === val) {
return radio;
}
}
return null;
}
var radio = getRadioWithValue(document.forms["your_form_name"], "grp1", "BBB");
This will be an awful lot more efficient and fast than the jQuery equivalent using unnecessary CSS selectors.