onchange not working with radio button - javascript

I have a few radio buttons which should call hider(something); when they change, meaning when they are checked or unchecked. This works, i.e. when checked they call the JS function, however, if they're unchecked due to selecting another radio button from that group, it does not call the js script again.
Do I need to use something else than onchange?
This is what the radio buttons look like at the moment:
<input name="ostype" type="radio" value="0" onchange="hider(solaris);">solaris
<input name="ostype" type="radio" value="1" onchange="hider(linux);">linux
My hider function is currently:
function hider(divid) {
if ($(divid).is('.hidden')) {
$(divid).removeClass('hidden');
} else {
$(divid).addClass('hidden');
}
}

Since this question is still not answered correctly yet ranks quite high for me in Google for "radio button onchange", here's a proper solution for anyone still looking.
If you're using jQuery, just use jQuery's attribute selector as noted by Flavius Stef.
OP, it's not entirely clear what your code does. Let's assume in your code you want to add the "hidden" class to whatever radio button is active.
$("your selector here").change(function() {
$('input[name="' + this.name + '"]').removeClass("hidden");
$(this).addClass("hidden");
});
Please note the difference between $(this) (the jQuery object) and this (the DOM object). Basically I'm removing the "hidden" class from every input that goes by the same name, and then I add the "hidden" class to the current input.
Of course I'm assuming here that you're not using duplicate names for different inputs on the page. Also note that this would only work for radio buttons, as the radio button "change" event only fires when activated, not when deactivated.
Listening for onchange on both checkboxes and radio buttons
In my case, I wanted to add a "checked" class to active radio buttons and checkboxes. Since the checkbox fires the "onchange" event both when checked and unchecked, I needed a bit of extra code.
$('input[type="radio"]').change(function() {
$('input[name="' + this.name + '"]').removeClass("checked");
$(this).addClass("checked");
});
$('input[type="checkbox"]').change(function() {
$(this).toggleClass("checked", ($(this).is(":checked")));
});
The latter function uses toggleClass to set the "checked" class if .is(":checked") is true.
Alternatively you might want to combine the two functions into something like:
$('input[type="radio"], input[type="checkbox"]').change(function() {
if(this.type == "radio")
$('input[name="' + this.name + '"]').removeClass("checked");
$(this).toggleClass("checked", ($(this).is(":checked")));
});
Either way, always be careful when listening for an onclick event as it will not fire when the input is activated through keyboard navigation.

Use onclick.
Also as the argument of your function call you'll need to either use a string with the id as a jQuery selector ('#solaris') - better yet use this:
<input name="ostype" type="radio" value="0" onclick="hider(this);">solaris

Bind change event to ALL radio buttons on document ready:
$(function(){
$('input[name=list_type]:radio').on("change", function(){
showHideBlock();
});
showHideBlock();
});
Show -- hide block depends on ONE radio button status:
function showHideBlock(){
if ($("#Option").is(':checked')){
$('#Block').show();
} else {
$('#Block').hide();
}
}

<input name="ostype" type="radio" value="0" onclick="hider('solaris');">solaris
<input name="ostype" type="radio" value="1" onclick="hider('linux');">linux
function hider(divid) {
$( 'div.div_class' ).hide();
$( '#' + divid ).show();
}
Make sure you add a class to call the divs and make sure you put quotes around solaris and linux in the function calls

Here's a version that you might draw inspiration from (tested on Chrome and FF):
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.4.4/jquery.min.js">
</script>
</head>
<body>
<input type="radio" name="ostype" checked="checked" onclick="hider('linux')">linux
<input type="radio" name="ostype" onclick="hider('solaris');">solaris
<div id="content">
<div id="linux">linux</div>
<div id="solaris" style="display:none;">solaris</div>
</div>
<script>
function hider(divname) {
$('#content div').each(function(){
$(this).hide();
});
$('#'+divname).show();
}
</script>
</body>
</html>

If I understand you correctly you can just use an onClick on every button and hide the others while showing the one your clicking on.
Like this:
function showInfo(info)
{
var info = document.getElementById("1");
info.style.display = "block";
var info = document.getElementById("2");
info.style.display = "none";
}
So the first one is showing and the second one is hiding.
Then just add one for every div that should be hidden.
You can also do this with jQuery.
function showAndHide(val1, val2)
{
$(val1).hide();
$(val2).show();
}
And don't forget to have style="display:none" in every div.

did you declare the vars solaris and linux?
otherwise your browser should show you an Error

Related

Capturing a button click as part of a field validation

