Javascript: get radiobutton label with a specific "for" in label - javascript

I have a form element like this:
<div id="myformelement">
<input type="radio" id="option1">
<label for="option2">Option 1</label>
<input type="radio" id="option2">
<label for="option2">Option 2</label>
<input type="radio" id="option3">
<label for="option3">Option 3</label>
<input type="radio" id="option4">
<label for="option4">Option 4</label>
</div>
I want to hide the input fields "option2" and "option3" and their labels.
I can hide the input bullets by addressing the id. Unfortunately the corresponding labels to the input fields only have a "for" tag with the id in it.
How can I do this with javascript (no jquery).
I found this question (Find html label associated with a given input), but this seems only to work with one label within an ID, I can not use this.
Thanks in advance!
Kind regards,
Malte

In pure JavaScript you can use querySelector:
document.querySelector("label[for='option2']").style.display = "none";

You can do it with nextSibling:
var rdo = document.getElementById("option2");
var lbl;
rdo.style.display = "none";
for (lbl = rdo.nextSibling; lbl && lbl.nodeName.toUpperCase() !== "LABEL"; lbl = lbl.nextSibling) {
}
if (lbl) {
lbl.style.display = "none";
}
But I have a better option for you: It seems to be a well-kept secret that label elements can contain the input they relate to, and when they do no for is required at all. So if you change your HTML to:
<div id="myformelement">
<label><input type="radio" id="option1"> Option 1</label>
<label><input type="radio" id="option2"> Option 2</label>
<label><input type="radio" id="option3"> Option 3</label>
<label><input type="radio" id="option4"> Option 4</label>
</div>
...it gets a lot easier:
document.getElementById("option2").parentNode.style.display = "none";
You just find the input, traverse up to its parent which is the label, and hide that (which will hide the input as well).

Related

Make check-boxes becoming one group of radio button

