Express handlebars, can't bind checked attribute to checkbox - javascript

I am opening some divs when a user clicks on a certain checkbox like so:
$(document).ready(function () {
$('input[type="checkbox"]').click(function () {
var inputValue = $(this).attr("value");
if ($(this).prop("checked") == true) {
$("." + inputValue).show();
}
else if ($(this).prop("checked") == false) {
$("." + inputValue).hide();
}
});
});
Then, I store the classes of the checked boxes and if the user gave me bad input I redirect them to the submission page, I store the checked boxes like so:
allEvents={'coinChecked':true,'crinChecked':true,'ppChecked':false,'quizChecked':false}
Now I pass this allEvents object back to the submission page with res.render(check:allEvents)
Then, I use the following code (on SO) to bind the checked attribute to a checkbox, and hence open the initially hidden div with :
<input type="checkbox" name="events" value="coin" {{bindAttr checked="check.coinChecked"}}> Code-in
But neither does this make the checkbox "checked", nor does it display the hidden div.
How can I do this, or is there a workaround for this process?
thanks

<input type="checkbox" name="events" value="coin" checked={{if(check.coinchecked){{checked}}}}> Code-in
might do the trick

Related

Jquery - Ensure all checkboxes are selected

I am trying to create a JS function that will ensure all checkboxes in my form are selected.
I have tried the following, but it isn't working. There are other checkboxes in another from on this page so I am wondering if this is conflicting? I thought using $(this) would fix that issue...
$('#my-form').on('submit', function(e) {
e.preventDefault();
var checked = false;
$('#input[type="checkbox"]').each(function() {
if ($(this).is(":checked")) {
checked = true;
}
});
if (checked == false) {
console.log('Something wasnt checked');
}
});
Can any advise what I am doing wrong here please?
Your code checks if any of the checkboxes are checked.
Change the code to
var checked = true;
And set the variable to false, if the checkbox in the loop is NOT checked.
"#" is used to query elements by their ID, so $("#input") would target only one input that has id="input". You should instead do this:
$("input[type='checkbox']")
or, if you don't want all checkboxes on the page you will need to use some other selector, etc. add class "some-class" to all inputs that you want to check and use:
$(".some-class")
Also, you will need to revert your logic, cause currently you will set checked to true if any of the checkboxes is checked. So, initially use checked = true, then in if statement set it to false if it's not checked.
Just check :checked checkbox length based upon that set your variable like below.
$('input[type="checkbox"]').click(function() {
var checked = false;
if ($('input[type="checkbox"]:checked').length == $('input[type="checkbox"]').length)
checked = true;
if (checked == true)
console.log('checked');
else
console.log('false');
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input checked="checked" type="checkbox">
<input checked="checked" type="checkbox">

Trigger functions from checkbox on click by clicking on a button

I have a couple of checkboxes and a button. When I click on checkbox - function is triggered. This is the desired behavior but I want to trigger it by clicking on the button. I want to have the possibility to first select checkboxes (I tried with return false and event.preventDefault but these completely switch the selection off) and then by clicking the button - trigger functions from checkboxes. Here is a link to jsfiddle:
http://jsfiddle.net/j93k2xns/6/
So for instance: I can select 3 checkboxes (nothing should happen) and after I click the button - three alerts should appear.
The code:
HTML:
<input type="checkbox" name='check[]' id="first">first</input>
<input type="checkbox" name='check[]'>second</input>
<input type="checkbox" name='check[]'>third</input>
<input type="checkbox" name='check[]'>fourth</input>
<input type="button" value="validate" id="val-button">
JS:
var check_state;
$(document).on('click','input[name="check[]"]', function(e){
if(check_state === true) {
alert('a');
} else {
return false;
}
});
$(document).on('click','#val-button', function(){
check_state = true;
});
There are a few interpretations to his question. If I'm reading it correctly, he wants to bind an arbitrary function to the checkboxes. Clicking the button should fire this event. This is how you can achieve that using custom events in jQuery:
$(function () {
$("input[name='check[]']").bind("myCustomButtonClick", function() {
if(this.checked) {
alert('a');
}
});
})
$(document).on('click','#val-button', function(){
$("input[name='check[]']").trigger("myCustomButtonClick");
});
And the associated jsfiddle: http://jsfiddle.net/3yf7ymos/
$(document).on('click','#val-button', function(){
$( 'input[name="check[]"]' ).each(function( index ) {
if($(this).is(':checked')) {
alert("a");
return true;
}
});
});
If you want to do something when the user checks a checkbox, add an event listener:
$('input[type="checkbox"]').click(function() {
if ($(this).is(':checked')) {
// do something
}
});
If the idea is run a couple of functions after the inputs are checked by clicking on a button:
function myFunction() {
if ($('input[id="something"]:checked').length == 0) {
// do something
} else if ($('input[id="something_2"]:checked').length == 0) {
// do something
}
//and so on..
}
$('#val-button').click(function() {
myFunction();
});
I have a similar inquiry. I have a number of check boxes. Each checkbox is linked to a different URL that opens a PDF form. I want my team to be able to select which forms they need by ticking the checkbox. Once they have done that, I would like a button to trigger the opening of each form based on which check box is checked. I have it so the checkbox upon being checked opens the form right away but it is very distracting. Its preferable they all get opened at once by a "button". Help. I am quite new to JavaScript so may need additional clarity.

How to check 2 checkboxes that have the same name

So I have a ajax search form which gives results with a checkbox:
Here is part of PHP code for each search result:
<input type="checkbox" class="lovkrav_checkbox checkbox_search" name="lovkrav['.$lovkrav_id.']" value="'.$lovkrav_id.'" orig-id="lovkrav'.$lovkrav_id.'" id="lovkravs'.$lovkrav_id.'" '.$checked.'/>
and there is a twin checkbox already on website with the same name but with different id.
By using "orig-id" property I am getting the id of the twin checkbox. Both checkboxes have same class lovkrav_checkbox.
I came to the point where the click event is detected by the twin checkbox as it should but not the checkbox you clicked on!
Here is the code:
$(document).on("click",".lovkrav_checkbox",function(e){
toggle_id = document.getElementById($(this).attr("orig-id"));
$(toggle_id).trigger("click");
});
What I want to achieve is when a user clicks on one checkbox - the twin checkbox (the one with same name property) will be checked/unchecked as well.
What am I doing wrong?
Would be easier to toggle the checked state with vanilla javascript.
HTML
<input type="checkbox" name="test">
<input type="checkbox" name="test">
JS
//All of the checkboxes
var $checkboxes = $("input[type=checkbox][name=test]");
//The event handler
$checkboxes.on("click", function() {
//Get the state of the check box you clicked
var checkedState = this.checked
//Make it the state of all the checkboxes
$checkboxes.each(function() {
this.checked = checkedState;
});
});
Here is the fiddle
You can try this:
DEMO
$(document).on("click",".check",function(e){
$("."+this.className).prop("checked", this.checked);
});
Try this too:
js:
$(document).on("click",".lovkrav_checkbox",function(e){
toggle_id = $(this).attr("name");
isChecked = $(this).prop("checked");
$("input:checkbox").each(
function(){
if($(this).attr("name") == toggle_id && isChecked){
$(this).prop("checked",true);
}
else{
$(this).prop("checked",false);
}
});
});
fiddle
Try this
$("input[type=checkbox][name=test]").prop("checked",true);

I need an event trigger for a radio button for when it is unchecked because another button is checked

I need an event trigger for a radio button for when it is unchecked because another button is checked.
The code below should demonstrate my dilemma.
If you will notice, there is an onchange event trigger atttached to each radio button and checkbox in the html code. In theory a change in state from checked to unchecked should fire the onchange event.
This happens as expected with the check boxes. If you check one, you get the alert, 'Your item is changed to checked'. If you uncheck it, you get the alert, 'Your item is changed to unchecked'.
With the radio buttons, when you check button one, you get, as expected, the alert, 'Your item is changed to checked' since the button changed from unchecked to checked. However, when you check the second button and the first radio button is changed from checked to unchecked the "onchange" event trigger does not fire and the 'else' alert is not triggered.
So this issue for me is what event is triggered when a radio button gets unchecked by another button being checked?
I appreciate everyone's assistance on this.
--Kenoli
<html>
<head>
<title></title>
<script type="text/javascript">
function clickAction() {
//alert ('Your item changed');
if (this.checked == true) {alert ('Your item is changed to checked');}
else if (this.checked == false) {alert('Your item is changed to unchecked');}
}
</script>
<script type="text/javascript">
function initializeToggles() {
var button1= document.getElementById('button1');
button1.onchange = clickAction;
var box1= document.getElementById('box1');
box1.onchange = clickAction;
var box2= document.getElementById('box2');
box2.onchange = clickAction;
}
</script>
<script type="text/javascript">window.onload = initializeToggles;</script>
</head>
<body>
<input type="radio" name="testRadio" id="button1" >Button one<br/>
<input type="radio" name="testRadio" id="button2" >Button two<br/><br/>
<input type="checkbox" name="testCheckbox" id="box1" >Box one<br/>
<input type="checkbox" name="testCheckbox" id="box2" >Box two<br/><br/>
</body>
</html>
I came here looking for a quick solution for this type of problem, and nuc's answer helped me come up with this:
$(document).ready(function(){
$('input[type=radio]').change(function() {
var selected = $(this);
$('input[type=radio]').each(function() {
if $(this).attr('id') != selected.attr('id') {
console.log( $(this).attr('value') + ' was deselected because ' + selected.attr('value') + ' was clicked.')
}
});
});
});
There is no event for when a radio button gets unchecked. You might be able to use the onpropertychange event, however that's not a standardised event so it might only work in Internet Explorer.
The safest way would be to take care of that in the onchange event. If you want to know which radio button was unchecked, you would have to keep a reference to the currently checked element in a variable.
I slightly modified rthbound's code to handle a group of radio input's, in my case enclosed in a <table>. But this could easily altered for a <div>. Also this code is more compliant with jQuery 1.9. A common class would be better, to take the class from the selected radio and find other radio inputs with the same class, but I'm working with ASP.NET and this is quicker and easier for me.
$(document).ready(function(){
$(document).on("change", "input[type='radio']", function () {
var selected = $(this);
$(this).closest("table").find("input[type='radio']").each(function () {
if ($(this).attr("id") !== selected.attr("id")) {
console.log($(this).attr("value") + " was deselected because " + selected.attr("value") + " was clicked.");
}
});
});
});
I've solved this issue in a generic way:
whenever a radio button is changed:
if they were triggered by this system - we don't want unending loops.
find all its radio button friends
trigger change on them
then I can test for whether the radio button was checked or unchecked.
$(function(){
$('body').on('change', 'input[type="radio"]', function(e, by_other) {
if (!by_other) {
$("input[type='radio'][name='" + $(this).attr('name') + "']")
.not(this)
.trigger('change', true)
}
}
}
(I did translate it from coffeescript to javascript for ya'll.)
The Radio buttons have same name, so we can select them by name.
Because .change() is not effected when the radio is unchecked, so we use .click() instead of.
$('input[name="your-radio-name"]').click(function() {
var $radios = $('input[name="your-radio-name"]');
for (var i = 0; i < $radios.length; i++) {
var radio = $radios[i];
if (radio != this) {
radio = $(radio);
// Process for unchecked radios here
}
}
// Now, process for checked radio
// alert(this.value + ' is checked'); Or
alert($(this).val() + ' is checked');
});

jQuery: Problems with detecting if a checkbox is checked

I'm creating a small jQuery plugin for my CMS that styles certain form input types (just radio, checkbox at the moment). It works by hiding the original form element and placing a normal HTML element (for styling with CSS) in the input's place. It then detects actions on the element and updates the original input accordingly. Additionally, it will also work when the associated label is clicked. Here is my code:
jQuery.fn.ioForm = function() {
return this.each(function(){
//For each input element within the selector.
$('input', this).each(function() {
var type = $(this).attr('type');
//BOF: Radios and checkboxes.
if (type == 'radio' || type == 'checkbox') {
var id = $(this).attr('id');
checked = '';
if ($(this).attr('checked')) {
checked = 'checked';
}
//Add the pretty element and hide the original.
$(this).before('<span id="pretty_'+ id +'" class="'+ type +' '+ checked +'"></span>');
$(this).css({ display: 'none' });
//Click event for the pretty input and associated label.
$('#pretty_'+ id +', label[for='+ id +']').click(function() {
if (type == 'radio') {
//Radio must uncheck all related radio inputs.
$(this).siblings('span.radio.checked').removeClass('checked');
$(this).siblings('input:radio:checked').removeAttr('checked');
//And then check itself.
$('#pretty_'+ id).addClass('checked');
$('#'+ id).attr('checked', 'checked');
} else if (type == 'checkbox') {
if ($('#'+ id).attr('checked')) {
//Checkbox must uncheck itself if it is checked.
$('#pretty_'+ id).removeClass('checked');
$('#'+ id).removeAttr('checked');
} else {
//Checkbox must check itself if it is unchecked.
$('#pretty_'+ id).addClass('checked');
$('#'+ id).attr('checked', 'checked');
}
}
});
} //EOF: Radios and checkboxes.
});
});
};
This works great for the radio, but the checkbox seems to get stuck when clicking the checkbox label for a second time - the first click of the label successfully changes it to the appropriate state, but clicking the label again doesn't change it (however the checkbox itself still works fine). It works perfectly in IE8.
I've checked the id is correct and it is. I've also tried a few other methods I stumbled across of checking if the checkbox is checked, but they either gave the same result or failed altogether. :(
Any help would be much appreciated.
Thanks :)
Update
Here is the HTML, which is generated by a PHP class. This is after the jQuery has run and added in the span elements:
<div>
<p class="label">Test:</p>
<span id="pretty_test_published_field" class="checkbox"></span>
<input class="checkbox" id="test_published_field" name="test" type="checkbox" value="published">
<label for="test_published_field" class="radio">Published</label>
<span id="pretty_test_draft_field" class="checkbox"></span>
<input checked="checked" class="checkbox" id="test_draft_field" name="test" type="checkbox" value="draft">
<label for="test_draft_field" class="radio">Draft</label>
</div>
Just use the infallible and extremely simple DOM checked property. jQuery is inappropriate for this and apparently makes one of the simplest JavaScript tasks there is error-prone and confusing. This also goes for the id and type properties.
$('input', this).each(function() {
var type = this.type;
if (type == 'radio' || type == 'checkbox') {
var id = this.id;
var checked = this.checked ? 'checked' : '';
// Etc.
}
});
UPDATE
The default action of clicking a <label> element associated with a checkbox is to toggle the checkbox's checkedness. I haven't tried this myself with labels for hidden form elements, but perhaps the toggling is still happening because you're not preventing the browser's default click action. Try the following:
//Click event for the pretty input and associated label.
$('#pretty_'+ id +', label[for='+ id +']').click(function(evt) {
if (type == 'radio') {
//Radio must uncheck all related radio inputs.
$(this).siblings('span.radio.checked').removeClass('checked');
$(this).siblings('input:radio:checked').each(function() {
this.checked = false;
});
//And then check itself.
$('#pretty_'+ id).addClass('checked');
$('#'+ id)[0].checked = true;
evt.preventDefault();
} else if (type == 'checkbox') {
if ($('#'+ id).attr('checked')) {
//Checkbox must uncheck itself if it is checked.
$('#pretty_'+ id).removeClass('checked');
$('#'+ id)[0].checked = false;
} else {
//Checkbox must check itself if it is unchecked.
$('#pretty_'+ id).addClass('checked');
$('#'+ id)[0].checked = true;
}
evt.preventDefault();
}
});
i've found on the odd accassion that i need to use the alternative of:
$("#checkboxID").is(':checked');
this may or not be an alternative in your scenario, but worth noting. Also, you may have to add the 'live' event, rather than 'click' if changes to the dom are occurring. i.e.
.click(function()
to
.live('click', function()
jim
The checked attribute of a checkbox is mapped to the defaultChecked property and not to the checked property. Use the prop() method instead.
If elem is the checkbox, use:
elem.checked
or
$(elem).prop("checked")
This gives us the proper state information of the checkbox and changes as the state changes.
This seems to be the reason of confusion in many cases. So its good to keep in mind the underlying reason behind this.
Could you show us the HTML? I am looking to see if you set a value property for the checkbox in the HTML. There is a possibility that broke it.
<input type="checkbox" value="This May Break Checkbox" />
<input type="checkbox" name="This Checkbox Works" />

Categories

Resources