I have an onblur='validate(this)' on a text field but I do not want the validate code to run when a cancel button is clicked.
function validate(oField) {
if (document.getElementById('Cancel').clicked != true) {
console.log("Cancel clicked");
}
}
<input id='reviewername'
name='reviewername'
type='text'
class='$class'
value='$reviewername'
tabindex=1
size=$size
onkeydown='setKeyCode(event)'
onblur='validate(this)'/>;
<input type='submit'
name='Button'
id='Cancel'
value='Cancel'>;
The document.getElementById('Cancel').clicked is always 'undefined'.
I have tried addListener(), probably incorrectly, as well as other newbie tricks with no success!
What I am trying to do is check whether the Cancel button is clicked while the text field has the focus. Immediately I click the button, the text field event 'onblur' runs. I want to check for the button click as the first part of the javascript validate() function.
Is what I am attempting even possible?
Please help before I lose the rest of my hair.
You can use àddListener() if you name it correctly as addEventListener().
Then, you can set some variable when the cancel button is clicked and use that variable in replacement to your document.getElementById(...).clicked.
cancel_clicked = false;
function validate(oField) {
if (cancel_clicked != true) {
console.log("Cancel not clicked");
} else {
console.log("Cancel clicked");
}
}
<input id='reviewername'
name='reviewername'
type='text'
class='$class'
value='$reviewername'
tabindex=1
size=$size
onkeydown='setKeyCode(event);'
onblur='validate(this);'/>
<input type='submit'
name='Button'
id='Cancel'
value='Cancel'
onclick='cancel_clicked = true;'/>
Browsers are removing direct event listener attachment to DOM elements, it's better to use javascript to add the event listeners, instead of the onlick or onblur attributes on DOM elements, this is what I've noticed lately.. So you are more safe with using addEventListener, also do watch out for your spelling too incases where you get undefined,or you are loading your script before your DOM tree.. As a thumb rule, load your javascript file last.

Javascript not checking radio button

The following script is not checking working when testing the radio button
<script type="text/javascript">
function checkButton(){
if(document.getElementById('Revise').checked = true){
alert("hello");
}
}
</script>
The html code is:
<form:radiobutton id= "Revise" value="Revise" name="status" path="status"></form:radiobutton>
Do i need to call the function/or place it in the body?
As most people have mentioned within their comments, you either need to
write
if(document.getElementById('Revise').checked === true)(newbie way)
or
write if(document.getElementById('Revise').checked) (pro way)
Also, you haven't invoked the function "checkButton", this is how you do it:
<form> <input type="radio" id= "Revise" value="Revise" name="status" path="status" onclick="checkButton()"> Click Me!! </form>
First off, your code is not working because you defined a function (checkButton) that never make a call to, thus it is never executed.
I'm not sure of what you are trying to do but you should avoid using in-line javascript.
If you are trying to run the alert when the radio button is clicked then add an click event listener on the radio.
document.getElementById('Revise').addEventListener('click',function() {
alert('Hello');
});
JSFindle
If you are trying to define a function called checkButton that checks your radio and shows an alert then your function would be defined like this:
function checkButton() {
document.getElementById('Revise').checked = true;
alert('Hello');
}
JSFindle
And then you would just invoke checkButton() on your trigger.

Disable/Enable Input when checkbox is clicked jQuery

I'm attempted to only allow the submit button in a form to be enabled when a user has checked off a checkbox. I've gotten the button to start disabled, then become enabled when the checkbox is initially clicked on, but if I then uncheck the checkbox, the button doesn't become re-enabled.
HTML:
<input type="checkbox" id="waivercheck">
<input class="submit join-button" type="submit" value="Join Now" id="joinevent" disabled>
Script:
$(document).ready(function() {
$('#waivercheck').click(function(){
if($(this).checked){
$('#joinevent').prop("disabled",false);
} else {
$('#joinevent').prop("disabled",true);
}
});
});
Can anyone help?
You can access the checkbox status via this.checked and not $(this).checked. And I recommend using the change event.
$(document).ready(function() {
$('#waivercheck').change(function(){
if(this.checked){
$('#joinevent').prop("disabled",false);
} else {
$('#joinevent').prop("disabled",true);
}
});
});
Demo: https://jsfiddle.net/rbnndz23/
Your issue is with the conditional.
A jQuery object doesn't have a checked property but the DOM element itself does
Instead of
if($(this).checked)
Can do
// native element has checked property
if(this.checked)
Or
// jQuery is() with pseudo selector
if($(this).is(':checked'))
You don't need to use $(this).checked. Instead try using this.checked. See here.

Fire an event on input.checked=true/false _without_ jQuery

