get label for for a check input radio - javascript

I am having a radio element that I want to get the text:
<div class="fleft multiplecolumns">
<div class="rdbUniteWrapper" style="line-height:20px">
<span class="EasilyRadioWrapper EasilyControlWrapper">
<span class="EasilyRadio EasilyChecked"></span>
<input id="rdbUnite_106" name="rdbUnite" type="radio" value="106" class="formElementHidden" checked="checked" style="opacity: 0;">
</span>
<label for="rdbUnite_106" style="font-weight: bold">kg (kilogramme)</label>
</div>
I tried $('input:radio[name=radio]:checked').next().text(); but it' s not the solution...
What am I doing wrong ?
Cheers

input:radio is not the sibling of label element, its parent span is. thus you need to traverse to parent span, then to next sibling element:
$('input:radio[name=radio]:checked').parent().next().text();

I find out the solution
var labelUnite = $('label[for="' + $("input[name='rdbUnite']:checked").attr("id") + '"]').text();
thanks for your helps

try below code
$('input:radio[name=radio]:checked').parent().next().text();

I am having a radio element that I want to get the text
Since the two are nicely related by id = for, you can use an attribute value selector:
// Assuming `this` is a reference to the radio button element
var label = $('label[for="' + this.id + '"]');
Then if you want the text, use .text():
var test = label.text();
Live example:
$("input[type=radio]").on("click", function() {
alert($('label[for="' + this.id + '"]').text());
});
Click a radio button to see its label text:
<div>
<label for="r1">This is for r1</label>
<input type="radio" id="r1">
</div>
<div>
<label for="r2">This is for r2</label>
<input type="radio" id="r2">
</div>
<div>
<label for="r3">This is for r3</label>
<input type="radio" id="r3">
</div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
More generally, a radio button element and its label are related in one of two ways:
Via id = for, as in your example
Via containment, where the label contains the input[type=radio]
If you want to handle the general case, you can do something like this:
// Assuming `this` is the radio button element
var text;
var label = null;
if (this.id) {
label = $('label[for="' + this.id + '"]');
}
if (!label || !label[0]) {
label = $(this).closest('label');
}
text = label && label.text();

Use This :-
var label = $("label[for='"+$('input:radio[name=radio]:checked').attr('id')+"']")

Related

Change parent style with javascript based on checked input

