javascript disable a single radio button - javascript

I have what should be a problem with a simple solution, and I'm sure I'm just missing something.
I have 2 columns of radio buttons, and when a radio button from a column is clicked, I need to disable the corresponding radio button from the opposite column, so it can't be selected. Then if another button is selected, re-enable the previous button and disable the new opposite selection.
I have given all the radio buttons a unique id. first1, first2, etc. for column one, and second1, second2 etc. for column two.
The way I was headed towards won't work after re-thinking this, and after searching online for an hour, I haven't found a non-jquery way of doing it. Is it possible with javascript?
What I had so far, and I know I'm way off base, but I'm burnt out with the different problems I've had with this page:
function disableForm(theform, theradio) {
//this was a start but does't save valid disabled fields
//it just enables everything
if (document.all || document.getElementById) {
for (i = 0; i < theform.length; i++) {
var formElement = theform.elements[i];
if (true) {
formElement.disabled = false;
}
}
}
document.getElementById(theradio).onclick = function(){
document.getElementById(theradio).disabled=true;
}
}

Let's say you define your radios as
<table style="width: 100%;">
<tr>
<td>
<input id="Radio1_1" type="radio" name="Radio1" onchange="process(this)"/><br />
<input id="Radio1_2" type="radio" name="Radio1" onchange="process(this)"/><br />
<input id="Radio1_3" type="radio" name="Radio1" onchange="process(this)"/><br />
<input id="Radio1_4" type="radio" name="Radio1" onchange="process(this)"/><br />
<input id="Radio1_5" type="radio" name="Radio1" onchange="process(this)"/>
</td>
<td>
<input id="Radio2_1" type="radio" name="Radio2" /><br />
<input id="Radio2_2" type="radio" name="Radio2" /><br />
<input id="Radio2_3" type="radio" name="Radio2" /><br />
<input id="Radio2_4" type="radio" name="Radio2" /><br />
<input id="Radio2_5" type="radio" name="Radio2" />
</td>
</tr>
</table>
Then the goal can be achieved by a simple script:
function process(rb) {
//clearing previos disabled
for (i = 0; i < document.getElementsByName("Radio2").length; i++) {
document.getElementsByName("Radio2")[i].disabled = '';
}
document.getElementById(rb.id.replace('Radio1','Radio2')).disabled='disabled';
}
Working example: http://jsfiddle.net/bbGDA/1/

Related

How to toggle a radio button with a label

I would like to unselect a radio button when I click on the label and the following code only works as expected if I click on the button itself.
How to link the behaviour of the label to the button?
<label>
<input type="radio" name="choice" value="HTML" onMouseDown="this.__chk = this.checked" onClick="if (this.__chk) this.checked = false" /> Learn HTML
</label>
<label>
<input type="radio" name="choice" value="Java" onMouseDown="this.__chk = this.checked" onClick="if (this.__chk) this.checked = false"/> Learn JavaScript
</label>
Radio buttons don't work like you are thinking they do. To deselect one you need to either select another with the same name attribute or reset the form. The functionality that you are describing fits more with a checkbox than a radio button. See https://developer.mozilla.org/en-US/docs/Web/HTML/Element/input/radio for the specs. You may also want to take a look at this question/answer: Reset Particular Input Element in a HTML Form.
Also, there is no need to wrap your label tag around the input. The for attribute takes care of the linking.
If you want to de-select a radio button, you will need to reset the form.
form {
display: flex;
flex-direction: column;
}
<form>
<label for="ckb-01">
<input id="ckb-01" type="radio" name="choice" value="HTML" />
Learn HTML
</label>
<label for="ckb-02">
<input id="ckb-02" type="radio" name="choice" value="Java" />
Learn JavaScript
</label>
<label for="ckb-03">
<input id="ckb-03" type="radio" name="choice" value="Java" />
Learn CSS
</label>
<input type="reset" />
</form>
use the attribut for in the label
<label for='idHTML'>Learn HTML </label>
give the radio the id equivalent
<input id='idHTML' type="radio" name="choice" />
what do you mean by this.__chk
onMouseDown="this.__chk = this.checked"
onClick="if (this.__chk) this.checked = false"
if you wanna select just one you could use simply type radio with group the options with one name='choice'
if you want check and uncheck multiple choices you could use checkbox
After many attempts I finally managed to code a working solution with some javascript.
The problem is that as soon as the radio button is clicked its state changes. the previous value needs to be stored in order to know if it has to be unselected or not.
<main id="form">
<label >
<input type="radio" name="rad" id="Radio0" />Learn Html
</label>
<br><br>
<label>
<input type="radio" name="rad" id="Radio1" />Learn CSS
</label>
<br><br>
<label>
<input type="radio" name="rad" id="Radio2" />Learn Java
</label>
</main>
<script>
let buttons = document.querySelectorAll('#form input');
for (button of buttons){
button.dataset.waschecked="false";
button.addEventListener('click', myFunction, false);
}
function myFunction(e) {
if (e.originalTarget.dataset.waschecked == "false"){
for (button of document.querySelectorAll('#form input')){
button.dataset.waschecked = "false";
}
e.originalTarget.dataset.waschecked = "true";
e.originalTarget.checked =true;
}else {
for (button of document.querySelectorAll('#form input')){
button.dataset.waschecked = "false";
}
e.originalTarget.checked =false;
}
}
</script>
Any suggestion to improve this code is welcome.