Consider the following code (http://jsfiddle.net/FW36F/1/):
<input type="checkbox" onchange="alert(this.checked)">
<button onclick="document.getElementsByTagName('input')[0].checked=!document.getElementsByTagName('input')[0].checked;">toggle</button>
If you click the checkbox, you get an alert telling you if it's checked or not. Great. However, if you click the toggle button, the checkbox changes it's checked state but the onchange event is NOT fired.
Essentially, the onchange for a checkbox only fires if the user actually clicks the checkbox, not if the checkbox is changed via JavaScript. This is be true in IE, FF, and Chrome. It appears that this behavior is to specification also.
However, I really need some kind of event to fire if, for any reason, the checkbox's checked state changes. Is this possible?
Oh yeah, and jQuery is not allowed. And please no setTimeout/setInterval based solutions either...
Update: Also, I should make it clear that the code above is for illustration only. In the real code, we need to ensure the state of the checkbox is checked or unchecked -- not just toggle it. Perhaps this would be better code to illustrate that:
<input type="checkbox" onchange="alert(this.checked)">
<button onclick="document.getElementsByTagName('input')[0].checked=true;">check</button>
<button onclick="document.getElementsByTagName('input')[0].checked=false;">un check</button>
Moreover, there may be code in other areas we don't fully control, which might do a simple .checked=true/false -- we'd like to make sure we see that also.
The existing answers work just fine, even with your update. Just be smart about it and don't call click if you don't need to. Also, please don't use inline JS. That was OK 10 years ago.
<input type="checkbox" onchange="alert(this.checked)">
<button id='check'>check</button>
<button id='uncheck'>uncheck</button>
document.getElementById('check').onclick = function() {
if (!this.checked) {
this.click();
}
}
If you need to be modified when a script changes the value, in Firefox, you can use https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Object/watch
Example here http://jsfiddle.net/PPuZ8/
// In FF $ is a shortcut for document.getElementById
// It doesn't fire when set from the UI, you have to use a regular handler for that
$('cb').watch("checked", function(){
console.log('Checked state changed from script', arguments);
return true;
});
For IE you can use onpropertychange http://msdn.microsoft.com/en-us/library/ie/ms536956(v=vs.85).aspx (Thanks to jivings for the reminder)
Example: http://jsfiddle.net/PPuZ8/1/
document.getElementById('cb').onpropertychange = function() {
if (event.propertyName == 'checked') {
console.log('Checked state changed onproperty change');
}
};
For other browsers, you have to poll using setInterval/setTimeout
Have the toggle button actually click the checkbox:
<input type="checkbox" onchange="alert(this.checked)">
<button onclick="document.getElementsByTagName('input')[0].click()">
toggle
</button>
If you wanted any change to the checkbox to inform you of its new position, then I would create a global method for changing the value of the checkbox, and deal with it as a proxy:
<script>
function toggleCB( state ) {
var cb = document.getElementById("cb");
arguments.length ? cb.checked = state : cb.click() ;
return cb.checked;
}
</script>
<input id="cb" type="checkbox" />
<input type="button" onClick="alert( toggleCB(true) )" value="Check" />
<input type="button" onClick="alert( toggleCB(false) )" value="Uncheck" />
<input type="button" onClick="alert( toggleCB() )" value="Toggle" />​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​
Now anytime you set or toggle the checkbox, you'll get the checked state back.
One last thing, I would avoid using the onClick attribute, and instead bind the click events up from within your JavaScript.
Use click()
<button onclick="document.getElementsByTagName('input')[0].checked=!document.getElementsByTagName('input')[0].click();">toggle</button>
oninput is the event you need to handle ...
https://developer.mozilla.org/en/DOM/DOM_event_reference/input

Trigger some jQuery code when a radio button is selected

I have these two radio buttons:
Original <input id="video_is_derivative_false" name="video[is_derivative]" type="radio" value="false">
Derivative (<i>ex. remix, mashup etc...</i>) <input id="video_is_derivative_true" name="video[is_derivative]" type="radio" value="true">
and I want to call some jQuery code when the "Derivative" button is selected. How can I do this?
Just attach a change event to it:
$('#video_is_derivative_true').change(function(){
console.log("Selected");
})
example: http://jsfiddle.net/niklasvh/cyADB/
$("#video_is_derivative_true").click(function(){
alert("your code goes here");
});
Add an onclick handler to the input tag
You could also put something on the change handler
$("#video_is_derivative_true").change(function(){
if($(this).is(':checked')){
alert("more code here");
}
});
You will want to monitor the change event, then in the handler, check to make sure that the button is checked. The second part is important because the change event will also fire when it becomes unchecked. The code would look something like this:
$('#video_is_derivative_true').change(function() {
if (this.checked) {
alert('derivative checked!');
}
});
Here's a live demo ->
$('#video_is_derivative_true').bind('click change', function() {
if (this.checked) {
// derivative is checked
}
});
$("#video_is_derivative_true").click(function(){ alert("your code goes here"); });

Categories

Resources