How can I tie input checkbox to Javascript function? - javascript

I can't bind my checkbox result to Javascript code. How can I do this correctly? The script doesn't react to this.
application.js
$(document).on('ready page:load', function () {
function setCheckbox() {
$('.check').on('click', function complete(){
alert("alert");
}) }
})
view file
<input type="checkbox" value="<% article.complete %>" class='check' data-remote="true" >

I would do a change event instead of a click
$('.check').on('change', function(){
if ($(this).is(':checked')) {
//do stuff here
}
});

Related

Highlight input text not working

Hello I would like the text inside an input element to highlight upon initial click. However my function does not seem to be working. I have researched the issue and seen that there are some issues with jquery 1.7 and below. I have adjusted it to account for this any it still does not work.
Any help would be great. Thanks!
HTML
<input type="text" value="hello"/>
JS
$scope.highlightText = function() {
$("input[type='text']").on("click", function() {
$(this).select();
});
https://plnkr.co/edit/b7TYAFQNkhjE6lpRSWTR?p=preview
You need to actually call your method at the end of controller, otherwise the event is not bound.
https://plnkr.co/edit/a0BlekB8qTGOmWS8asIx?p=preview
... other code ...
$scope.highlightText = function () {
$("input[type='text']").on("click", function () {
$(this).select();
var test = $(this).parent();
console.log(test);
});
$("textarea").on("click", function () {
$(this).select();
});
};
$scope.highlightText();
};
To select the text inside an input you would simply call this.select() from onclick like shown below
<input type="text" onclick="this.select()" value="hello"/>

How to get bool value from checkbox in javascript / jquery?

I'm trying to see if a checkbox is checked or not with a simple function. It doesn't seem to be working, here's the code:
HTML:
<form>
<input type="checkbox" id="check" />
</form>
JS:
$(document).ready(function() {
if ($('#check').is(":checked")) {
alert('it works')
}
});
JSFiddle: https://jsfiddle.net/5h58mx1h/
Your code only runs once - when document is ready. You need to attach an event listener to the checkbox and check when it changes:
$(document).ready(function() {
$('#check').change(function() {
if ($(this).is(":checked")) {
alert('it works');
}
});
});
Fiddle
You don't need jQuery. An <input type="checkbox"> has a checked attribute, which you can use like this:
document.addEventListener("DOMContentLoaded", () => {
if (document.getElementById("check").checked) {
alert('it works')
}
})
It should be work:
$(document).ready(function () {
var ckbox = $('#checkbox');
$('input').on('click',function () {
if (ckbox.is(':checked')) {
alert('You have Checked it');
} else {
alert('You Un-Checked it');
}
});
});
jsFiddle
I think this is the most simple way:
if ($('#check').checked) {
alert('it works');
}
Replace your HTML to this
<form>
<input type="checkbox" id="check" checked />
</form>
This will work for you. Because you don't checked checkbox yet that's why not alert.

jquery uncheck and check and vise versa checkbox of child element

Here is my html
#This will be generated throught loop
<li class="selector">
<a>
<input type="checkbox" value="test" /> test
</a>
</li>
Here is my jquery click event
$('.selector').on('click', function() {
if($(this).find('input').is(':checked')){
#uncheck the checkbox
}else{
#check the checkbox
}
});
How do I uncheck if checked and check if unchecked
Try
$(document).on('click', '.selector', function (e) {
if (!$(e.target).is('input')) {
$(this).find('input').prop('checked', function () {
return !this.checked;
});
}
});
Demo: Fiddle
Another way
$(document).on('click', '.selector', function (e) {
$(this).find('input').prop('checked', function () {
return !this.checked;
});
});
$(document).on('click', '.selector input', function (e) {
e.stopPropagation();
});
Demo: Fiddle
Try this
$('.selector').on('click', function() {
var checkbox = $(this).find(':checkbox');
if($(checkbox).is(':checked')){
$(checkbox).prop('checked', false);
}else{
#check the checkbox
$(checkbox).prop('checked', true);
}
});
I don't understand why you are trying to do this with JavaScript. If the user clicks directly on the checkbox it will automatically check/uncheck itself, but if you add code to check/uncheck it in JS that would cancel out the default behaviour so in your click handler you'd need to test that the click was elsewhere within the .selector.
Anwyay, the .prop() method has you covered:
$('.selector').on('click', function(e) {
if (e.target.type === "checkbox") return; // do nothing if checkbox clicked directly
$(this).find("input[type=checkbox]").prop("checked", function(i,v) {
return !v; // set to opposite of current value
});
});
Demo: http://jsfiddle.net/N4crP/1/
However, if your goal is just to allow clicking on the text "test" to click the box you don't need JavaScript because that's what a <label> element does:
<li class="selector">
<label>
<input type="checkbox" value="test" /> test
</label>
</li>
As you can see in this demo: http://jsfiddle.net/N4crP/2/ - clicking on the text "test" or the checkbox will toggle the current value without any JavaScript.