I cannot make the input name same or value same. The second and third inputs come from a loop using c# razor. I have 2 sets of radio inputs first one is one set and second and third are another set. Because the second and third have the same name, checking one makes the other unchecked. I want the same for all of them together so it would be like I have one set of 3 radio buttons. Like I said above I am not able to make the name or value same due to back-end data display issue. Here is my attempt below.
//first radio <br/>
<div class="radio">
<label>
<input id="dcenter-allradio" type="radio" value="0" />All
</label>
</div>
//this radio button is a loop <br>
<input type="radio" name="#Model.Facet.Key" value="#item.Key">tagitem.j
<div class="radio">
<label>
<input id="dcenter-listradio" type="radio" name="#Model.Facet.Key" value="#item.Key" />tagItem.Name
</label>
</div>
<script>
$(document).ready(function () {
if ($('#dcenter-listradio').prop("checked", true)) {
$('#dcenter-allradio').prop("checked", false);
}
if ($('#dcenter-allradio').prop("checked", true)) {
$('#dcenter-listradio').prop("checked", false);
}
});
</script>
If you can give them all the same class, then you can just use jQuery to detect when a change has occurred and then uncheck other items in the same class.
$(document).ready(function() {
var selector = ".groupTogether";
// or if you can't give same class, you could use "#unrelatedRadio, input[name='related']"
$(selector).change(function()
{
if(this.checked)
{
$(selector).not(this).prop('checked', false);
}
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<input id="unrelatedRadio" name="unrelated" type="radio" class="groupTogether">unrelated</input>
<input id="relatedA" name="related" type="radio" class="groupTogether">Related A</input>
<input id="relatedB" name="related" type="radio" class="groupTogether">Related B</input>
Or, if you can't give them the same class, just replace the selector with something that selects both sets (in my example, "#unrelatedRadio, input[name='related']")
let radios = document.querySelectorAll("input");
for (let i of radios){
i.name="same"
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
//first radio <br/>
<div class="radio">
<label>
<input id="dcenter-allradio" type="radio" value="0" />All
</label>
</div>
//this radio button is a loop <br>
<input type="radio" name="#Model.Facet.Key" value="#item.Key">tagitem.j
<div class="radio">
<label>
<input id="dcenter-listradio" type="radio" name="#Model.Facet.Key" value="#item.Key" />tagItem.Name
</label>
</div>

jQuery validate, radio button group, nesting issue

I am trying to add a custom method to validate a group of radio buttons, using v1.9 of the jQuery validate plugin.
Contrary to this post, it is possible to have the same name attribute for radio button inputs, as long as any class rules are only applied to one of the inputs. jQuery validate then treats your input group as a single input.
This works when your inputs are children of a common parent, ie
<input type="radio" name="radiogroup" value="1" class="input-shipping" checked="checked">
<input type="radio" name="radiogroup" value="2">
<input type="radio" name="radiogroup" value="3">
<input type="radio" name="radiogroup" value="4">
But as soon as the html structure changes, the validation rules are not applied:
<div class="form-row">
<input type="radio" name="radiogroup" value="1" class="input-shipping" checked="checked">
</div>
<div class="form-row">
<input type="radio" name="radiogroup" value="2">
</div>
<div class="form-row">
<input type="radio" name="radiogroup" value="3">
</div>
<div class="form-row">
<input type="radio" name="radiogroup" value="4">
</div>
Is anyone aware of a workaround for this issue? Class rules are added as follows:
$.validator.addClassRules({
"input-shipping" : {
required: true,
dateselected: true
}
});
$.validator.addMethod("dateselected", function(value, element) {
console.log(element);
});
The reason the validation rule was not being called was that custom radio buttons were used, which set the CSS display value of inputs to none, and pseudo elements were styled up in place of the original inputs.
Once this was changed to visibility:hidden; the validator seemed to pick up the rule OK.
To create a custom method based on the value of the selected input, a further level of filtering was needed:
$.validator.addMethod("dateselected", function(value, element) {
var radios = $('input[name='+element.name+']'),
val = radios.filter(':checked')[0].value;
console.log(val);
});

I have multiple checkboxes, and want to make a rule for 2 of them so that if I select 1 the other cannot be selected

​<form>
<label for="1">Text 1</label>
<input type="checkbox" name="1" value="something1" id="1"><br>
<label for="2">Text 2</label>
<input type="checkbox" name="2" value="something2" id="2"><br>
<label for="3">Text 3</label>
<input type="checkbox" name="3" value="something3" id="3"><br>
<label for="4">Text 4</label>
<input type="checkbox" name="4" value="something4" id="4">
</form>​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​
Those are the checkboxes , I have tried to search all over the internet and didn't find anything.
I want to allow the user to check id 3 and 4 BUT if he checks 1 , then 2 is not available to check, or if he checks 2 then 1 is not available to check.
And to the unavailable to add a class .. named ..
grade-out{ color: #DDD;}
Hope u understand the problem. Thanks in Advance !!
I would add data-groupid attribute to your checkboxes to identify which group they belong to. And then add a click handler to checkboxes belonging to group, which would disable all other checkboxes in the same group when checked and enable them when unchecked..
Assumming your markup is consistent and labels are always predecessors of respective checkboxes, you can easily target them using the prev() method.
$('input:checkbox[data-group]').click(function() {
var groupid = $(this).data('group');
var checked = $(this).is(':checked');
if(checked) {
$('input:checkbox[data-group=' + groupid + ']').not($(this))
.attr('disabled', 'disabled')
.prev().addClass('grade-out');
} else {
$('input:checkbox[data-group=' + groupid + ']')
.removeAttr('disabled')
.prev().removeClass('grade-out');
}
});
DEMO
I would assign an attribute data-disable to disable certain elements and check onchange.
This is how I would do it:
<form>
<label for="1">Text 1</label>
<input type="checkbox" name="1" value="something1" id="1" data-disable="2,3"><br>
<label for="2">Text 2</label>
<input type="checkbox" name="2" value="something2" id="2" data-disable="1"><br>
<label for="3">Text 3</label>
<input type="checkbox" name="3" value="something3" id="3"><br>
<label for="4">Text 4</label>
<input type="checkbox" name="4" value="something4" id="4">
</form>​​​
and script:
$('input:checkbox​​​​​​​​​​​​​​​​​​')​.on('change', function(){
var toUncheck = $(this).attr('data-disable');
var self = $(this);
$.each(toUncheck.split(','), function(el, val){
if(self.attr('checked') == 'checked'){
$('#'+val).attr('disabled', 'disabled');
} else {
$('#'+val).removeAttr('disabled');
}
});
});​
JSFiddle Demo
You could use radio form inputs. Anyway, if it's a must to use checkboxes then you could use some javascript (with jQuery, for example)
$('#1,#2').click(function(){
var $this = $(this);
var theOtherId = $this.attr('id') == 1 ? 2 : 1;
var theOtherOne = $('#'+theOtherId);
if( $this.is(':checked') ) theOtherOne.attr('checked',false);
});
It this what you're looking for?
Re-worked example: demo fiddle
$('#1,#2').click(function(){
var $this = $(this);
var theOtherId = $this.attr('id') == 1 ? 2 : 1;
var theOtherOne = $('#'+theOtherId);
if( $this.is(':checked') ) theOtherOne.attr('disabled',true);
else theOtherOne.attr('disabled',false);
});
Although there are more complex and flexible solutions above if you wish a solid but clear usage sample look at this. Using id's make things easier.
http://jsfiddle.net/erdincgc/uMhbs/1/
HTML (added class and id) ;
<form>
<label for="1">Text 1</label>
<input class="checks" type="checkbox" id="option1" name="option1" value="something1" id="1"><br>
<label for="2">Text 2</label>
<input class="checks" type="checkbox" id="option2" name="option2" value="something2" id="2"><br>
<label for="3">Text 3</label>
<input class="checks" type="checkbox" id="option3" name="option3" value="something3" id="3"><br>
<label for="4">Text 4</label>
<input class="checks" type="checkbox" id="option4" name="option4" value="something4" id="4">
</form>
And JS
$('.checks').click(function(){
op1 = $('#option1') ;
op2 = $('#option2') ;
this_id = $(this).attr("id") ;
this_state = $(this).attr("checked");
if(this_id =="option1"){
if( this_state == "checked" ){
op2.attr("disabled",true);
}
else {
op2.attr("disabled",false);
}
op2.prev().toggleClass('disabled');
}
if(this_id=="option2"){
if( this_state=="checked" )
op1.attr("disabled",true);
else {
op1.attr("disabled",false);
}
op1.prev().toggleClass('disabled');
}
});
Use $("#element_id").hide(); for disabling the check box
Use $("#element_id").attr("checked", true); to check if the check box is selected
Use $("#element_id").addclass(); to add class to an element so in short search for jQuery selectors and you will find the solutions
Vist for more information http://api.jquery.com/category/selectors/ I hope I help take care

Find name of the radio button that is checked

My page has about 25 radio button groups. When a radio button is selected in a group, I want to perform an action Specific to that group, and so need the NAME attrib of the radio group.
Take this HTML for example :
<div id="stackExchange">
<input type="radio" name="sofu_group" value="Stack Overflow">
<input type="radio" name="sofu_group" value="Meta Stack Overflow">
<input type="radio" name="sofu_group" value="Server Fault">
<input type="radio" name="sofu_group" value="Super User">
</div>
<!-- In no particular order - don't want to start a flame war ;) -->
If you wanted to deduce what group the clicked radio button belongs to you could use something like this :
// jQuery ver 1.7+
$("#stackExchange input:radio").on('click',function(){
var groupName = $(this).attr('name');
var groupElements = $(this).parent().find(":radio[name='"+groupName+"']");
});
Lets see whats going on here :
$("#stackExchange input:radio") - this selector will find us all of the input radio elements that are decendants of the #stackExchange element using the :radio selector. (Link to docs).
$(this).attr('name') - here is where we extract the name attribute of the selected radio element. (In our example - this becomes sofu_group).
$(this).parent() - In this case the variable $(this) refers to the radio element that was clicked - so we are selecting its parent - the #stackExchange element.
parent().find(":radio[name='"+groupName+"']") - this line will find all of the radio buttons held within the element that have a name attribute set to 'sofu_group'.
In the example - the variable $(this) refers to the radio element that was clicked.
This might give you some hint
<html>
<head>
<title>My Page</title>
</head>
<body>
<form name="myform" action="http://www.mydomain.com/myformhandler.cgi" method="POST">
<div align="center"><br>
<input type="radio" name="group1" value="Milk"> Milk<br>
<input type="radio" name="group1" value="Butter" checked> Butter<br>
<input type="radio" name="group1" value="Cheese"> Cheese
<hr>
<input type="radio" name="group2" value="Water"> Water<br>
<input type="radio" name="group2" value="Beer"> Beer<br>
<input type="radio" name="group2" value="Wine" checked> Wine<br>
</div>
</form>
</body>
</html>
call document.getElementsByName("group1").items(0).<propertyname>or<function>

How to find the value of a radio button with pure javascript?

<input checked=checked type="radio" name="colors" value="red" />Red
<input type="radio" name="colors" value="green" />Green
<input type="radio" name="colors" value="blue" />Blue
Given the above, I set the red button to be selected by default (so I give it the checked=checked attribute. With this, if I ever call .checked on that input element, it will always return true, even if another option is selected.
In plain javascript (no jQuery), how can you get the actual selected option?
Try this:
var options = document.getElementsByName("colors");
if (options) {
for (var i = 0; i < options.length; i++) {
if (options[i].checked){
alert(options[i].value);
}
}
}
Would be so much easier with jQuery though... just saying.
I believe you will find it in the document.all collection:
var selectedColor = document.all["colors"];
plain javasript:
document.querySelector('input[name=colors]:checked').value;
you can try like this .....
This is example
<form name="frmRadio" method="post">
<input name="choice" value="1" type="radio" />1
<input name="choice" value="2" type="radio" />2
<input name="choice" value="3" type="radio" />3
<input name="choice" value="4" type="radio" />4
</form>
function to get the selected value
<script language="JavaScript">
function getRadioValue() {
for (index=0; index < document.frmRadio.choice.length; index++) {
if (document.frmRadio.choice[index].checked) {
var radioValue = document.frmRadio.choice[index].value;
break;
}
}
}
</script>
Well, they all have the same name. So naturally at least one of them has to be selected. Give them different ID's and try again.

Categories