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');
Related
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>
First time asking here. I tried a number of topics for this, and I currently use a code for checkboxes, but it's for gathering into a mailform and sending to me via php. I can't seem to find exactly what I need for the following scenario.
I am reworking some Flash puzzles to be all html and javascript (or jquery). One puzzle requires the player to enter a code (to open a safe). In Flash they clicked buttons with code symbols on them, so I thought, Checkboxes displayed as images could work...
I have 9 checkboxes. Each has a value from 1 to 9. In the layout they are mixed up (they are not positioned on the page in sequential order) and I use images to represent the checkboxes.
I want to find out if all the boxes are selected, and if they are selected in the exact order of 1-9.
If the checkboxes are checked in the correct order according to their value (1,2,3,4,5,6,7,8,9) then on clicking the Submit button, the player is taken to the next webpage.
I can also do this with names or Ids, whatever works. Or php. I was hoping to keep it simple, because I am not savvy with the javvy. I probably know enough to be dangerous to myself and others :)
Thanks in advance for any help, or links to a topic that could point me in the right direction.
Here's my html code.
<form name="checklist" method="post" action="My-Page.php">
<label>
<input type="checkbox" value="8">
<img src="btn_8.png"></label>
<label>
<input type="checkbox" value="3">
<img src="btn_3.png"></label>
<label>
<input type="checkbox" value="9">
<img src="btn_9.png"></label>
<label>
<input type="checkbox" value="2">
<img src="btn_2.png"></label>
<label>
<input type="checkbox" value="5">
<img src="btn_5.png"></label>
<label>
<input type="checkbox" value="4">
<img src="btn_4.png"></label>
<label>
<input type="checkbox" value="7">
<img src="btn_7.png"></label>
<label>
<input type="checkbox" value="1">
<img src="btn_1.png"></label>
<label>
<input type="checkbox" value="6">
<img src="btn_6.png"></label>
<input type="submit" value="Open">
</form>
Here's the js I found that gets the values, but I don't know how to make it get the values in that specific order, and then go to a URL, or alert the user to an error.
var array = []
var checkboxes = document.querySelectorAll('input[type=checkbox]:checked')
for (var i = 0; i < checkboxes.length; i++) {
array.push(checkboxes[i].value)
}
Update. I struggled with this, and finally asked a friend to help. What took me 8 days, he did in like 1 hour, from scratch.
I do appreciate those who took time to give me some hints, and this site is great for learning.
As you didn't share code , I will not help you fix it. I can give you some hints and you can try to implement that.
Call onClick function on each checkbox selection.
Create an array and push the selected checkbox's values into it.
// example: checkedArr = [1,2,3,4];
maintain a final order of values with another array
// expectedArr = [1,2,3,4];
Deep compare those 2 arrays and depending on their result, proceed with your business logic.
Comparing two array with their order
var is_same_arr = (checkedArr.length == expectedArr.length) && checkedArr.every(function(element, index) {
return element === expectedArr[index];
});
Here is one way to do it in JavaScript. You maintain a selected array that you either add to or remove items from as the checkboxes are clicked. Then, when the form is submitted, you do a couple checks: first you see if all boxes have been checked. Next, you see if all of the numbers in the selected array are in order.
const form = document.querySelector("#form");
let selected = [];
const numberOfCheckboxes = document.querySelectorAll("#form input").length;
form.addEventListener("click", function(e) {
if (e.target.nodeName !== "INPUT") return;
if (e.target.checked) {
selected.push(parseInt(e.target.value));
} else {
selected = selected.filter(el => el != e.target.value);
}
})
function check(e) {
console.log(selected);
if (selected.length !== numberOfCheckboxes) {
e.preventDefault();
alert("You didn't select all the boxes");
}
const inOrder = selected.every((el, i, arr) => i === 0 || el === arr[i-1] + 1);
if (!inOrder) {
e.preventDefault();
alert("Wrong order!");
}
}
<form id="form" onsubmit="return check(event)">
<label>
<input type="checkbox" value="1" /> 1
</label>
<label>
<input type="checkbox" value="2" /> 2
</label>
<label>
<input type="checkbox" value="3" /> 3
</label>
<button>submit</button>
</form>
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.
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'
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);
}