Getting the value of a checked radio button using javascript [duplicate] - javascript

This question already has answers here:
How to get the selected radio button’s value?
(19 answers)
Closed 5 years ago.
I am trying to access the value of a checked radio button in my form using JavaScript only, no jQuery. I have looked this up and seen many answers but when I copy the same code into my project it doesn't work for some reason. Here is my code.
<form>
<input type="radio" name="style" value="3" checked>
<input type="radio" name="style" value="5">
<input type="radio" name="style" value="10">
</form>
I tried to access the value using this JavaScript code:
var value = document.querySelector('input[name="style"]:checked').value;
console.log(value);
I would assume this would give me the string of 3 as the logged value. When I try this example I get the following error:
request.js:1 Uncaught TypeError: Cannot read property 'value' of null
at request.js:1
I also tried using a for loop of an array of the inputs named style and that didn't work either. It found all three inputs but didn't have values for them in the array. Can someone please explain what is wrong? And if this is obvious please be patient I am still learning I am just trying to get better.

Your code is correct, you only need is an event to run the selector code to get the value of selected value. See below code :- you can also use javascript selector for click event instead of function placement in onclick event handler.
function run_test(){
var radio_ele = document.querySelector('input[name="style"]:checked');
console.log(radio_ele.value);
}
<form>
<input type="radio" name="style" value="3">
<input type="radio" name="style" value="5">
<input type="radio" name="style" value="10">
<button type="button" onclick="run_test()">click</button>
</form>

function getValue() {
var value = document.querySelector('input[name="style"]:checked').value;
console.log(value);
}
<form>
<input type="radio" name="style" value="3" checked>
<input type="radio" name="style" value="5">
<input type="radio" name="style" value="10">
<button type="button" onclick="getValue()">click</button>
</form>
you code is working fine, except you need event to get latest value after load

Related

How to force radio buttons to remain checked when checking another radio buttons field?

Hi I have two ratings fields on my page, when the first rating is checked and I check the second one, the first one is unchecked. It's not a problem in back-end because the value of the ratings is already saved but for the visitors it's a problem because the stars disappears.
Is there a way in javascript or jQuery to say : if this field is check it remains check ?
<script src="https://code.jquery.com/jquery-1.10.2.js"></script>
<fieldset class="rate">
<input id="5-stars-1" type="radio" name="firstRate" value="5" />
<label for="5-stars-1">5</label>
<input id="4-stars-1" type="radio" name="firstRate" value="4" />
<label for="4-stars-1">5</label>
</fieldset>
<fieldset class="rate2">
<input id="5-stars-2" type="radio" name="secondRate" value="5" />
<label for="5-stars-2">5</label>
<input id="4-stars-2" type="radio" name="secondRate" value="4" />
<label for="4-stars-2">5</label>
</fieldset>
Do you have any idea ?
If you need more infos or more extract from my code don't mind to ask !
Alright so thanks to Rory and Sathish, the answer is really simple :
Radio are designed to be checked once at a time so I couldn't do what I wanted, instead I simply need to switch to checkboxes and the problem is solved !
Thanks again !

Cloning forms with radio buttons

Cloning forms in jQuery, for example to create an RSVP option on a guest list with multiple people, is relatively simple.
$(selector).clone().insertAfter(selector:last)
It's relatively easy with inputs as well, offering the ability to copy methods or properties by passing true to the clone() method. To cope with multiple inputs you can append [] to the end of your input names:
<input type="text" name="email_address[]"/>
However this becomes more complicated with <input> elements of type radio, as you would usually use these to denote a choice:
<input type="radio" name="choice" value="1"/> <input type="radio" name="choice" value="2"/>
Adding the square bracket syntax further confuses things, as there are still multiple values, and some browsers may now allow different selections:
<label>Person:</label> <input type="radio" name="choice[]" value="1"/> <input type="radio" name="choice[]" value="2"/>
<label>Person:</label> <input type="radio" name="choice[]" value="1"/> <input type="radio" name="choice[]" value="2"/>
How can we solve this in a way which allows easy cloning whilst not making radio buttons hard to parse on the back end?
Turns out this can be achieved with a little bit of RegEx fun!
Firstly add a numeric value to your first input element:
<input type="radio" name="choice[0]" value="1"> <input type="radio" name="choice[0]" value="2">
Now in your JavaScript
$(selector).clone().insertAfter(selector:last)
.find('input[type="radio"]').each(function(){
var name=$(this).attr('name');
$(this).attr('name',name.replace(/([0-9]+)/g,1*(name.match(/([0-9]+)/g))+1));
});
Which creates a simple increment in numbers for each element in line with their siblings.

Preventing radio buttons from being clicked completely