check all other radio button using one radio button

i am fetching roll numbers here which have two radio buttons in 'php'.there will be multiple number of roll numbers so i want to check all the radio buttons whose value are 'yes' at once using a particular radio button or check box.although i didn't write that button in this code as i don't know what to write.please give me a solution using java script.
while($row=mysqli_fetch_assoc($result))
{
echo"<tr><td>{$row['roll']}</td>
</td><td></td><td></td><td></td><td>
<td><input type='radio' name='present[$i]' value='Yes'>YES</td>
</td><td></td><td></td><td>
<td><input type='radio' name='present[$i]' value='No'>NO</td></tr>";
$i++;
}
This type of interaction should be using a Javascript implementation since it is a client-side operation.
HTML:
<form>
<input type="radio" name="radio1" value="yes"/>Yes
<input type="radio" name="radio1" value="no"/>No
<br />
<input type="radio" name="radio2" value="yes"/>Yes
<input type="radio" name="radio2" value="no"/>No
<br />
<input type="radio" name="radio3" value="yes"/>Yes
<input type="radio" name="radio3" value="no"/>No
<br />
<input type="button" value="Select All" onclick="selectAll('radio',true);"/>
<input type="button" value="Deselect All" onclick="selectAll('radio',false);"/>
</form>
Javascript:
function selectAll( prefix, set ) {
var form = document.forms[0], //Get the appropriate form
i = 0,
radio;
while( radio = form[prefix + ++i] ) //Loop through all named radio# elements
for( var j = 0; j < radio.length; j++ ) //Loop through each set of named radio buttons
if( radio[j].value == (set ? "yes" : "no") ) //Selector based on value of set
radio[j].checked = true; //Check that radio button!
}
JSFiddle

Possible to pass several array items using 1 attribute?

I have a group of tick boxes with 1 select all box at the top
<input type="checkbox" id="1195" value="All" />
<input type="checkbox" name="GroupA" title="TickboxA" value="TickboxA" id="TickboxA" />
<input type="checkbox" name="GroupA" title="TickboxB" value="TickboxB" id="TickboxB" />
<input type="checkbox" name="GroupA" title="TickboxC" value="TickboxC" id="TickboxC" />
<input type="checkbox" name="GroupA" title="TickboxD" value="TickboxD" id="TickboxD" />
I'm passing all the checks to an array so I can pass it around the site like so:
$('input').on('ifClicked', function (event) {
addRemoveService(document.getElementById(this.title));
setItemArray();
document.getElementById('mydoc').value = "";
for (var i = 0; i < itemIdArray.length; i++) {
setInterestedIn(i);
}
});
I have some jquery that will tick all the boxes for me if i click on the top checkbox - Everything is working perfect, except if i tick on the 'all' checkbox - I can't pass all the titles of all the other boxes to the array - what I want to do is something like:
<input type="checkbox" id="1195" value="All" title="TickboxA,TickboxB,TickboxC,TickboxD" />
If that makes sense? Is there an easy way to do this?

Delete drop down when it is blank using Javascript or Jquery