I am looking to change the style of the parent label when the checkbox is checked. I realise this can't feasibly be done with CSS, is this possible with Javascript?
<label id="cont">
<span>
<input type="checkbox" />
</span>
</label>
Yes, here's an example:
const container = document.querySelector('#cont');
const checkbox = document.querySelector('input');
checkbox.addEventListener('change', () => {
if (checkbox.checked) {
container.style.background = 'red'
} else {
container.style.background = 'white'
}
})
<label id="cont">
<span>
<input type="checkbox" />
</span>
</label>
Your question is a bit unclear. If you have just a single parent element and checkbox like your code suggests, then it's straightforward.
You can define the new styles you want a class(let's say a class called new-style) inside your stylesheet, then add a listener function inside your js script to trigger when the checkbox is clicked. The listener function will basically insert the class into the parent if it doesn't have it or remove it if it does. Something like this.
<script>
let checkbox = document.querySelector('input[type="checkbox"]');
checkbox.onclick = function() {
let parent = document.querySelector('#cont')
parent.classList.toggle('new-style');
}
</script>
Have you tried it this way? You can use css :checked property for this.
input:checked + label {
color: red;
}
<input id="name" type="checkbox">
<label for="name" id="cont">
label
</label>

HTML Jquery radio buttons switch as per select

I have 2 radio buttons that switch on selected. When one of the two radio buttons is selected, there should be a description for it, when the other is selected, the description should change.
The code below does pretty much what I want, but the problem is it does it on CLICK. One of the radio buttons will come as pre-selected (with 'checked' attribute) and a description isn't going to show up until the user clicks a radio button. Thus I would like for the description to match the corresponding radio button if one of them is pre-checked.
$(document).ready(function(){
$('input[name="subscription-type"]').click(function(){
var inputValue = $(this).attr("value");
var targetBox = $("." + inputValue);
$(".subscription-desc").not(targetBox).hide();
$(targetBox).show();
});
});
.subscription-desc {
display: none;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="radio-toolbar-3">
<input type="radio" id="classic" name="subscription-type" value="classic" class="choose" checked>
<label for="classic">Classic</label>
<input type="radio" id="adventurer" name="subscription-type" value="adventurer" class="choose">
<label for="adventurer">Adventurer</label>
</div>
<div class="classic subscription-desc">
Description 1
</div>
<div class="adventurer subscription-desc">
Description 2
</div>
Basically in the above, "Classic" option will come as pre-selected, but there is no description for it until the user clicks it.
Seems like a simple problem but I just can't find a solution for it. Any help appreciated. Thanks
You can trigger the .click event on the :checked radio button so that it fires the click event:
$('input[name="subscription-type"]:checked').click();
$(document).ready(function() {
$('input[name="subscription-type"]').click(function() {
var inputValue = $(this).attr("value");
var targetBox = $("." + inputValue);
$(".subscription-desc").not(targetBox).hide();
$(targetBox).show();
});
$('input[name="subscription-type"]:checked').click();
});
.subscription-desc {
display: none;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="radio-toolbar-3">
<input type="radio" id="classic" name="subscription-type" value="classic" class="choose" checked>
<label for="classic">Classic</label>
<input type="radio" id="adventurer" name="subscription-type" value="adventurer" class="choose">
<label for="adventurer">Adventurer</label>
</div>
<div class="classic subscription-desc">
Description 1
</div>
<div class="adventurer subscription-desc">
Description 2
</div>
Alternatively, you can extract the code that does the display into a function and call that:
function updateSubscription() {
var inp = $('input[name="subscription-type"]:checked');
var inputValue = $(inp).attr("value");
var targetBox = $("." + inputValue);
$(".subscription-desc").not(targetBox).hide();
$(targetBox).show();
}
$(document).ready(function() {
$('input[name="subscription-type"]').click(updateSubscription);
updateSubscription();
});
function updateSubscription() {
var inp = $('input[name="subscription-type"]:checked');
var inputValue = $(inp).attr("value");
var targetBox = $("." + inputValue);
$(".subscription-desc").not(targetBox).hide();
$(targetBox).show();
}
$(document).ready(function() {
$('input[name="subscription-type"]').click(updateSubscription);
updateSubscription();
});
.subscription-desc {
display: none;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="radio-toolbar-3">
<input type="radio" id="classic" name="subscription-type" value="classic" class="choose" checked>
<label for="classic">Classic</label>
<input type="radio" id="adventurer" name="subscription-type" value="adventurer" class="choose">
<label for="adventurer">Adventurer</label>
</div>
<div class="classic subscription-desc">
Description 1
</div>
<div class="adventurer subscription-desc">
Description 2
</div>
Note you can also use
var inputValue = $('input[name="subscription-type"]').val()
instead of
var inp = $('input[name="subscription-type"]:checked');
var inputValue = $(inp).attr("value");
I've kept the code above close to your original, just replacing the clicked this with $('input[name="subscription-type"]:checked')
Another alternative is to show the correct description at the time of load - this way you also don't get the "FOUC" (flash of unstyled content) where the description is displayed only after the page has fully loaded.
How you do this will depend on how you set the 'checked' value on the radio at page load, so may not be a suitable solution.

Javascript to Jquery, add text in input onclick

How can I change this javascript code to JQuery.
<script type="text/javascript">
function addTextTag(text){
document.getElementById('text_tag_input').value += text;
}
</script>
When a user click the link text automaticaly is added in input.
This is the HTML:
<input id="text_tag_input" type="text" name="tags" />
<div class="tags_select">
text1
text2
text3
</div>
Here is the demo: http://jsfiddle.net/Smartik/j8qGT/
<script type="text/javascript">
$(function() {
$('.tags_select a').click(function() {
var value = $(this).text();
var input = $('#text_tag_input');
input.val(input.val() + value + ', ');
return false;
});
});
</script>
and your markup:
<input id="text_tag_input" type="text" name="tags" />
<div class="tags_select">
text1
text2
text3
</div>
and here's a live demo.
Without inline javascript, completely jQuery:
http://jsfiddle.net/j8qGT/3/
JavaScript:
$('a').click(function(){
$('#text_tag_input').val($('#text_tag_input').val()+$(this).html()+', ');
});
​
HTML:
<input id="text_tag_input" type="text" name="tags" />
<div class="tags_select">
text1
text2
text3
</div>​
Some notes on the steps:
select already the input where to set the value so you avoid the need to re-query for it all the time: var $tagsInput = $('#text_tag_input');. The hash tag selector if the ID selector in jQuery, replaces document.getElementById
bind a click event with .click() for links within element with class "tags_select": `$('.tags_select a').click(...);``
To append the value, instead of struggling with jquery methods to get and set the value of the input, get the native DOM element with [0] on $tagsInput and use the += notation of the property value.
Here's the code:
// select already you input element for re-use
var $tagsInput = $('#text_tag_input');
// bind a click event to links within ".tags-select" element
$('.tags_select a').click(function() {
// append link text to the input field value
$tagsInput[0].value += $(this).text();
return false;
});
DEMO
Further reading:
jQuery selectors
Bind a click event with .click()

Show element with attribute

<input type="radio" name="group2" test="one" value="Water"> Water
<input type="radio" name="group2" test="two" value="Beer"> Beer<br>
<div style="display: none" test="one">aaaaaaa</div>
<div style="display: none" test="two">bbbbbbb</div>
<div style="display: none" test="one">ccccccc</div>
I would like: if i click on radio Water with attribute test="one" then should show me all div with attribute test="one". How can i make it with jQuery?
LIVE: http://jsfiddle.net/hRCXV/
Try this:
$("input[type='radio']").click(function() {
var test = $(this).attr("test");
$("div[test]").hide();
$("div[test='" + test + "']").show();
});
Updated fiddle
Please bear in mind that creating your own attributes as you have here is not valid. If you're using HTML5 you should consider using the data attribute to store whatever information you need associated with each element.
Attach a label to the Water text, and a click handler using the attribute selector:
<label for="option1">
<input type="radio" name="group2" id="option1" test="one" value="Water"> Water
</label>
<script>
$('label').click(function() {
// Logic tells me that you want to only show the test elements whose
// attribute matches the selected radio element; Hide the previous ones:
$('div[test]').hide();
// Get test value:
var test = $('#' + $(this).attr('for') ).attr('test');
$('div[test="' + test + '"]').show();
});
</script>
$('input [value="Water"]').click(function() {
$('[test="one"]').show();
});
jsFiddle: http://jsfiddle.net/hRCXV/1/
$("input[type=radio][value=Water]").click(function()
{
$("[test=one]").show();
});​
I belive this is something that you are looking for?
​$(':radio[name="group2"]')​.click(function(e){
var test = $(this).attr('test');
$('div[test]').hide();
$('div[test='+test+']').show();
});​
try this
jQuery(document).ready(function(){
var yourAttributeName = 'test';
var allDivs = jQuery('div['+yourAttributeName+']');
jQuery('input['+yourAttributeName+']').click(function(){
allDivs.hide().filter('[' + yourAttributeName + '=' + jQuery(this).attr(yourAttributeName) + ']').show();
})
//check the init checked
.filter(':checked')
//and fire click event to filter
.click();
});

How can I know which radio button is selected via jQuery?

I have two radio buttons and want to post the value of the selected one.
How can I get the value with jQuery?
I can get all of them like this:
$("form :radio")
How do I know which one is selected?
To get the value of the selected radioName item of a form with id myForm:
$('input[name=radioName]:checked', '#myForm').val()
Here's an example:
$('#myForm input').on('change', function() {
alert($('input[name=radioName]:checked', '#myForm').val());
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form id="myForm">
<fieldset>
<legend>Choose radioName</legend>
<label><input type="radio" name="radioName" value="1" /> 1</label> <br />
<label><input type="radio" name="radioName" value="2" /> 2</label> <br />
<label><input type="radio" name="radioName" value="3" /> 3</label> <br />
</fieldset>
</form>
Use this..
$("#myform input[type='radio']:checked").val();
If you already have a reference to a radio button group, for example:
var myRadio = $("input[name=myRadio]");
Use the filter() function, not find(). (find() is for locating child/descendant elements, whereas filter() searches top-level elements in your selection.)
var checkedValue = myRadio.filter(":checked").val();
Notes: This answer was originally correcting another answer that recommended using find(), which seems to have since been changed. find() could still be useful for the situation where you already had a reference to a container element, but not to the radio buttons, e.g.:
var form = $("#mainForm");
...
var checkedValue = form.find("input[name=myRadio]:checked").val();
This should work:
$("input[name='radioName']:checked").val()
Note the "" usaged around the input:checked and not '' like the Peter J's solution
You can use the :checked selector along with the radio selector.
$("form:radio:checked").val();
If you want just the boolean value, i.e. if it's checked or not try this:
$("#Myradio").is(":checked")
Get all radios:
var radios = jQuery("input[type='radio']");
Filter to get the one thats checked
radios.filter(":checked")
Another option is:
$('input[name=radioName]:checked').val()
$("input:radio:checked").val();
In my case I have two radio buttons in one form and I wanted to know the status of each button.
This below worked for me:
// get radio buttons value
console.log( "radio1: " + $('input[id=radio1]:checked', '#toggle-form').val() );
console.log( "radio2: " + $('input[id=radio2]:checked', '#toggle-form').val() );
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form id="toggle-form">
<div id="radio">
<input type="radio" id="radio1" name="radio" checked="checked" /><label for="radio1">Plot single</label>
<input type="radio" id="radio2" name="radio"/><label for="radio2">Plot all</label>
</div>
</form>
Here's how I would write the form and handle the getting of the checked radio.
Using a form called myForm:
<form id='myForm'>
<input type='radio' name='radio1' class='radio1' value='val1' />
<input type='radio' name='radio1' class='radio1' value='val2' />
...
</form>
Get the value from the form:
$('#myForm .radio1:checked').val();
If you're not posting the form, I would simplify it further by using:
<input type='radio' class='radio1' value='val1' />
<input type='radio' class='radio1' value='val2' />
Then getting the checked value becomes:
$('.radio1:checked').val();
Having a class name on the input allows me to easily style the inputs...
try this one.
it worked for me
$('input[type="radio"][name="name"]:checked').val();
In a JSF generated radio button (using <h:selectOneRadio> tag), you can do this:
radiobuttonvalue = jQuery("input[name='form_id\:radiobutton_id']:checked").val();
where selectOneRadio ID is radiobutton_id and form ID is form_id.
Be sure to use name instead id, as indicated, because jQuery uses this attribute (name is generated automatically by JSF resembling control ID).
Also, check if the user does not select anything.
var radioanswer = 'none';
if ($('input[name=myRadio]:checked').val() != null) {
radioanswer = $('input[name=myRadio]:checked').val();
}
If you have Multiple radio buttons in single form then
var myRadio1 = $('input[name=radioButtonName1]');
var value1 = myRadio1.filter(':checked').val();
var myRadio2 = $('input[name=radioButtonName2]');
var value2 = myRadio2.filter(':checked').val();
This is working for me.
I wrote a jQuery plugin for setting and getting radio-button values. It also respects the "change" event on them.
(function ($) {
function changeRadioButton(element, value) {
var name = $(element).attr("name");
$("[type=radio][name=" + name + "]:checked").removeAttr("checked");
$("[type=radio][name=" + name + "][value=" + value + "]").attr("checked", "checked");
$("[type=radio][name=" + name + "]:checked").change();
}
function getRadioButton(element) {
var name = $(element).attr("name");
return $("[type=radio][name=" + name + "]:checked").attr("value");
}
var originalVal = $.fn.val;
$.fn.val = function(value) {
//is it a radio button? treat it differently.
if($(this).is("[type=radio]")) {
if (typeof value != 'undefined') {
//setter
changeRadioButton(this, value);
return $(this);
} else {
//getter
return getRadioButton(this);
}
} else {
//it wasn't a radio button - let's call the default val function.
if (typeof value != 'undefined') {
return originalVal.call(this, value);
} else {
return originalVal.call(this);
}
}
};
})(jQuery);
Put the code anywhere to enable the addin. Then enjoy! It just overrides the default val function without breaking anything.
You can visit this jsFiddle to try it in action, and see how it works.
Fiddle
$(".Stat").click(function () {
var rdbVal1 = $("input[name$=S]:checked").val();
}
This works fine
$('input[type="radio"][class="className"]:checked').val()
Working Demo
The :checked selector works for checkboxes, radio buttons, and select elements. For select elements only, use the :selected selector.
API for :checked Selector
To get the value of the selected radio that uses a class:
$('.class:checked').val()
I use this simple script
$('input[name="myRadio"]').on('change', function() {
var radioValue = $('input[name="myRadio"]:checked').val();
alert(radioValue);
});
Use this:
value = $('input[name=button-name]:checked').val();
DEMO : https://jsfiddle.net/ipsjolly/xygr065w/
$(function(){
$("#submit").click(function(){
alert($('input:radio:checked').val());
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table>
<tr>
<td>Sales Promotion</td>
<td><input type="radio" name="q12_3" value="1">1</td>
<td><input type="radio" name="q12_3" value="2">2</td>
<td><input type="radio" name="q12_3" value="3">3</td>
<td><input type="radio" name="q12_3" value="4">4</td>
<td><input type="radio" name="q12_3" value="5">5</td>
</tr>
</table>
<button id="submit">submit</button>
If you only have 1 set of radio buttons on 1 form, the jQuery code is as simple as this:
$( "input:checked" ).val()
I've released a library to help with this. Pulls all possible input values, actually, but also includes which radio button was checked. You can check it out at https://github.com/mazondo/formalizedata
It'll give you a js object of the answers, so a form like:
<form>
<input type="radio" name"favorite-color" value="blue" checked> Blue
<input type="radio" name="favorite-color" value="red"> Red
</form>
will give you:
$("form").formalizeData()
{
"favorite-color" : "blue"
}
JQuery to get all the radio buttons in the form and the checked value.
$.each($("input[type='radio']").filter(":checked"), function () {
console.log("Name:" + this.name);
console.log("Value:" + $(this).val());
});
To retrieve all radio buttons values in JavaScript array use following jQuery code :
var values = jQuery('input:checkbox:checked.group1').map(function () {
return this.value;
}).get();
try it-
var radioVal = $("#myform").find("input[type='radio']:checked").val();
console.log(radioVal);
Another way to get it:
$("#myForm input[type=radio]").on("change",function(){
if(this.checked) {
alert(this.value);
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form id="myForm">
<span><input type="radio" name="q12_3" value="1">1</span><br>
<span><input type="radio" name="q12_3" value="2">2</span>
</form>
From this question, I came up with an alternate way to access the currently selected input when you're within a click event for its respective label. The reason why is because the newly selected input isn't updated until after its label's click event.
TL;DR
$('label').click(function() {
var selected = $('#' + $(this).attr('for')).val();
...
});
$(function() {
// this outright does not work properly as explained above
$('#reported label').click(function() {
var query = $('input[name="filter"]:checked').val();
var time = (new Date()).toString();
$('.query[data-method="click event"]').html(query + ' at ' + time);
});
// this works, but fails to update when same label is clicked consecutively
$('#reported input[name="filter"]').on('change', function() {
var query = $('input[name="filter"]:checked').val();
var time = (new Date()).toString();
$('.query[data-method="change event"]').html(query + ' at ' + time);
});
// here is the solution I came up with
$('#reported label').click(function() {
var query = $('#' + $(this).attr('for')).val();
var time = (new Date()).toString();
$('.query[data-method="click event with this"]').html(query + ' at ' + time);
});
});
input[name="filter"] {
display: none;
}
#reported label {
background-color: #ccc;
padding: 5px;
margin: 5px;
border-radius: 5px;
cursor: pointer;
}
.query {
padding: 5px;
margin: 5px;
}
.query:before {
content: "on " attr(data-method)": ";
}
[data-method="click event"] {
color: red;
}
[data-method="change event"] {
color: #cc0;
}
[data-method="click event with this"] {
color: green;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form id="reported">
<input type="radio" name="filter" id="question" value="questions" checked="checked">
<label for="question">Questions</label>
<input type="radio" name="filter" id="answer" value="answers">
<label for="answer">Answers</label>
<input type="radio" name="filter" id="comment" value="comments">
<label for="comment">Comments</label>
<input type="radio" name="filter" id="user" value="users">
<label for="user">Users</label>
<input type="radio" name="filter" id="company" value="companies">
<label for="company">Companies</label>
<div class="query" data-method="click event"></div>
<div class="query" data-method="change event"></div>
<div class="query" data-method="click event with this"></div>
</form>
$(function () {
// Someone has clicked one of the radio buttons
var myform= 'form.myform';
$(myform).click(function () {
var radValue= "";
$(this).find('input[type=radio]:checked').each(function () {
radValue= $(this).val();
});
})
});

Categories

Resources