Eventlistner on Checkbox should give user a prompt - javascript

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)

Related

.is(":checked") doesn't work in jQuery

I'm new to jQuery and I need to check if the checkbox is checked. In other posts I saw that I need to use .is(":checked") to solve it, but somehow it doesn't work.
$('.neutral').on('click', function() {
var checkbox = $(this);
if (checkbox.is(":checked")) {
console.log('checked');
} else {
console.log('unchecked');
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="checkbox" class="neutral" />
In this code I have 2 problems and I don't know how to solve it.
When I'm using console.log('checked') outside of the if statement (after checkbox variable) and I click on the checkbox one time, console prints the result 2 times.
I don't know why this if statement doesn't working.
Thank you for your time and help.
checked happens after the change event,just replace click with change.
$('.neutral').on('change', function() {
var checkbox = $(this);
if (checkbox.is(":checked")) {
console.log('checked');
} else {
console.log('unchecked');
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="checkbox" class="neutral" />
I have seen your code, I think you should try
$(document).on("click",".neutral",function() {
// Write code here
});
Instead of your code, Replace this code to as i written
$('.neutral').on('click', function() {
// Code here
});
For more undesirability see here
$(document).ready(function() {
// This WILL work because we are listening on the 'document',
// for a click on an element with an ID of #test-element
$(document).on("click","#test-element",function() {
alert("click bound to document listening for #test-element");
});
// This will NOT work because there is no '#test-element' ... yet
$("#test-element").on("click",function() {
alert("click bound directly to #test-element");
});
// Create the dynamic element '#test-element'
$('body').append('<div id="test-element">Click mee</div>');
});
Visit these link that may help you more for your implementation
Statck over flow link
jsFiddle Link

Working With checkboxes in the web pages

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

Radio Button Check

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")
};
}

Get state of checkbox using javascript

I'm trying to write a javascript with jquery which should be able to pick out and use information on if a checkbox is checked or not. This should happen every time the checkbox(has id 'edit-toggle-me') is clicked. I've written a test function for this with some alert() in it to see if I've succeeded or not.
(function ($) {
"use strict";
$(document).ready(function () {
$('#edit-toggle-me').click(function(){
if ($('#edit-toggle-me').checked()) {
alert('Yup!');
}
else {
alert('Nup!');
}
});
});
})(jQuery);
It perform neither of the alerts so I'm guessing it crashes at $('#edit-toggle-me').checked(). I don't know why though.
I've also tried this:
(function ($) {
$(document).ready(function () {
$('#edit-toggle-me').click(function(){
var elementy = document.getElementById('edit-toggle-me');
var check = elementy.value;
alert(check);
if(elementy.checked()) {
alert('yup');
}
});
});
})(jQuery);
The first alert works, but neither or the last two 'yup' or 'nup'.
And then I also tried this:
(function ($) {
$(document).ready(function () {
$('#edit-toggle-me').click(function(){
var element2 = document.getElementById('edit-toggle-me');
var check = element2.value;
alert(check);
});
});
})(jQuery);
This always return 1. Which I don't understand why either.
Grateful for any hints.
Use .is(':checked'). You can find the documentation HERE.
JSFIDDLE
There is no such method as .checked() in jQuery or in the DOM API. There is simply a .checked property on the element that is true if the element is checked, false otherwise. Try this:
(function ($) {
"use strict";
$(document).ready(function () {
$('#edit-toggle-me').click(function(){
alert( this.checked ? ":)" : ":(" );
});
});
})(jQuery);
See demo: http://jsfiddle.net/scZ3X/
$(function(){
$('#edit-toggle-me').on('change', function(){
if($(this).is(':checked')) {
alert('checked');
}
else {
alert('unchecked');
}
});
});
You should have to use �change� event instead click. Because In some cases click event is not good to use in check box and radio buttons.
Example 1:
If you have a radio button have click event bind. In case your radio button is already true and you clicking in radio button. It�s not change radio button value, But your click event fire every time.
But in case if you use change event. Your event will fire only if your radio button value got change(If it�s already not checked or true)
Example 2:
If you have any label for any radio button or check box. In case you have click event bind in checkbox or radio button. On click of your label your check box or radio button value got change but your click event will not call.
In case of change event. It�ll work as expected on click of label related label too.
Try this:
$('#edit-toggle-me').is(':checked')

Detect which form input has focus using JavaScript or jQuery

How do you detect which form input has focus using JavaScript or jQuery?
From within a function I want to be able to determine which form input has focus. I'd like to be able to do this in straight JavaScript and/or jQuery.
document.activeElement, it's been supported in IE for a long time and the latest versions of FF and chrome support it also. If nothing has focus, it returns the document.body object.
I am not sure if this is the most efficient way, but you could try:
var selectedInput = null;
$(function() {
$('input, textarea, select').focus(function() {
selectedInput = this;
}).blur(function(){
selectedInput = null;
});
});
If all you want to do is change the CSS for a particular form field when it gets focus, you could use the CSS ":focus" selector. For compatibility with IE6 which doesn't support this, you could use the IE7 library.
Otherwise, you could use the onfocus and onblur events.
something like:
<input type="text" onfocus="txtfocus=1" onblur="txtfocus=0" />
and then have something like this in your javascript
if (txtfocus==1)
{
//Whatever code you want to run
}
if (txtfocus==0)
{
//Something else here
}
But that would just be my way of doing it, and it might not be extremely practical if you have, say 10 inputs :)
I would do it this way: I used a function that would return a 1 if the ID of the element it was sent was one that would trigger my event, and all others would return a 0, and the "if" statement would then just fall-through and not do anything:
function getSender(field) {
switch (field.id) {
case "someID":
case "someOtherID":
return 1;
break;
default:
return 0;
}
}
function doSomething(elem) {
if (getSender(elem) == 1) {
// do your stuff
}
/* else {
// do something else
} */
}
HTML Markup:
<input id="someID" onfocus="doSomething(this)" />
<input id="someOtherID" onfocus="doSomething(this)" />
<input id="someOtherGodForsakenID" onfocus="doSomething(this)" />
The first two will do the event in doSomething, the last one won't (or will do the else clause if uncommented).
-Tom
Here's a solution for text/password/textarea (not sure if I forgot others that can get focus, but they could be easily added by modifying the if clauses... an improvement could be made on the design by putting the if's body in it's own function to determine suitable inputs that can get focus).
Assuming that you can rely on the user sporting a browser that is not pre-historic (http://www.caniuse.com/#feat=dataset):
<script>
//The selector to get the text/password/textarea input that has focus is: jQuery('[data-selected=true]')
jQuery(document).ready(function() {
jQuery('body').bind({'focusin': function(Event){
var Target = jQuery(Event.target);
if(Target.is(':text')||Target.is(':password')||Target.is('textarea'))
{
Target.attr('data-selected', 'true');
}
}, 'focusout': function(Event){
var Target = jQuery(Event.target);
if(Target.is(':text')||Target.is(':password')||Target.is('textarea'))
{
Target.attr('data-selected', 'false');
}
}});
});
</script>
For pre-historic browsers, you can use the uglier:
<script>
//The selector to get the text/password/textarea input that has focus is: jQuery('[name='+jQuery('body').data('Selected_input')+']')
jQuery(document).ready(function() {
jQuery('body').bind({'focusin': function(Event){
var Target = jQuery(Event.target);
if(Target.is(':text')||Target.is(':password')||target.is('textarea'))
{
jQuery('body').data('Selected_input', Target.attr('name'));
}
}, 'focusout': function(Event){
var Target = jQuery(Event.target);
if(Target.is(':text')||Target.is(':password')||target.is('textarea'))
{
jQuery('body').data('Selected_input', null);
}
}});
});
</script>
You only need one listener if you use event bubbling (and bind it to the document); one per form is reasonable, though:
var selectedInput = null;
$(function() {
$('form').on('focus', 'input, textarea, select', function() {
selectedInput = this;
}).on('blur', 'input, textarea, select', function() {
selectedInput = null;
});
});
(Maybe you should move the selectedInput variable to the form.)
You can use this
<input type="text" onfocus="myFunction()">
It triggers the function when the input is focused.
Try
window.getSelection().getRangeAt(0).startContainer

Categories