Get the value of checked radio button without re-selecting the buttons - javascript

So I am getting some buttons as follows:
var reportFilterButtons = $('input[name=reportfilter]', '#reportChartForm');
Later on this easily allows me to attach a change handler as follows:
reportFilterButtons.change(handlers.reportFilterButtonsChange);
Inside of this handler I need to get the value of the currently checked button, so I do this:
var checkedReportFilterButton = $('input[name=reportfilter]:checked', '#reportChartForm');
....
if (checkedReportFilterButton.val() ....
The reportFilterButtons and checkedReportFilterButton selectors seem redundant however. Is there a way to get the checked/value by working against reportFilterButtons and not doing the second selection?

You could use $.filter to find the checked one:
reportFilterButtons.filter(':checked').val()

A jQuery event listener handler this property points to the element that was the target of the event. This means that you don't have to find it again. Just wrap in a jQuery object $(this), and you're good to go (fiddle demo).
Code:
<div id="reportChartForm">
<input type="radio" name="reportfilter" value="1">
<label>Radio 1</label>
<input type="radio" name="reportfilter" value="2">
<label>Radio 2</label>
<input type="radio" name="reportfilter" value="3">
<label>Radio 3</label>
</div>
var reportFilterButtons = $('input[name=reportfilter]', '#reportChartForm');
reportFilterButtons.change(reportFilterButtonsChange);
function reportFilterButtonsChange() {
var value = $(this).val(); // this is the reference to the element
console.log(value);
}

Related

How to get the value of selected radio button where multiple radio buttons have same name using javascript

All of these radio buttons have an onclick method in which I am trying to get the value of the selected radio button.
<div id="interior">
<label><input type="radio" name="groundfloordropdown" value="125">1BHK</label>
<label><input type="radio" name="groundfloordropdown" value="175">2BHK</label>
<label><input type="radio" name="groundfloordropdown" value="225">3HK</label>
</div>
You can use JQuery to get the value by
let value = $('input[name="groundfloordropdown"]:checked').val().
var names = document.getElementsByName("groundfloordropdown");
groundfloordropdown.forEach((ground) => {
if (ground.checked) {
alert(`Choise: ${ground.value}`);
}
})
this is a pure js
have a good day :)
Do not declare js events inside tags. This will lead to many bad consequences.
I made you a little javascript code using the forEach() method. This method is required to work with the collection. Namely, when you work with many elements that have the same class, or it will be the same tag.
Also, in this example you get the value of the input tag and the label tag.
If you have any questions, let me know. I will answer with pleasure.
let radio = document.querySelectorAll('.radiogroup input');
let label = document.querySelectorAll('.radiogroup label');
radio.forEach(function (radio_current, index) {
radio_current.addEventListener('change', function () {
console.log('Value Radio: ' + this.value + '; Value Label: ' + label[index].innerText);
});
});
<div class="radiogroup">
<label><input type="radio" name="groundfloordropdown" value="125">1BHK</label>
<label><input type="radio" name="groundfloordropdown" value="175">2BHK</label>
<label><input type="radio" name="groundfloordropdown" value="225">3HK</label>
</div>

Jquery select from a collection of jquery objects which is checked