change div text on radion button click

I want to put the radio button value in the status div. The text of status div should change, according to the radio button selected by the user.
The code that I used bellow is not working. Please help. Thanks!
HTML code:
<form action="">
<input type="radio" name="sex" value="male">Male<br>
<input type="radio" name="sex" value="female">Female<br>
<div id="status"></div>
</form>​
JS code:
$(document).ready(function () {
RadioStatus="";
$("input[type='radio']:checked").each( function()
{
if ($(this).attr('checked');)
RadioStatus=$(this).val();
$("#status").text(RadioStatus);
});
$("input[type='radio']").change(function()
{
RadioStatus= $('input[type='radio']:checked').val()
$('#status').text(RadioStatus);
});
});
This should work:
$("input[type='radio']").click(function() {
$('#status').text($(this).val());
});
A few minor adjustments to your code got it to work just fine:
$(document).ready(function () {
RadioStatus="";
$("input[type='radio']:checked").each( function()
{
if ($(this).attr('checked'))
RadioStatus=$(this).val();
$("#status").text(RadioStatus);
});
$("input[type='radio']").change(function()
{
RadioStatus= $('input[type="radio"]:checked').val();
$('#status').text(RadioStatus);
});
});​
see: http://jsfiddle.net/f6Tru/
..or you can really simplify it by using techfoobar's:
$(document).ready(function () {
$("input[type='radio']").click(function() {
$('#status').text($(this).val());
});
});​
instead. see: http://jsfiddle.net/RrhYM/
You have a problem in your single quotes '
Change:
RadioStatus= $('input[type='radio']:checked').val()
To:
RadioStatus= $('input[type="radio"]:checked').val()
Try this code
$('input[name ^=sex]').click(function() {
$('#status').text($(this).val());
});
demo
$("input:radio").click(function() { //use $("input:radio[name='sex']").click if more radio buttons there
$('#status').text($(this).val());
});​
Simply use change to determine that a radio button is selected. Then use html or text to append the value of chosen radio button to your <div id="status">.
$(document).ready(function () {
$('input[type=radio]').on("change", function() {
$('#status').html($(this).val());
// Alternative
// $('#status').text($(this).val());
});
});​
DEMO
You may achieve that with the following JS code :
$("input").click(function(e){
var selectedValue = e.currentTarget.value;
$('#status').html(selectedValue );
});
​
​

jquery select all checkboxes

