I was wondering if somebody can tell me how I can check if the checkbox status has changed. The problem is that I'm using a bootstrap theme (AdminLTE) which gives me a fancy checkbox, but I can't put a onchange or onclick on the checkbox, because I will be kind of hidden underneath the "makeup".
So I'm looking for a solution that does something on checkbox status change (true or false), while you cant "acces" the checkbox with an onclick etc. in html.
Checkbox plugin: icheck.
The code for the checkbox:
<span class="input-group-addon">
<input id="username" type="checkbox" class="minimal">
</span>
Thanks in advance (:
Edit: Most answers here will work for regular checkboxes (Might be usefull for others), but for my problem there was 1 working answer. But I'd like to thank everybody (:
Attach an event handler for ifChanged event.
$('input').on('ifChanged', function(event){
alert(event.type + ' callback');
});
You can choose the preferred event as you need, which is fired by iCheck plugin : check here.
check this example
JS
$('input:checkbox[name=example]').change(function() {
alert("Hello!");
});
HTML
<input type="checkbox" name="example" /> click me
Try this..
$(document).ready(function(){
$("#x").change(function(){
if ( $("#y").val().length == 0 )
{
$("#y").val(0);
var a = parseInt($('#x').val(), 10);
var b = parseInt($('#y').val(), 10);
$('#z').val(a+b);
}
else{
var a = parseInt($('#x').val(), 10);
var b = parseInt($('#y').val(), 10);
$('#z').val(a+b);
}
});
Related
I have group of checkboxes and that are compulsory to be applied but the situation is user can be able to check only one check box at a time. So, for this I have implemented something like this with the help of internet. No doubt it works fine when there are no checkbox checked by default. But suppose, one of the checkbox is checked true when page loads, then this does not works unitl I click on checkbox twice.
Here is what I am using::
So , Assuming I have set of 5 checkboxes, I set same class name for all the checkboxes and then
<input type="checkbox" class="myclass" onclick="Checkme(this.className);"/>
<input type="checkbox" class="myclass" onclick="Checkme(this.className);"/>
<input type="checkbox" class="myclass" onclick="Checkme(this.className);"/>
<input type="checkbox" class="myclass" onclick="Checkme(this.className);"/>
<input type="checkbox" class="myclass" onclick="Checkme(this.className);"/>
In View page I have declared::
function Checkme(class_Name) {
Check_OR_Uncheck(class_Name);
}
In Common js::
function Check_OR_Uncheck(class_Name) {
$("." + class_Name).click(function () {
if ($(this)[0].checked) {
$("." + class_Name).each(function () {
$(this)[0].checked = false;
});
$(this)[0].checked = true;
}
else {
$(this)[0].checked = false;
}
});
}
Please Help me to achieve this..
Keep your code in the document ready event. This will register the click event for "myclass".
$(".myclass").click(function () {
if ($(this)[0].checked) {
$(".myclass").each(function () {
$(this)[0].checked = false;
});
$(this)[0].checked = true;
} else {
$(this)[0].checked = false;
}
});
jsfiddle
You could use document ready handler and call method:
jsFiddle
$(function(){
$(':checkbox:checked').each(function(){
Checkme(this.className);
});
});
Try this
$(function(){
$('.myclass').click(function(){
var s=$(this).prop('checked');
if(s==true)
{
$('.myclass').prop('checked',false)
$(this).prop('checked',true)
}
});
});
Or
You simply can use
if(s==true)
{
$(this).siblings().prop('checked',false);
}
FIDDLE
Try this
$(function(){
$('input:checkbox').prop('checked', false)
$('input:checkbox').click(function(){
if($(this).is(':checked')){
$('input:checkbox').not(this).prop('checked', false);
}
});
})
Instead of implementing a group of check boxes that behave like a group of radio buttons, I suggest implementing a group of radio buttons that look like a group of check boxes:
input[type=radio] {content:url(mycheckbox.png)}
input[type=radio]:checked {content:url(mycheckbox-checked.png)}
This approach simplifies your implementation; you have two one-line CSS rules instead of a JS event handler function, event binding (on both document ready and the HTML element itself), not to mention a possible dependency on jQuery (if you choose to use it).
The catch to this approach is that it requires CSS3 support. For more info, check out this SO answer: https://stackoverflow.com/a/279510/2503516
I have a checkbox on the webpage and I want that when the check box is ticked a prompt should come with a 'message and YES\NO button'. Clicking YES should take the user to the next website and clicking NO just close the prompt.
How can this be done using Javascript.How will the program know if the checkbox is yicked or not? I read using addeventlistner but i dont know how to use it. Can someone share an example.
You can use addEventListener to bind event
document.getElementById('testcb').addEventListener('change', function () {
if (this.checked) {
if (confirm('Really Take me to new loaction?')) {
alert("Take me to new loaction");
//window.location.href = newURL;
}
}
}, false);
DEMO
I would recommend using a library, like jQuery, and you could do somtehing like this
HTML:
<input type="checkbox" name="testcb" id="testcb" />
JavaScript:
$(function() {
$('#testcb').click(function() {
if (this.checked) {
if (confirm('Really?'))
window.location.href = newURL;
}
});
});
Careful with addEventListener : it will not work with IE 8 and below, and 'change' event is buggy in the same browser (IE8-) (http://www.quirksmode.org/dom/events/change.html)
Add a JavaScript function on check box event ,
HTML
<input id="chk" onclick="doSomething()" type="checkbox">
javascript function :
function doSomething()
{
var x = document.getElementById("chk").checked;
if (x)
{ var conf = confirm("checkbox is checked, proceed ?");
if (conf == true) {
window.location = "http://www.google.com";
}
}
}
Don't forget to add reference of jQuery (you can add from googleAPI)
I am trying to check if a radio box is checked using JavaScript, but I can't seem to figure it out properly.
This is the HTML code:
<input type="radio" name="status" id="employed_yes" value="yes">
<input type="radio" name="status" id="employed_no" value="no">
I have tried using jQuery as follows:
$(document).ready(function() {
if($('#employed_yes').is(':checked')) {
// do something
}
});
Also, I tried using pure Javascript by getting the element and check its 'checked' attribute, but it didn't work.
I look forward to your insight!
Thank you!
Use onchange
$('input[type="radio"]').on('change',function(){
if($('#employed_yes').is(':checked')) {
alert("yes");
}
});
DEMO
Try to check using name of the radio buttons like
if($('input[name="status"]').val() != "") {
// do something
} else {
alert("Select an Status");
}
Your solution doesn't work because when the page loads the checkbox's default state is unchecked, which is when the jQuery code runs.
You need to listen for the change event on the checkbox like so:
$(document).ready(function() {
$("#employed_yes").change(function() {
if(this.checked) {
document.write("checked");
}
});
});
Demo: http://jsfiddle.net/7CduY/
Try this. This will alert Hi on document ready if the any radio button is checked. If you want to check on specific event then you can bind on any event to check same.
$(document).ready(function() {
if($('input[type=radio]').is(':checked')) {
alert("Hi");
}
});
if($('input:radio:checked').text("yes") {
// do something
}
Got the idea from the jQuery forum. http://forum.jquery.com/topic/how-to-check-whether-all-radio-buttons-have-been-been-selected
Dude, I think you Wanted, whether radio button is checked or not, this what i understand from your question
If so here it is
$(document).ready(function() {
$('input[type="radio"]').on('change',function(){
if($('[name=status]:checked').length) {
alert("checked");
}
});
});
FIDDLE DEMO
Pure JS:
<input type = "button" value = "What?" name = "wic" onclick = "whatischecked(this.name);" />
Event onClick:
function whatischecked(name) {
var
emp = document.getElementById("employed_yes").checked
nonemp = document.getElementById("employed_no").checked
if (emp) {
alert("Employed");
};
if (nonemp) {
alert("Non-Employed");
};
if ((emp == false) & (nonemp == false))
{
alert("nothing checked")
};
}
Is there a better way of doing this
$("#<%=Text_Name.ClientID%>").mouseleave(function () {
var t_name = this.value;
if (t_name == "") {
$(this).val("Name");
$("#<%=Text_Name.ClientID%>").addClass("grey_add");
$("#<%=Text_Name.ClientID%>").removeClass("black_add");
}
});
What this code does is when you scroll out of the textbox it leaves the it returns to you "Name".
A con about using this technique is when user move mouse out the textbox it fills something in when user types.
It's really simple with jQuery, check this:
html
<input type="text" id="myInput" value="Name" />
jQuery
$(function() {
$('#myInput').focusin(function() {
$(this).val('');
});
$('#myInput').focusout(function() {
$(this).val('Name');
$(this).css('background-color', '#ccc');
});
});
Here goes jsFiddle.
No need for plugins or much code for this.
<input name="search" placeholder="<%=Text_Name.ClientID%>"/>
no javascript needed.
$("#<%=Text_Name.ClientID%>").blur(function () {
var t_name = this.value;
if (t_name == "") {
$(this).val("Name");
$("#<%=Text_Name.ClientID%>").addClass("grey_add");
$("#<%=Text_Name.ClientID%>").removeClass("black_add");
}
});
This event happens when you focus on something else, which is what the textbox at the top right of stack overflow probably uses.
You could look into the watermark plugin I was posting about here:
Custom jQuery plugin return val()
Just edit it to be mouseover / mouseout instead of on focus/blur.
jsFiddle edited to show mouseover/mouseout
I have a radio input group. If a radio is checked and I click again it becomes unchecked.
Is there a way to get the previous status of the radio onClick event?
<input name="options" type="radio" onClick="resetMeIfChecked()">
<input name="options" type="radio" onClick="resetMeIfChecked()">
<input name="options" type="radio" onClick="resetMeIfChecked()">
jQuery edition
// bind to retrieve old status
$('input[type="radio"]').mousedown(function() {
// if it was checked before
if(this.checked) {
// bind event to reset state after click is completed
$(this).mouseup(function() {
// bind param, because "this" will point somewhere else in setTimeout
var radio = this;
// apparently if you do it immediatelly, it will be overriden, hence wait a tiny bit
setTimeout(function() {
radio.checked = false;
}, 5);
// don't handle mouseup anymore unless bound again
$(this).unbind('mouseup');
});
}
});
But again, this is not how radio buttons are intended to be used. I think you'd be better of with a set checkbox'es where you could uncheck all other checkboxes than the current clicked (hence always max 1 selected)
A working example
I use this. You simply store the pre-click value and ! it into the value.
<input type=radio name="myoptions" value="1"
onmousedown="this.tag = this.checked;" onclick="this.checked = !this.tag;">
This behavior is not the expected one for radio buttons and I don't recommend it at all. Try to find another way of achieving this. Use another widget or another option to reset the field value:
http://jsfiddle.net/marcosfromero/rRTE8/
try this:
function resetMeIfChecked(radio){
if(radio.checked && radio.value == window.lastrv){
$(radio).removeAttr('checked');
window.lastrv = 0;
}
else
window.lastrv = radio.value;
}
<input value="1" name="options" checked="checked" type="radio" onClick="resetMeIfChecked(this)" />A
<input value="2" name="options" type="radio" onClick="resetMeIfChecked(this)" />B
<input value="3" name="options" type="radio" onClick="resetMeIfChecked(this)" />C
Its quite simple. Just follow the simple example and
var rdblength=document.formname.elementname.length;
alert('length='+rdblength);
for(i=0;i<rdblength;i++){
document.formname.elementname[i].checked=false;
}
Just find the length and make every index checked=true/false.
Ping me at:-
http://manojbardhan2009.blogspot.com
I had the same problem and figured it out. None of the answers above work exactly as I wanted - most of them require an additional button to reset the radio. The goal was to uncheck radio by clicking on the radio itself.
Here's the fiddle: http://jsfiddle.net/MEk5Q/1/
The problem was very complicated because the radio button value changes BEFORE the click event fires so when we're listening to the event we can't tell if the radio button was already checked or not. In both cases it is already checked.
Another approach was to listen to mousedown event. Unlike click, it fires before changing radio checked attribute but unchecking it inside event handler gives us nothing since it is checked back again during mouseup event.
My answer is a little ugly workaround so I generally don't suggest it to others and I'll probably abandon it myself. It works but it involves 20ms timeout function which I'm not fond of in cases like this.
Here is the code explanation:
$('input[type="radio"]').on('mousedown', function() {
if (this.checked) { //on mousedown we can easily determine if the radio is already checked
this.dataset.check = '1'; //if so, we set a custom attribute (in DOM it would be data-check="1")
}
}).on('mouseup', function() {
if (this.dataset.check) { //then on mouseup we determine if the radio was just meant to be unchecked
var radio = this;
setTimeout(function() {radio.checked = false;}, 20); //we give it a 20ms delay because radio checking fires right after mouseup event
delete this.dataset.check; //get rid of our custom attribute
}
});
As a timeout function I could use a string (less writing) but as far as I know it would be eval'ed. Though I don't trust eval function, I prefered anonymous function.
One more thing - one could ask why spreading the code into two separate event handlers while we can fire the timeout function on mousedown? Well, what if someone press the mouse on a radio and holds it for a few secs or even someone is simply a very slow person ;). Generally, with this solution we omit the problem of lag between mousedown and mouseup.
If you need some more info about dataset, here's the MDN reference:
https://developer.mozilla.org/en-US/docs/Web/API/HTMLElement.dataset
This property came with HTML5 and might be not cross-browser, I guess, so if you want 100% compatibility, replace it with any other solution that'll contain the data, you name it.
Sorry about jQuery here and there but I hope you're fine with it - it was much easier that way.
Hope you'll enjoy it.
$('input[type="radio"]').on("mousedown", function () {
if (this.checked) {
$(this).one("click", function () {
this.checked = false;
});
}
});
I was never too happy about being forced to aim at that tiny radio button, so I came up with a larger target AND a way to turn a radio group off without resorting to anything that would upset the HTML / JavaScript purists.
The technique relies on not molesting the radio buttons at all via event handlers, but checking for a readonly proxy for each one instead. Everything is contained in what's below in pure JavaScript using a radio group to select a type of cheese, or no cheese at all.
I purposely used no styling in this example to avoid that added layer. The dump button will tell you what the three checked states are, so use it to interrogate what happened after hitting the radio or text input elements. For example simplicity I used a global to remember the former state, but a more elegant method is to use a dataset, which I what I use in the real code of my application.
<!DOCTYPE html>
<html>
<head>
<title>Uncheck a radio button</title>
<script>
function attachEventListener(target, eventType, functionRef, capture) {
"use strict";
if (typeof target.addEventListener !== 'undefined') {
// Most modern browsers
target.addEventListener(eventType, functionRef, capture);
} else if (typeof target.attachEvent !== 'undefined') {
// IE
target.attachEvent('on' + eventType, functionRef);
} else {
eventType = 'on' + eventType;
if (typeof target[eventType] === 'function') {
var oldListener = target[eventType];
target[eventType] = function() {
oldListener();
return functionRef();
};
} else {
target[eventType] = functionRef;
}
}
}
</script>
</head>
<body>
<form>
<input id="Cheddar-radio" class="radio" type="radio" name="Cheeses-0" value="Cheddar Cheese" tabindex="-1"></input>
<input id="Cheddar-text" type="text" readonly value="Cheddar Cheese" tabindex="-1"></input><br>
<input id="Swiss-radio" class="radio" type="radio" name="Cheeses-0" value="Swiss Cheese" tabindex="-1"></input>
<input id="Swiss-text" type="text" readonly value="Swiss Cheese" tabindex="-1"></input><br>
<input id="American-radio" class="radio" type="radio" name="Cheeses-0" value="American Cheese" tabindex="-1"></input>
<input id="American-text" type="text" readonly value="American Cheese" tabindex="-1"></input><br><br>
<input onclick="dumpStates()" type="button" name="button" value="dump" tabindex="-1"></input>
</form>
<script>
window.onload = addRadioListeners;
function addRadioListeners() { // But do it on the -text elements.
attachEventListener(document.getElementById('Cheddar-text') , 'mousedown', rememberCurrentState, false);
attachEventListener(document.getElementById('Swiss-text') , 'mousedown', rememberCurrentState, false);
attachEventListener(document.getElementById('American-text'), 'mousedown', rememberCurrentState, false);
attachEventListener(document.getElementById('Cheddar-text') , 'mouseup', checkNewState, false);
attachEventListener(document.getElementById('Swiss-text') , 'mouseup', checkNewState, false);
attachEventListener(document.getElementById('American-text'), 'mouseup', checkNewState, false);
}
function dumpStates() {
console.log(document.getElementById('Cheddar-radio').checked +
' ' + document.getElementById('Swiss-radio').checked +
' ' + document.getElementById('American-radio').checked);
}
var elementWasChecked; // Global - Could just as well use a dataset attribute
// on either the -radio or -text element and check it instead.
function rememberCurrentState(event) {
var element;
var radioElement;
element = event.target;
radioElement = document.getElementById(element.id.replace(/text/,'radio'));
elementWasChecked = radioElement.checked;
radioElement.checked = true;
}
function checkNewState(event) {
var element;
var radioElement;
element = event.target;
radioElement = document.getElementById(element.id.replace(/text/,'radio'));
var currentState = radioElement.checked;
if (elementWasChecked === true && currentState === true) {
console.log('Changing ' + radioElement.id + ' to false.');
radioElement.checked = false;
}
};
</script>
</body>
</html>
If you click on the radio buttons they work as expected. If you click on the text items next to each, they are a proxy for the radio buttons with one exception. If you click on a text item that has an associated radio button that's already checked, it will uncheck it. Therefore, the text proxy's are event triggered, and not the radio buttons.
The added benefit is that you can now hit the larger text target too.
If you want to make it simple and wouldn't mind using a double-click event try something like this:
<input name="options" type="radio" ondblclick="this.checked=false;">
#jerjer's answer is almost perfect, but radios can be switched also by arrows if the radio group has the focus (so mousedown event is not enough). Alas, the radio group also gets checked when activated by focus shift (Tab), which can undesirably check one option. Therefore space should uncheck the focused radio, just like the checkbox behavior.
This code fixes that for all radios (Most credit still goes to jerjer):
window.addEventListener("DOMContentLoaded", function() {
var radios = document.querySelectorAll("input[type=radio]");
for(var i=0; i<radios.length; ++i) {
radios[i].addEventListener("click", function(e) {
if(e.target.checked && e.target.value == window.lastrv){
e.target.checked = false;
window.lastrv = 0;
}
else
window.lastrv = e.target.value;
});
radios[i].addEventListener("keypress", function(e) {
if(e.keyCode==32) e.target.click();
});
}
});