Javascript to jQuery Get value of Radio button - javascript

After having successfully completed an application in Javascript, I am trying to make it more jQuery friendly. However, when I try to get the value of a radio button like so:
// relavent declarations:
var radio = $("[name='buttons']"); // 4 radio buttons
var val = '';
var score = 0;
for( var q in radio ) {
if (radio[q].checked)
val = radio[q].val();
}
if(val === correct) {
score++;
}
What I'm trying to do is make it so that the equivalent in straight Javascript is like this:
for( var q in radio ) {
if (radio[q].checked)
val = radio[q].value;
}
if(val === correct) {
score++;
}
My Javascript console keeps giving me the error "Uncaught TypeError: Object # has no method 'val'" What is the problem?

try this
$('input:radio').each(function(){
if($(this).is(':checked'))
var value = $(this).val();
});

radio[q] will give you a raw DOM node object, you probably want the associated jQuery object, so try radio[q].eq(q).
See: http://api.jquery.com/eq/

Try below code :
$(":radio:checked").each(function(){
val = $(this).val();
})

i think you are writing some thing that have an answer and user if checked correct one then he will get a score
Suggestion 1) Give all the check box the same name , so that only one can be checked
<input type="radio" name="Answer" />
Suggestion 2) get the selected checkbox value from myForm
$('input[name=radioName]:checked', '#myForm').val()

As close as I think you want.
$(document).ready(function() {
var radio = $("input[type='radio']");
for (var i in radio) {
i = parseInt(i);
var r = radio[i];
if ($(r).prop("checked") == true) {
console.log($(r).val());
}
}
})
})
Added the readout of the value

Related

Uncaught TypeError: Cannot read property 'prop' of undefined

I have 6 input checkboxes and if checkboxes are checked more than 3 the last one gets unchecked. For better understanding refer my previous question. Which is solved.
Now, I have another problem, Now 3 checkboxes are checked already by Math.random. On click of any unchecked checkbox. I'm getting error in console.
Uncaught TypeError: Cannot read property 'prop' of undefined
Fiddle Demo
code below:
var random_checked = $("input[type=checkbox]").get().sort(function(){
return Math.round(Math.random())-0.6; //so we get the right +/- combo
}).slice(0,3);
$(random_checked).prop('checked', true);
var checked = [];
$('input[type=checkbox]').change(function(e) {
var num_checked = $("input[type=checkbox]:checked").length;
if (num_checked > 3) {
checked[checked.length - 1].prop('checked', false);
checked.pop();
}
if($.inArray($(this), checked) < 0){
checked.push($(this));
}
});
You can try the below code
var checked = $('input[type=checkbox]:checked').map(function(){
return $(this);
}).get(); // First change
$('input[type=checkbox]').change(function(e) {
var num_checked = $("input[type=checkbox]:checked").length;
if (num_checked > 3) {
$(checked.pop()).prop('checked', false);// Second change
}
if($.inArray($(this), checked) < 0){
checked.push($(this));
}
});
DEMO FIDDLE
Changes Made
► Stored the currently checked elements to an array using
var checked = $('input[type=checkbox]:checked').map(function(){
return $(this);
}).get();
► $(checked.pop()) is used to select the last inserted element.
Why your code was not working?
As per you code var checked = []; will be empty at the initial stage. So checked[checked.length - 1] will become undefined.
You should push initial items in checked list.
$(random_checked).each(function(){
console.log($(this));
checked.push($(this));
});
https://jsfiddle.net/usx8Lkc5/18/
This one works, just simply adding lastChecked = random_checked[2]; so that your lastChecked is defined.
var random_checked = $("input[type=checkbox]").get().sort(function(){
var test = Math.round(Math.random())-0.6;
return test; //so we get the right +/- combo
}).slice(0,3);
$(random_checked).prop('checked', true);
lastChecked = random_checked[2];
var $checks = $('input:checkbox').click(function(e) {
var numChecked = $checks.filter(':checked').length;
if (numChecked > 2) {
alert("sorry, you have already selected 3 checkboxes!");
lastChecked.checked = false;
}
lastChecked = this;
});

jquery .val() not returning correct value

In the below function I want to show and hide an element based on other options selected on the page (radio buttons). The problem is, the var complianceMember always returns the first value for the set of radio buttons it's part of and not the selected value, why is this? The other two variables return the correct values.
$(document).ready(function() {
$('input[name="waste-management-plan"]').change(function () {
var producerType = $('input[name="producertype"]').val();
var complianceMember = $('input[name="compliance-member"]').val();
if ($(this).val() == 'Y' && complianceMember == 'Y' && producerType == 'both' ) {
$('.producerOp3').show();
} else {
$('.producerOp3').hide();
console.log( $(this).val(),complianceMember,producerType );
}
});
});
You need to use a filter to find the checked radio button and then get its value. You can use the :checked selector
var complianceMember = $('input[name="compliance-member"]:checked').val();
Since you mentioned radio group, you have to get the value of radio button which is checked
var complianceMember = $('input[name="compliance-member"]:checked').val();

Execute custom function onChange

Pure JavaScript.
I have a checkbox in HTML page. I want to execute
App.setCheckedProperty(name, val);
Where name is name attribute of the checkbox and val true/false means checked.
How to implement it? I can't find any materials aboit it on the Net.
UPD:
<input type="checkbox" name="smth" onChange="<WHAT TO DO HERE?>" checked />
Final execution must be equal:
App.setCheckedProperty("smth", false);
UPD2:
Are there any contructions like this.name or this.checked in JavaScript?
you shouldnt do it "inline" inside your html. its just bad practice. i think what you want to do is to loop over a couple of checkboxes?
see this code:
// declare all vars that you need and find all input-elements
var i, input, inputs = document.getElementsByTagName('input');
// loop over all input-elements
for(i = 0; i <= inputs.length; i++) {
input = inputs[i];
// if the current element is a checkbox
if(input.type === 'checkbox') {
//append a click-handler to that checkbox
input.onclick = function () {
// if the checkbox is clicked, you can find the name and the checked-property
App.setCheckedProperty(this.name, this.checked);
};
}
}
and a working example here (i just alert instead of App.setCheckedProperty): http://jsfiddle.net/5wExJ/