I have a series of checkboxes that are loaded 100 at a time via ajax.
I need this jquery to allow me to have a button when pushed check all on screen. If more are loaded, and the button is pressed, to perhaps toggle all off, then pressed again toggle all back on.
This is what i have, obviously its not working for me.
$(function () {
$('#selectall').click(function () {
$('#friendslist').find(':checkbox').attr('checked', this.checked);
});
});
The button is #selectall, the check boxes are class .tf, and they all reside in a parent div called #check, inside a div called #friend, inside a div called #friendslist
Example:
<div id='friendslist'>
<div id='friend'>
<div id='check'>
<input type='checkbox' class='tf' name='hurr' value='durr1'>
</div>
</div>
<div id='friend'>
<div id='check'>
<input type='checkbox' class='tf' name='hurr' value='durr2'>
</div>
</div>
<div id='friend'>
<div id='check'>
<input type='checkbox' class='tf' name='hurr' value='durr3'>
</div>
</div>
</div>
<input type='button' id='selectall' value="Select All">
I know I'm revisiting an old thread, but this page shows up as one of the top results in Google when this question is asked. I am revisiting this because in jQuery 1.6 and above, prop() should be used for "checked" status instead of attr() with true or false being passed. More info here.
For example, Henrick's code should now be:
$(function () {
$('#selectall').toggle(
function() {
$('#friendslist .tf').prop('checked', true);
},
function() {
$('#friendslist .tf').prop('checked', false);
}
);
});
$('#friendslist .tf')
this selector will suit your needs
Use the jquery toggle function. Then you can also perform whatever other changes you may want to do along with those changes... such as changing the value of the button to say "check all" or "uncheck all".
$(function () {
$('#selectall').toggle(
function() {
$('#friendslist .tf').attr('checked', 'checked');
},
function() {
$('#friendslist .tf').attr('checked', '');
}
);
});
A very simple check/uncheck all without the need of loop
<input type="checkbox" id="checkAll" /> Check / Uncheck All
<input type="checkbox" class="chk" value="option1" /> Option 1
<input type="checkbox" class="chk" value="option2" /> Option 2
<input type="checkbox" class="chk" value="option3" /> Option 3
And the javascript (jQuery) accounting for "undefined" on checkbox value
** UPDATE - using .prop() **
$("#checkAll").change(function(){
var status = $(this).is(":checked") ? true : false;
$(".chk").prop("checked",status);
});
** Previous Suggestion - may not work **
$("#checkAll").change(function(){
var status = $(this).attr("checked") ? "checked" : false;
$(".chk").attr("checked",status);
});
OR with the suggestion from the next post using .prop() combined into a single line
$("#checkAll").change(function(){
$(".chk").attr("checked",$(this).prop("checked"));
});
This is how I toggle checkboxes
$(document).ready(function() {
$('#Togglebutton').click(function() {
$('.checkBoxes').each(function() {
$(this).attr('checked',!$(this).attr('checked'));
});
});
});
maybe try this:
$(function () {
$('#selectall').click(function () {
$('#friendslist .tf').attr('checked', this.checked);
});
});
<div class="control-group">
<input type="checkbox" class="selAllChksInGroup"> All
<input type="checkbox" value="NE"> Nebraska
<input type="checkbox" value="FL"> Florida
</div>
$(document).ready(function(){
$("input[type=checkbox].selAllChksInGroup").on("click.chkAll", function( event ){
$(this).parents('.control-group:eq(0)').find(':checkbox').prop('checked', this.checked);
});
});
I could not get this last example to work for me. The correct way to query the state of the checkbox is apparently :
var status = $(this).prop("checked");
and not
var status = $(this).attr("checked") ? "checked" : false;
as above.
See jQuery receiving checkbox status
It works for me (IE, Safari, Firefox) by just changing your this.checked to 'checked'.
$(function() {
$('#selectall').click(function() {
$('#friendslist').find(':checkbox').attr('checked', 'checked');
});
});
You may try this:
$(function () {
$('#selectall').click(function () {
$('#friendslist input:checkbox').attr('checked', checked_status);
});
});
//checked_status=true/false -as the case may be, or set it via a variable
assuming #selectall is a checkbox itself whose state you want copied to all the other checkboxes?
$(function () {
$('#selectall').click(function () {
$('#friendslist input:checkbox').attr('checked', $(this).attr('checked'));
});
});
try this
var checkAll = function(){
var check_all = arguments[0];
var child_class = arguments[1];
if(arguments.length>2){
var uncheck_all = arguments[2];
$('#'+check_all).click(function (){
$('.'+child_class).attr('checked', true);
});
$('#'+uncheck_all).click(function (){
$('.'+child_class).attr('checked', false);
});
$('.'+child_class).click(function (){
var checkall_checked = true;
$('.'+child_class).each(function(){
if($(this).attr('checked')!=true){
checkall_checked = false;
}
});
if(checkall_checked == true){
$('#'+check_all).attr('checked', true);
$('#'+uncheck_all).attr('checked', false);
}else{
$('#'+check_all).attr('checked', false);
$('#'+uncheck_all).attr('checked', true);
}
});
}else{
$('#'+check_all).click(function (){
$('.'+child_class).attr('checked', $(this).attr('checked'));
});
$('.'+child_class).click(function (){
var checkall_checked = true;
$('.'+child_class).each(function(){
if($(this).attr('checked')!=true){
checkall_checked = false;
}
});
$('#'+check_all).attr('checked', checkall_checked);
});
}
};
To "check all" and "uncheck all" is same checkbox
checkAll("checkall_id", "child_checkboxes_class_name");
To "check all" and "uncheck all" is separate checkbox
checkAll("checkall_id", "child_checkboxes_class_name", "uncheckall_id");
Here is how I achieved it.
function SelectAllCheckBoxes();
{
$('#divSrchResults').find(':checkbox').attr('checked', $('#chkPrint').is(":checked"));
}
The following fires the above line.
<input type=checkbox id=chkPrint onclick='SelectAllCheckBoxes();' />
On the click of chkPrint , every checkbox in the grid divSrchResults' is either checked or unchecked depending on the status of chkPrint.
Of course, if you need advanced functions like unchecking the titled checkbox when every other checkbox has been unchecked, you need to write another function for this.
I created a function that I use on all projects. This is just the initial draft, but maybe it will help:
Function:
function selectAll(wrapperAll, wrapperInputs) {
var selectAll = wrapperAll.find('input');
var allInputs = wrapperInputs.find('input');
console.log('Checked inputs = ' + allInputs.filter(':not(:checked)').length);
function checkitems(allInputs) {
//If all items checked
if (allInputs.filter(':not(:checked)').length === 0) {
console.log('Function: checkItems: All items checked');
selectAll.attr('checked', true);
} else {
console.log('Function: checkItems: Else all items checked');
selectAll.attr('checked', false);
}
}
checkitems(allInputs);
allInputs.on('change', function () {
checkitems(allInputs)
});
selectAll.on('change', function () {
if (this.checked) {
console.log('This checkbox is checked');
wrapperInputs.find(':checkbox').attr('checked', true);
} else {
console.log('This checkbox is NOT checked');
wrapperInputs.find(':checkbox').attr('checked', false);
}
});
}
It accepts the 2 parameters where the inputs are wrapped into and you cand use-it like this:
$(function () {
var wrapperAll = $('.selectallinput');
var wrapperInputs = $('.inputs');
selectAll(wrapperAll, wrapperInputs);
});
See demo: http://jsfiddle.net/cHD9z/
So "checked" is a crappy attribute; in many browsers it doesn't work as expected :-( Try doing:
$('#friendslist').find(':checkbox')
.attr('checked', this.checked)
.attr('defaultChecked', this.checked);
I know setting "defaultChecked" doesn't make any sense, but try it and see if it helps.
<input type="checkbox" onclick="toggleChecked(this.checked)"> Select / Deselect All
Now here are two versions of the toggleChecked function dependent on the semantics of your document. The only real difference is the jQuery selector for your list checkboxes:
1: All checkboxes have a class of “checkbox” (<input type=”checkbox” class=”checkbox” />)
function toggleChecked(status) {
$(".checkbox").each( function() {
$(this).attr("checked",status);
})
}
2: All the checkboxes are contained within a div with an arbitary id:
<div id="checkboxes">
<input type="checkbox" />
<input type="checkbox" />
<input type="checkbox" />
</div>
In this case the function would look like this:
function toggleChecked(status) {
$("#checkboxes input").each( function() {
$(this).attr("checked",status);
})
Have fun!
This may work for both (checked/unchecked) selectall situations:
$(document).ready(function(){
$('#selectall').click(function () {
$("#friendslist .tf").attr("checked",function(){return $(this).attr("checked") ? false : true;});
});
});
The currently accepted answer won't work for jQuery 1.9+. The event handling aspect of the (rather heavily) overloaded .toggle() function was removed in that version, which means that attempting to call .toggle(function, function) will instead just toggle the display state of your element.
I'd suggest doing something like this instead:
$(function() {
var selectAll = $('#selectall');
selectAll.on('click', function(e) {
var checked = !(selectAll.data('checked') || false);
$('#friendslist .tf').prop('checked', checked);
selectAll.data('checked', checked);
});
});
That uses a regular click event handler, plus a data attribute to track the "toggled" status and invert it with each click.
Here's a basic jQuery plugin I wrote that selects all checkboxes on the page, except the checkbox/element that is to be used as the toggle. This, of course, could be amended to suit your needs:
(function($) {
// Checkbox toggle function for selecting all checkboxes on the page
$.fn.toggleCheckboxes = function() {
// Get all checkbox elements
checkboxes = $(':checkbox').not(this);
// Check if the checkboxes are checked/unchecked and if so uncheck/check them
if(this.is(':checked')) {
checkboxes.prop('checked', true);
} else {
checkboxes.prop('checked', false);
}
}
}(jQuery));
Then simply call the function on your checkbox or button element:
// Check all checkboxes
$('.check-all').change(function() {
$(this).toggleCheckboxes();
});
As you are adding and removing more checkboxes via AJAX, you may want to use this instead of .change():
// Check all checkboxes
$(document).on('change', '.check-all', function() {
$(this).toggleCheckboxes();
});

Categories

Resources