Is it possible to write a Javascript function to delete a drop down when it is blank?
<form name="myform" method="post" enctype="multipart/form-data" action="" id="myform">
<div>
<label id="question1">1) Draw recognizable shapes</label>
<br />
<input type="radio" value="Yes" id="question1_0" name="question1_0" />
Yes
<input type="radio" value="No" id="question1_1" name="question1_1" />
No
</div>
<div>
<label id="question2">2) Competently cut paper </label>
<br />
<input type="radio" value="Yes" id="question2_0" name="question2_0" />
Yes
<input type="radio" value="No" id="question2_1" name="question2_1" />
No
</div>
<div>
<label id="question3">3) Hold a pencil</label>
<br />
<input type="radio" value="Yes" id="question3_0" name="question3_0" />
Yes
<input type="radio" value="No" id="question3_1" name="question3_1" />
No
</div>
<input type="submit" value="Delete Drop Down" onclick="return checkanddelete"/>
</form>
If somebody does not select question 2 for example, it deletes question 2 label and the drop down.
Assuming you actually meant radio button groups (and not drop down lists) then firstly your HTML is incorrect, you need to set the name values of each group of radio buttons to be the same:
<input type="radio" value="Yes" id="question1_0" name="question1" /> Yes
<input type="radio" value="No" id="question1_1" name="question1" /> No
Then you need to loop through the list of radio buttons, if none in the group are selected then delete the parent div:
$('input[type=submit]').on('click', function() {
var radioArr = [];
$(':radio').each(function(){
var radName = this.name;
if($.inArray(radName, radioArr) < 0 && $(':radio[name='+radName+']:checked').length == 0)
{
radioArr.push(radName);
$(this).closest("div")
.remove();
}
});
return false; //to stop the form submitting for testing purposes
});
While you are there, you might want to add some <label for=""> tags around your text.
Here is a jsFiddle of the solution.
If your dropdown has an id of DropDown, and you are looking to hide the dropdon on submit click:
function checkanddelete()
{
if ( $('#question2_0.=:checked, #question2_1:checked').length )
$('#dropdown').hide() // Or $('#dropdown').remove() if you do not plan on showing it again.
return false; // if you plan on not submitting the form..
}
Optimization for use in a module for a page include adding appropriate ids and classes to the divs, which I'm assuming that in full code are there, but if you are planning on making UI adjustments I would advise against using a submit button in the mix..
I don't know, what do you mean under "dropdown menu", but here some info, that can help you.
You can set a class name for the all Objects, you want to delete. E.g.
HTML
<div>
<label class='question2' id="question2">2) Competently cut paper </label>
<br />
<input class='question2' type="radio" value="Yes" id="question2_0" name="question2_0" />
Yes
<input class='question2' type="radio" value="No" id="question2_1" name="question2_1" />
No
</div>
JS
$(".question2").remove();
As an another solution you can set an ID for the DIV Tag above all of this elements
<div id='block_to_remove'>
<label id="question2">2) Competently cut paper </label>
<br />
<input type="radio" value="Yes" id="question2_0" name="question2_0" />
Yes
<input type="radio" value="No" id="question2_1" name="question2_1" />
No
</div>
And then remove it in JS
$("#block_to_remove").remove();

Alert if ANY radio options are not checked

I have a form with 3 questions that have 3 radio options each. I want the form to send an alert if ANY of the questions are left blank. This code sends an alert only if ALL of the questions are left blank:
if (!$("input").is(':checked')) {
alert("You left one blank!");
}
So, for example, if I have only one question answered, I want the alert to send. Instead, it continues on with the code.
You have 3 radio groups, so there will be 3 checked inputs and 6 unchecked inputs, I suggest:
if ( $("input[type=radio]:checked").length < 3 ) {
alert('Please answer all of the questions');
}
Try this:
$(document).ready(function () {
$("#btn1").on("click", function () {
var count = 0;
var questions = $("div.question");
questions.each(function () {
if ($(this).find("input").filter('[type="radio"]').filter(":checked").length > 0) {
count++;
}
});
if (count >= questions.length) {
alert("all good");
} else {
alert("something not checked");
}
});
});
With the HTML:
<div class="question">
Question 1:
<input type="radio" name="radio1" />
<input type="radio" name="radio1" />
<input type="radio" name="radio1" />
</div>
<div class="question">
Question 2:
<input type="radio" name="radio2" />
<input type="radio" name="radio2" />
<input type="radio" name="radio2" />
</div>
<div class="question">
Question 3:
<input type="radio" name="radio3" />
<input type="radio" name="radio3" />
<input type="radio" name="radio3" />
</div>
<div>
<input type="button" id="btn1" value="Submit" />
</div>
http://jsfiddle.net/4yQHv/1/
You can change if (count >= questions.length) { to be === instead of >= to make sure exactly 1 radio button is chosen for every question. Otherwise, this allows for more than one radio button to be chosen (which isn't exactly possible when they're grouped by name attribute)...but just wanted to point that out.
http://jsfiddle.net/tVUuW/
<form>
<input type="radio" name="facepunch" class="facepunch" value="1" />
<input type="radio" name="facepunch" class="facepunch" value="2" />
<input type="radio" name="facepunch" class="facepunch" value="3" />
<br />
<input type="radio" name="stack" class="stack" value="1" />
<input type="radio" name="stack" class="stack" value="2" />
<input type="radio" name="stack" class="stack" value="3" />
<br />
<input id="button" type="button">
</form>
$(document).ready(function(){
$('#button').click(function(){
if(!$("input.facepunch:checked").val()) {
alert("Please select facepunch");
}
if(!$("input.stack:checked").val()) {
alert("Please select stack");
}
});
});
If you have only few groups of radios you can use this method, this is one way to validate user data.
I recommend you to check out one of the great jQuery Validation Plugins out there:
jzaefferer plugin, bassistance plugin
Also, Make sure you validate it on the server side as well! The user can send request to your server from somewhere else or even disable javascript on his browser
You can loop through all your radio buttons and see if any of them is unchecked:
$('input[type="radio"]').each(function () {
if( ! $(this).is(':checked') ) {
alert('You left one blank!');
return false; //exit function, so alert won't show multiple times
}
});
Example

Categories

Resources