This has been bugging me for a while now. I'm trying to prevent users from clicking on a radio button depending if the user has the access to do so. The first solution was to do the following:
Without disabled
<input type="radio" name="my_radio1" id="abc1" value="5">
<input type="radio" name="my_radio1" id="abc2" value="0">
<input type="radio" name="my_radio1" id="abc3" value="1" checked>
With disabled with pre-selection
<input type="radio" name="my_radio2" id="abc1" onclick="return false;" value="5">
<input type="radio" name="my_radio2" id="abc2" onclick="return false;" value="0">
<input type="radio" name="my_radio2" id="abc3" onclick="return false;" value="1" checked>
With disabled and no pre-selection
<input type="radio" name="my_radio3" id="abc1" onclick="return false;" value="5">
<input type="radio" name="my_radio3" id="abc2" onclick="return false;" value="0">
<input type="radio" name="my_radio3" id="abc3" onclick="return false;" value="1">
As shown here: http://jsfiddle.net/93CqR/6/
This works great for radio buttons ALREADY checked but doesn't work for boxes that haven't been checked (as shown in example 3 above). Are there any known workarounds to this?
Chrome and IE behave differently with this
You should add a 'disabled' attribute to the ones not selectable. You don't really need the javascript.
see http://jsfiddle.net/Ma6TA/
<input type="radio" name="my_radio2" id="abc1" value="5" disabled>
<input type="radio" name="my_radio2" id="abc2" value="0" disabled>
<input type="radio" name="my_radio2" id="abc3" value="1" checked disabled>
Update I don't know the actual use case here, but if you aren't already, the actual check for this should be done on the server. Disabling or hiding the input from the user with javascript will enhance the UX, but a nefarious user could get around these things.
I would use javascript to show/hide the elements that users have access to. For 2 reasons.
1) It's a better user experience if they can only see the form elements they can manipulate.
and more importantly
2) a disabled form field WILL NOT show up in the post/get array. I've had issues with this in the past and it is a very frustrating problem if you don't know why you're fields aren't coming through.
it could be as simple as wrapping js code in a php conditional ie...
<?php if($userCantSeeThese): ?>
<script>
$('.classOfElementsUserShouldntSee').hide();
</script>
<?php endif; ?>

clicking on custom checkbox does not run the associated onClick function

I'm trying to use Ryan Fait's custom checkboxes. These are much more readable than the standard checkboxes, but clicking on them does not run the associated onClick functions. Any advice will be appreciated. The relevant portion of my code follows:
<p style="font-family:arial; font-size:large">
<input type="checkbox" class="styled" id="level-0" type="radio" value="0"
onClick="count();"> 0 (ages 5-7)
<input type="checkbox" class="styled" id="level-1" type="radio" value="1"
onClick="count();" checked> 1 (beginner)
<input type="checkbox" class="styled" id="level-2" type="radio" value="2"
onClick="count();" checked> 2 (easy)
<input type="checkbox" class="styled" id="level-3" type="radio" value="3"
onClick="count();" checked> 3 (intermediate)
<input type="checkbox" class="styled" id="level-4" type="radio" value="4"
onClick="count();"> 4 (challenging)
<input type="checkbox" class="styled" id="level-5" type="radio" value="5"
onClick="count();"> 5 (hard)
<input type="checkbox" class="styled" id="level-all" type="radio" value="6"
onClick="all_levels();"> All
<input id="available" type="button" style="background-color:white; border:2px;
font-family:arial; font-size:large" value="??"> </p> <br>
From Styling Checkboxes and Radio Buttons With CSS and JavaScript on Ryan Fait's site:
How does it work?
In a nutshell, the JavaScript looks for every form element with
class="styled" on it; hides the real form element; sticks a span tag
with a CSS class on it next to the element; and, finally, mouse events
are added to the span that handles the visual stages form inputs go
through when they are clicked.
Your inline onClick handlers are not firing because your checkboxes aren't actually being clicked. Ryan explicitly says that it "hides the real form element; sticks a span tag with a CSS class" ... so you are actually clicking on the <span> that Ryan's code inserted; the real checkbox is hidden.
Later in the article, Ryan says outright:
onChange and other JavaScript events
This script utilizes JavaScript's onChange and other events. Because
these events can only be used once, if you want to add more functions
to an event, you will need to call them from inside my script.
You will need to call them from inside my script
Take your onClick= out of the <input> tags; add your code to his code -- you'll have to figure out which bit of your code to call from his code, since I see you're doing different things from your onClicks.
You should also take your style="..." out of your tags and use a stylesheet, but that's a separate issue.

Dynamically change input id with value - input type=range

I'm making a phone gap query mobile iOS app for course evaluation at my uni. This app primary function will be a form that in it's original form uses radio buttons where each value also has a corresponding id - e.g.
<input name="q10" id="1" value="1" type="radio" />
<input name="q10" id="2" value="2" type="radio" />
<input name="q10" id="3" value="3" type="radio" />
<input name="q10" id="4" value="4" type="radio" />
<input name="q10" id="5" value="5" type="radio" />
<input name="q10" id="6" value="6" type="radio" />
But radio buttions aren't that intuitive on iOS devices so I'm using input type range instead.
This works great for changing the value between 1 and 6 but the problem is that one only specifies one id for the whole input, not one id per value.
<input type="range" name="q10" id="q10" value="0" min="0" max="6" />
Is there a way to change the id with the value? I think this should be doable through JavaScript but I lack the know-how. I also cannot change the way the database is set up (requiring both id and value) as this database belongs to the university's IT-department.
You can use the change event
<input type="range" onchange="this.id=this.value" name="q10" id="q10" value="0" min="0" max="6" />
Working example here - http://jsfiddle.net/aVHm8/
Note: I always feel uneasy about changing the ID of a DOM element .. perhaps you should investigate better options to resolve your issue
The database can't know what the id is unless you use JavaScript to send it to the server (standard form submission sends the name and the value). In which case find the bit of JS that pulls out the ID and just send the value twice instead.

Categories