How to get the selected radio button label text using jQuery - javascript

I have a radio button like this on page
<div id="someId">
<label class="radio-inline">
<input name="x" type="radio" onchange="GetSelectedVal();">Yes</label>
<label class="radio-inline">
<input name="x" type="radio" onchange="GetSelectedVal();">No</label>
</div>
On page load I don't want to set any selection so not using checked property. In my JavaScript function, how can I get the value Yes or No based on the user selection at runtime?
function GetSelectedVal() {
console.log($('#someId input:radio.........);
}
I have seen similar questions but unable to find solution of this issue.

Remove onchange inline handler from HTML. Use on to bind events.
:checked will select the checked radio button. closest will select the parent label and text() will get the label associated with the radio button. e.g. Yes
$('[name="x"]').on('change', function () {
alert($('[name="x"]:checked').closest('label').text());
});
DEMO

You can simple pass this in onchange="GetSelectedVal(); like onchange="GetSelectedVal(this);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="someId">
<label class="radio-inline"><input name="x" type="radio" onchange="GetSelectedVal(this);">Yes</label>
<label class="radio-inline"><input name="x" type="radio" onchange="GetSelectedVal(this);">No</label>
</div>
<script>
function GetSelectedVal(ele) {
alert($(ele).closest('label').text());
}
</script>

I would do it a bit different than the accepted answer.
Instead of having events on multiple radio buttons, you can have one on the containing div. Also let just the checked radio trigger the change:
$('#someId').on('change', 'input[name="x"]:checked', function () {
var label = $(this).siblings('span').text();
console.log(label);
});
When I have text next to other elements I prefer wrapping the text in span's:
<div id="someId">
<label class="radio-inline"><input name="x" type="radio"><span>Yes</span></label>
<label class="radio-inline"><input name="x" type="radio"><span>No</span></label>
</div>
A demo: jsfiddle.net/qcxgwe66/

Related

Change label text with jQuery but not other label elements

I have 2 radio buttons and each of them inside a label.
<fieldset>
<label><input type="radio" name="invoice_type" value="Receipt"> Receipt</label>
<label><input type="radio" name="invoice_type" value="Invoice"> Invoice</label>
</fieldset>
I tried to change the label text with jQuery with this code but it replaces entire label content, including the radio boxes.
$('fieldset>label:eq(0)').text('Some text');
$('fieldset>label:eq(1)').text('Some text');
how i can replace only the label text without touching the radio boxes?
You should consider rearranging your HTML.
$('fieldset>label:eq(0)').text('Some teqxt');
$('fieldset>label:eq(1)').text('Some text');
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<fieldset>
<label for="label1">Receipt</label>
<input type="radio" id="label1" name="invoice_type" value="Receipt">
<label for="label2">Invoice</label>
<input type="radio" id="label2" name="invoice_type" value="Invoice">
</fieldset>
To make minimal changes to your layout and still not need an id= and related for=:
add a span to wrap your text and target the span
this also has the added bonus of allowing some styling to be added to the span, eg for consistent spacing
label>input+span { margin-left:0.75em; }
without relying on additional spaces in both the original markup and in the replacement text
$("button").click(() => {
$('fieldset>label:eq(0)>span').text('Some text');
$('fieldset>label:eq(1)>span').text('Some other text');
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<fieldset>
<label>
<input type="radio" name="invoice_type" value="Receipt">
<span>Receipt</span>
</label>
<label>
<input type="radio" name="invoice_type" value="Invoice">
<span>Invoice</span>
</label>
</fieldset>
<button>click me</button>
Note
https://api.jquery.com/eq-selector/#eq1
As of jQuery 3.4, the :eq pseudo-class is deprecated. Remove it from your selectors and filter the results later using .eq().
left it in above so that it matches OPs code more closest, the alternative would be:
$("fieldset>label").eq(0).find(span)
or target the individual label directly
$("input[value='Receipt']").next()
(based on the current layout)
Using simple vanilla JS this is easy (no clue about jQuery though, stopped using that in 2015), and does not require any changes in the markup:
document.querySelector('fieldset>label').childNodes[1].textContent = ' foo';
document.querySelector('fieldset>label+label').childNodes[1].textContent = ' bar';
<fieldset>
<label><input type="radio" name="invoice_type" value="Receipt"> Receipt</label>
<label><input type="radio" name="invoice_type" value="Invoice"> Invoice</label>
</fieldset>
Here is a solution that does not require to change your HTML and uses jquery:
$('fieldset>label:eq(0)').contents()[1].textContent = 'Some teqxt';
$('fieldset>label:eq(1)').contents()[1].textContent = 'Some text';
If you have multiple tags inside the <label> tag you can use the more correct filtering version:
$('fieldset>label:eq(0)').contents().filter(function () { return this.nodeType === 3; })[0].textContent = 'Some teqxt';
$('fieldset>label:eq(1)').contents().filter(function () { return this.nodeType === 3; })[0].textContent = 'Some text';

formidable toggle switch, how to click the label?

Currently, the below HTML code only switches when you click the input (ie. the center switch).
I need the switch to happen when you click the labels (ie. Yes or No).
How to make that happen?
<div>
<span class="frm_off_label frm_switch_opt">No</span>
<label class="frm_switch">
<input type="checkbox" name="2002" id="field_2002" value="Yes" checked="checked"
data-off="No" data-sectionid="2002" data-frmval="Yes" placeholder="Yes">
<span class="frm_slider"></span>
</label>
<span class="frm_on_label frm_switch_opt">Yes</span>
</div>
What are the ways to make the click of Yes or No, do the same thing as clicking the input?
You can achieve this by setting the checked status of input -
HTML
<div>
<span class="frm_off_label frm_switch_opt">No</span>
<label class="frm_switch">
<input type="checkbox" name="2002" id="field_2002" value="Yes" checked="checked"
data-off="No" data-sectionid="2002" data-frmval="Yes" placeholder="Yes">
<span class="frm_slider"></span>
</label>
<span class="frm_on_label frm_switch_opt">Yes</span>
</div>
JS (with jquery)
$('.frm_off_label').on('click', function(){
$(this).next('label').find("input")[0].checked = false;
});
$('.frm_on_label').on('click', function(){
$(this).prev('label').find("input")[0].checked = true;
});
CSS (optioanl)
.frm_switch_opt{
cursor:pointer;
}
You can see it in action on jsfiddle
https://jsfiddle.net/guruling/tegmps9b/27/
You can use label combine with for="element_id" like for="field_2002" attribute to achieve it.
The for attribute specifies which form element a label is bound to.
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div>
<label for="field_2002" class="frm_off_label frm_switch_opt">No</label>
<input type="checkbox" name="2002" id="field_2002" value="Yes" checked="checked"
data-off="No" data-sectionid="2002" data-frmval="Yes" placeholder="Yes">
<label for="field_2002" class="frm_on_label frm_switch_opt">Yes</label>
</div>

javascript check radio button on a <span> element - UX

I have multiple radio buttons, each one inside a <span> with margin, so they seem like a button with a radio element inside. how can I check the radio button when I click anywhere inside the <span> parent element of the radio button
UX oriented
<span class="radio-box" id="white-box">
<input type="radio" id="white" name="colour"> White
</span>
<span class="radio-box" id="red-box">
<input type="radio" id="red" name="colour"> Red
</span>
<span class="radio-box" id="blue-box">
<input type="radio" id="blue" name="colour"> Blue
</span>
sorry, very noob at Javascript
thanks :)
This is exactly what label elements are for. Use those, rather than span elements:
<label class="radio-box" id="white-box">
<input type="radio" id="white" name="colour"> White
</label>
<label class="radio-box" id="red-box">
<input type="radio" id="red" name="colour"> Red
</label>
<label class="radio-box" id="blue-box">
<input type="radio" id="blue" name="colour"> Blue
</label>
When the label wraps the input like that, it's associated with that input. (If you couldn't use wrapping, you could use the for attribute to tell the label what the id of its associated input is.)
You could make it work with spans. Targeting just those spans:
$("span > input[type=radio][name=colour]").parent().on("click", function() {
$(this).find("input[type=radio][name=colour]").prop("checked", true);
});
or targeting any input[type=radio] inside a span.radio-box:
$("span.radio-box > input[type=radio]").parent().on("click", function() {
$(this).find("input[type=radio]").prop("checked", true);
});
But again, this is exactly what label is for, so best to use that.
If you want to do this without the <label> tag and without jquery and just vanilla JavaScript then here's a solution.
var radioBoxes = document.querySelectorAll("span.radio-box");
radioBoxes.forEach(function (box) {
var radioButton = box.querySelector("input[type='radio']");
box.addEventListener("click", function () {
radioButton.click();
});
});

without an event for a radiobutton or checkbox, how can I set it true or false programmatically

I have a page with radiobuttons and checkboxes; the form has previously been filled out by the user. I need to bring the form back up for them to edit the EXISTING data, which means I have to programmatically check checkboxes and check radio buttons.
If I HAD an event, I could easily change the corresponding control with srcElement, but there is no event in this case. I haven't been able to find a way with document.getElementById('XXX'). ??? to work in any way.
Using Angular 4 if that helps.
Thoughts?
Thanks in advance, :-)
Use data binding. Then you can set the changed value and the checkbox and radio buttons will check/select automatically.
Here is an example:
<label>
<input id="sendCatalogId"
type="checkbox"
[(ngModel)]="sendCatalog"
name="sendCatalog" >
Send me your catalog
</label>
And a radio button:
<label class="radio-inline">
<input type="radio" id="addressType1Id" value="home"
[(ngModel)]="addressType"
name="addressType">Home
</label>
<label class="radio-inline">
<input type="radio" id="addressType1Id" value="work"
[(ngModel)]="addressType"
name="addressType">Work
</label>
<label class="radio-inline">
<input type="radio" id="addressType1Id" value="other"
[(ngModel)]="addressType"
name="addressType">Other
</label>
This in the component class:
...
export class CustomerComponent {
sendCatalog = false;
addressType = "home";
constructor() {
sendCatalog = true;
addressType = "work";
}
}

Show / Hide contents base on radio button selection

I am trying to toggle a content DIV base on the selection of radio buttons.
HTML for radio button.
<div class="row-fluid">
<label class="radio">
<input type="radio" name="account" id="yes" value="yes" checked>
Yes, I have an existing account
</label>
<label class="radio">
<input type="radio" name="account" id="no" value="no">
No, I don't have an account
</label>
</div>
Content DIV
<div id="account_contents">
<p>This is account contents.......</p>
</div>
This is how I tried it in jquery.
$('#no').bind('change',function(){
$('#account_contents').fadeToggle(!$(this).is(':checked'));
$('#account_contents').find("input").val("");
$('#account_contents').find('select option:first').prop('selected',true);
});
But it doesn't work for me correctly. Here I want to show this content DIV only if user don't have an account.
Can anybody tell me how to fix this problem?
seems you need .on('change') for radio buttons not just for one of them
$('input[type="radio"][name="account"]').on('change',function(){
var ThisIt = $(this);
if(ThisIt.val() == "yes"){
// when user select yes
$('#account_contents').fadeOut();
}else{
// when user select no
$('#account_contents').fadeIn();
$('#account_contents').find("input").val("");
$('#account_contents').find('select option:first').prop('selected',true);
}
});
Working Example
$(document).ready(function(){
$('.radio input[type="radio"]').on("click", function(){
if($('.radio input[type="radio"]:checked').val() === "yes"){
$("#account_contents").slideDown("slow");
}else{
$("#account_contents").slideUp("slow");
}
});
});
I'm not sure if I got you right, but this fiddle toggles #account_contents depending on which button you click:
This was how i tweaked the script:
$('#no').bind('change',function(){
$('#account_contents').fadeToggle(!$(this).is(':checked'));
$('#account_contents').find("input").val("");
$('#account_contents').find('select option:first').prop('selected',true);
});
$("#yes").bind("change", function() {
$('#account_contents').fadeOut();
});

Categories