I haven't been able to find this answer. I don't know if I'm searching wrong or my lexicon is incorrect but I am trying to get the selected elements of a group of jquery radio buttons. Here is my JS code:
var hideFieldsBasedOnRadioButtonValue = function () {
var $employmentStatusRadioButtons = $(".edit-profile-employment-information input[name='user[profile_attributes][employment_status]']");
var displayOrHideRequiredFields = function ($radioButton) {
if ($radioButton.val() === "Full Time" || $radioButton.val() === "Part Time") {
$radioButton.closest("div.form-row").next(".required-input-when-yes").removeClass("d-none");
} else {
$radioButton.closest("div.form-row").next(".required-input-when-yes").addClass("d-none");
}
}
displayOrHideRequiredFields($(".edit-profile-employment-information input[name='user[profile_attributes][employment_status]']:checked"));
$employmentStatusRadioButtons.on("change", function () {
displayOrHideRequiredFields($(this));
});
}
This is a stripped down version of this function. I have a few more radio buttons that need to either hide or display additional fields depending on the radio button's value. What I'm having trouble with specifically is I want to trim this line down:
displayOrHideRequiredFields($(".edit-profile-employment-information input[name='user[profile_attributes][employment_status]']:checked"));
the $employmentStatusRadioButtons are a collection of jquery objects and I'm unable to figure out how to grab the selected one. Any help would be amazing.
Instead of using the same ".edit-profile-employment-information input[name='user[profile_attributes][employment_status]']" selector on this line and on line 2 of the code I want to do something like
displayOrHideRequiredFields($employmentStatusRadioButtons:checked);
Now that won't work. The closest I've been able to get this to work is by doing the following;
displayOrHideRequiredFields($employmentStatusRadioButtons.selector + ":checked")
But I don't really like how that looks. We aren't using ES6 or else it would be awesome.
I haven't been able to find anything to help me in this regard. Does anyone know any methods specifically where I can do something like this?
You can use the jquery filter() function for filtering a variable with jQuery objects.
var $radios = $('[name=test],[name=test2]');
var $radiosFiltered = $radios.filter(':checked');
$radiosFiltered.each(function(){
console.log($(this).val());
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="radio" name="test" value="1" checked>
<input type="radio" name="test" value="2">
<input type="radio" name="test" value="3">
<input type="radio" name="test2" value="4">
<input type="radio" name="test2" value="5" checked>
<input type="radio" name="test2" value="6">
You was so close, you need to use filter to get the checked elements from your collection :
$employmentStatusRadioButtons.filter(':checked');

Take value for each check box if checked Javascript

I still learning javascript, i think this is ez question, but i can't fix it with my experience (already try search some source), this my code
This is example:
PHP
<?php
<input type="checkbox" checked="checked" value="1" class="box_1">1</label> // checked
<input type="checkbox" value="2" class="box_1">2</label> //unchecked
<input type="checkbox" checked="checked" value="3" class="box_1">3</label> // checked
<input type="checkbox" value="4" class="box_1">4</label> //unchecked
<input type="checkbox" checked="checked" value="5" class="box_1">5</label> // checked
<input type="button" value="Submit" id="button-price" class="button" />
?>
I try check the check box with javasript by class, (i can't use by name&id because i use looping)
I try build condition like this Javascript :
$('#button-price').bind('click', function() {
var box = '';
$(".box_1").each(function(){ // for each checkbox in class box_1(1-5)
if(this).attr("checked","true"){ // if this checked box is true
var value = (this.value).toLowerCase(); // take the value
box = box + value; // store to box
}
});
});
when click button then take value and store to box,
I know there error in here if(this).attr("checked","true"){
what it should be writing the condition?
Try using prop instead of attr
if($(this).prop('checked')) {
}
Hope this helps.
You can use the jQuery .prop() method to check the checkbox state:
if ($(this).prop("checked")) { // if this checked box is true
box += $(this).val().toLowerCase(); // store to box
}
Suggestion: (this.value).toLowerCase() will work but try not mixing up jQuery code with pure javascript. Instead of it you can use the solution above.

Problems with retrieving radio button value for feedback form

I'm trying to build a simple feedback form. The user will answer a series of yes or no questions. If they choose no, then they will be provided with a comment form to include text.
Currently, I'm having problems with retrieving radio button values. I am trying to print them in the console, but nothing happens when I choose the appropriate choice. If the user chooses 'no', it needs to be able to remember the comment that will get submitted.
My JSFiddle is here: http://jsfiddle.net/787x18vx/
HTML
<p>You are providing feedback</p>
<form>
<div id="question-1">
<label for="question-1">Is this correct?</label>
<input type="radio" value="yes" name="choice-1" />Yes
<input type="radio" value="no" name="choice-1" />No
</div>
<div id="question-2">
<label for="question-2">Another question</label>
<input type="radio" value="yes" name="choice-2" />Yes
<input type="radio" value="no" name="choice-2" />No
</div>
<div id="question-3">
<label for="question-3">One more question</label>
<input type="radio" value="yes" name="choice-3" />Yes
<input type="radio" value="no" name="choice-3" />No
</div>
<br />
<button>Send Feedback</button>
</form>
jQuery
var firstInput = 'input[name=choice]';
var firstInputValue = $('input[name=choice-1]:checked').val();
$(firstInput).on('click', function() {
console.log(firstInputValue);
console.log($('input[name="choice-1"]:checked').val());
console.log($('input[name="choice-2"]:checked').val());
// if value === 'no' show comment form
});
You are using input[name=choice] selector which is not exisiting.
Use input[type=radio] instead.
var firstInput = 'input[type=radio]';
var firstInputValue = $('input[name=choice-1]:checked').val();
$(firstInput).on('click', function() {
console.log(firstInputValue);
console.log($('input[name="choice-1"]:checked').val());
console.log($('input[name="choice-2"]:checked').val());
// if value === 'no' show comment form
});
Fiddle
var firstInput = 'input[name=choice]';
This is looking for something specifically with the name choice, which doesn't appear to be in your html.
There are two quick ways about this.
First, just change your selector:
$('input[type=radio]').on('click', function(){...
This will trigger the function on a click of any radio
Another way is with the wildcard selector:
var firstInput = 'input[name^=choice]';
The ^ should make is so any input with the name starting with choice gets selected.
This method should work, but targeting input[type=radio] is probably a better solution,
You are missing the -1 in your name
var firstInput = 'input[name=choice-1]';
Your selector is trying to get tags with name exactly equals 'choice'. You can search by prefix with the following
var firstInput = 'input[name|="choice"]';
This will get all tags which name starts with 'choice'

How to manually check a YUI radio "button"

<script type="text/javascript">
(function () {
var ButtonGroup = YAHOO.widget.ButtonGroup;
var onCheckedButtonChange = function (p_oEvent) {
};
YAHOO.util.Event.onContentReady("mediaFilterButtonsFieldset", function () {
var oButtonGroup = new ButtonGroup("mediaFilterButtons");
oButtonGroup.on("checkedButtonChange", onCheckedButtonChange);
});
}());
</script>
<div id="resultInfo">
<form id="button-example-form" name="button-example-form" method="post">
<fieldset id="mediaFilterButtonsFieldset">
<div id="mediaFilterButtons" class="yui-buttongroup ie7filter" style="z-index:11;">
<div id="mediaFilterLabel">Go to</div>
<input id="radio1" class="filter_but" type="radio" name="0" value="First" checked rel="0" >
<input id="radio2" class="filter_but" type="radio" name="2" value="Second" rel="2">
<input id="radio3" class="filter_but" type="radio" name="1" value="Third" rel="1">
</div>
</fieldset>
</form>
</div>
These are my YUI buttons. They're just 3 radio buttons turned into "buttons"--literally. My question is this:
After people click the third button, I cannot manually check the first button anymore. How can I manually check "radio1"?
Edit:
According to the official YUI website, there is a method called "set". But I don't know how to use that in this buttonGroup.
The radio buttons must all have the same name attribute in order for them to be grouped together.
Answering your question with the set method. Perhaps this does the trick:
YAHOO.one("#radio1").set("checked",true);
To manually check the radio buttons, it's necessary to have the same name of radio button. Put the same name of radio button and get your result.

Categories

Resources