Capturing the value of the proper input if one is a checkbox

Given the following markup:
<input name="active" type="hidden" value="0" />
<input id="active" name="active" type="checkbox" value="1" />
When the checkbox is unchecked and the form is submitted the server will get a value of "0" for the "active" param. When the checkbox is checked and the form is submitted the server will get a value of "1" for the "active" param. This works just fine.
What I want to do is capture the proper value in JavaScript based upon that. The trick, however, is I don't know if the input is a checkbox or not. As far as my script is concerned it is just acting on a set of inputs.
I have created a JSFiddle here: http://jsfiddle.net/bcardarella/5QRjF/ that demonstrates the issue.
TL;DR I want to ensure the value I capture from each input is the actual value sent to the server.
Don't know if you actually want to check for the checkbox or not, but this code works:
$(function() {
var getCheckBoxValue = function() {
if ($('[name="active"]:checkbox').attr("checked")) {
return $('[name="active"]:checkbox').val();
} else {
return $('[name="active"]').val();
}
}
var result = $('#result');
result.append($('<p/>', {text: 'Expected value 0, got: ' + getCheckBoxValue()}));
$(':checkbox')[0].checked = true;
result.append($('<p/>', {text: 'Expected value 1, got: ' + getCheckBoxValue()}));
});
Basically if the checkbox is checked, use that, otherwise, go with the default value from the hidden input.
Edit
Turned my comment into a fiddle, I've also added another field, a text field, to show better the idea behind it: http://jsfiddle.net/45qup/
Hope it helps!
Write up the click event for the checkbox..
$('#active').on('click', function(){
var isChecked = this.checked;
var val = 0;
if(isChecked){
val = 1
}
});
Try somthing like
$("form#formID :input").each(function(){
if ($(this).attr() == 'checkbox') return $(this).checked();
else return $(this).val();
});
Not sure if if I’d go with this ;) , but it works:
var getCheckBoxValue = function() {
var values = $('[name="active"]')
.filter(':checked, :hidden')
.map(function(){
return parseInt($(this).val(), 10);
}
);
return Math.max.apply(Math, values);
}
http://jsfiddle.net/Xc5H7/1/
Inspired by #Deleteman's idea, this is a slightly simpler way of doing it:
var getCheckBoxValue = function() {
var input = $('[name="active"]');
return $(input[1].checked ? input[1] : input[0]).val();
}
This assumes there's only two fields with this name, which is a sane assumption for what you're trying to do.
It also assumes the hidden field always comes before the checkbox, which again, since this is, I assume, for Rails, is a sane assumption :)

javascript check radio buttons automatically

I wanna check radio buttons automatically: I tried this code but it does not work:
Radio buttons have 3 different values, I wanna select the radio button with value 'clean".
How can I check automatically radio buttons on a webpage?
Thanks!
function getElements()
{
for (i=0; i<document.getElementsByTagName('input').length; i++)
{
//if (document.getElementsByTagName('input')[i].type == 'radio')
if(document.getElementsByTagName('input')[i].type=='radio')
{
//if (document.getElementsByTagName('input')[i].value=='clean')
document.getElementsByTagName('input')[i].click();
}
}
I modified the code as following:
for (i=0; i<document.getElementsByTagName('input').length; i++)
{
if(document.getElementsByTagName('input')[i].type=='radio')
{
if(document.getElementsByTagName('input')[i].value == "clean")
{
document.getElementsByTagName('input')[i].checked =true;
}
}
}
but it is not still working:(
the radio buttons are in a iframe, can it be the reason why the code is not working?
Give your radio buttons "names" would make things a lot easier
<input type="radio" name="myradios" value="clean"/>
<input type="radio" name="myradios" value="somethingelse"/>
var elements = document.getElementsByName('myradios');
for (i=0;i<elements.length;i++) {
if(elements[i].value == "clean") {
elements[i].checked = true;
}
}
Working example : http://jsfiddle.net/Dwzc9/
Updated
getElementsByName doesn't seem to be supported in all IE versions ... so you could use the following based on your original example :
var allElems = document.getElementsByTagName('input');
for (i = 0; i < allElems.length; i++) {
if (allElems[i].type == 'radio' && allElems[i].value == 'clean') {
allElems[i].checked = true;
}
}
Working example : http://jsfiddle.net/Dwzc9/2/
you might try setting the "checked" attribute instead.
var getElements = function()
{
var x = document.getElementsByTagName("input");
var oldname = '';
for(var i = 0; i < x.length; i++)
{
if(x[i].type == 'radio' && x[i].name != oldname && x[i].value == 'clean')
{
x[i].checked = true;
oldname = x[i].name;
}
}
};
The problem with this function is that it will attempt to check all the radio buttons, so if they belong to a group (which is usually the case), only the last radio button from each group will be selected. If that is your intention, then great, otherwise it bears thinking about how to decide which button is selected, and breaking the loop. You can see in the function above that I have decided to select only the first button in the group, by checking the name attribute of the element.
I hope this helps you!
Matt
UPDATE
Another way to handle this, using jQuery, would be:
var getElements = function(){
var oldname = '';
$.each($('input[type="radio"]'), function(){
if($(this).attr('name') != oldname && $(this).val() == 'clean'){
$(this).checked = true;
oldname = this.name;
}
});
};

Categories