This is driving me completely nuts. I can't figure out how to check/uncheck a checkbox through JavaScript.
I have the following in my HTML file:
<div class="form-group">
<label class="col-sm-3 control-label"></label>
<div class="col-sm-9">
<div class="checkbox">
<input id="hardhat" type="checkbox" name="hardhat" checked="false" class="flat"/> Does the employee need his own hardhat?
</div>
</div>
</div>
Which translates to this in Jade:
.form-group
label.col-sm-3.control-label
.col-sm-9
.checkbox
input#hardhat(type='checkbox', name='hardhat', class='flat', checked='false')
| Does the employee need his own hardhat?
Having the checked property in HTML will ALWAYS open the window with the checkbox checked. The only way to uncheck the checkbox is to remove the checked property. What am I missing?
Because of this, nothing I do in JavaScript to check/uncheck the checkbox works :(. I was trying this:
var $modal = $('#editJob');
$modal.find('input#hardhat')['checked']=true;
Any help would be greatly appreciated!
EDIT:
function showJobInfo(event) {
document.getElementById('editJob').style.display = "block";
document.getElementById('editJob').style.visibility = "visible";
// Prevent Link from Firing
event.preventDefault();
// Retrieve job title from link rel attribute
var thisJobTitle = $(this).attr('rel');
// Get Index of object based on id value
var arrayPosition = userJoblistData.map(function(arrayItem) { return arrayItem.title; }).indexOf(thisJobTitle);
// Get our Job Object
var thisJobObject = userJoblistData[arrayPosition];
// Populate the edit job popup window
var $modal = $('#editJob');
$modal.find('input#jobTitle').val(thisJobObject.title);
$modal.find('input#payRate').val(thisJobObject.payrate);
$modal.find('input#startDate').val(thisJobObject.durationstart);
$modal.find('input#endDate').val(thisJobObject.durationend);
$modal.find('input#workingHours').val(thisJobObject.workinghrs);
$modal.find('input#location').val(thisJobObject.location);
$('#hardhat').prop('checked', false);
}
I do not understand what is the problem. If you want always checked, add checked="true" html attribute.
https://jsfiddle.net/yw3obrrt/
<input id="hardhat" type="checkbox" name="hardhat" checked="true" class="flat"/>
Check in jade that checked='true'
input#hardhat(type='checkbox', name='hardhat', class='flat', checked='true')
| Does the employee need his own hardhat?
For test, not use F5 because remember your selection.
If not works.. try with jquery and use
$(document).ready(function (){
$("#hardhat").attr("checked",true);
});
https://jsfiddle.net/yw3obrrt/1/
In your example!!
$('#hardhat').prop('checked', false);
This line, unchecked checkbox!
Change to
$('#hardhat').attr('checked', true); // attr or prop
or comment this and add checked="true" in the html input!
Related
I would like, on load of the page, to check if a checkbox is :checked Then if it is, add a class to the label. I currently have the following script but it doesn't work.
$(document).ready(function() {
$('input').is(':checked') {
$(this).parent('label').toggleClass('label--active');
});
});
My HTML is:
<label class="container-checkbox" for="checkOne">
<span class="checkbox-label">Option one</span>
<input type="checkbox" id="checkOne">
<span class="checkmark"></span>
</label>
I can not change the DOM order as these are custom checkboxes.
I guess you can use this:
$(document).ready(function() {
let checkboxone = document.getElementById('checkOne');
checkboxone.addEventListener('change',function() {
checkboxone.parentNode.classList.toggle('label--active');
});
});
How does is work?
Everytime when the checkbox is clicked, the class 'label--active' will be added / removed.
I've used similar code earlier in the application and it works, but for some reason, I cannot get anything inside the .each function here to fire.
I have an application where you can check a membership checkbox to apply a 10% credit to the premium of a premise. The number of premises is dynamic, so when you check the membership box, the javascript creates a premise checkbox for each user-created premise on the page. No problem there.
But, I need to find the label for each premise that is checked under the membership box, and my code is failing. The alerts inside that .each do not fire. I've rewritten it to go Div by Div to reach those checkboxes, but I still cannot reach it.
HTML
<div class="form-check creditChecks">
<input class="form-check-input creditCheckInput" type="checkbox" value='4' id="Membership">
<label class="form-check-label" for="Membership">Association Membership</label>
<div class="creditPremiseSelect">
<div class="form-check">
<input class="form-check-input creditPremiseInput" type="checkbox" value='1' id="MembershipcreditPrem1">
<label class="form-check-label" for="MembershipcreditPrem1">Premise #1</label>
</div>
</div>
Javascript to append more premise checkboxes:
//Populate Credit/Debit Premise Selector
function loadSelectPrems(ele){
var firedInput = ele;
var inputID = ele.attr('id');
var thisDiv = firedInput.closest('.creditChecks');
var selector = thisDiv.find('.creditPremiseSelect');
//Empty selector
selector.empty();
//Find all Premises on Policy
$('.premiseList').find('.premise').each(function(index){
var premiseID = $(this).find('.premiseNum').text();
var premNum = index+1;
selector.append($(`
<div class='form-check'>
<input class='form-check-input creditPremiseInput' type='checkbox' value='`+premNum+`' id='`+inputID+`creditPrem`+premNum+`'>
<label class='form-check-label' for='`+inputID+`creditPrem`+premNum+`'>`+premiseID+`</label>
</div>
`))
});
}
JQuery that isn't working as expected:
if($('#Membership').is(':checked')){
doc.text(25, lineCount, 'Association Membership Credit 10% applied to:');
updateLine('s');
alert("Membership checked"); //This alert fires
$(this).closest('.creditChecks').find('.creditPremiseInput').each(function(){
alert("Looking at premises"); //This alert does not fire
if($(this).is(':checked')){
alert("Found checked premise");
var labeltxt = $(this).closest('.creditPremiseSelect').find('.form-check-label').text();
doc.text(30, lineCount, labeltxt);
updateLine('s');
}
});
updateLine('n');
}
I'm going to go out on a limb and say the error is on this line:
$(this).closest('.creditChecks').find('.creditPremiseInput').each...
It appears you are referencing $(this) as being $('#Membership'), but it isn't. Also, as you've assigned a singular ID $('#Membership'), I think you probably just need to access $('.creditChecks') directly in that line.
if ($('#Membership').is(':checked')) {
doc.text(25, lineCount, 'Association Membership Credit 10% applied to:');
updateLine('s');
alert("Membership checked"); //This alert fires
$('.creditChecks').find('.creditPremiseInput').each(function() {
alert("Looking at premises"); //This alert does not fire
if ($(this).is(':checked')) {
alert("Found checked premise");
var labeltxt = $(this).closest('.creditPremiseSelect').find('.form-check-label').text();
doc.text(30, lineCount, labeltxt);
updateLine('s');
}
});
updateLine('n');
}
right now I am a beginner in Javascript/Jquery.
I want to create a dynamic code, so that it will work when there comes some new features to the website without need to edit code.
Now i just read in some posts how to use a variable as identifier for id, but it is not working for me. So below is an example:
var category;
$('#mainCategory').change(function (event) {
checkboxID = event.target.id;
category="category"+checkboxID;
...some code...
});
$("#"+category).change(function (event) {
$('#category'+checkboxID+' :input').attr('class','' );
console.log("var: "+category);
});
So the function mainCategory always runs before the other one and category got written correct in the 2nd function, when i am using the whole expression instead of using a variable.
I hope you can help me.
the part of html code:
<form method="post" action="../php/saveTraining.php">
<section id="mainCategory" class="hidden">
<label><input type="checkbox" id="Krafttraining">Krafttraining</label>
<label><input type="checkbox" id="Joggen">Joggen</label>
</section>
<section id="categoryKrafttraining" class="hidden">
<label><input type="checkbox">Kurzhantel</label>
<label><input type="checkbox">Bankdrücken</label>
<label class="hidden"><input type="number" id="saetze">Sätze</label>
<label class="hidden"><input type="number" id="wiederholungen">Wiederholungen</label>
</section>
<input type="hidden" id="saveTraining" name="sent" value="save" class="hidden"/>
</form>
So what actually happens is that when checking a checkbox of mainCategory the checkboxes of the second section appearing.
But when I check a checkbox of the second section nothing happens.
I thought I had the solution before but I see I was wrong. I believe this should work, where you re-add the listener as the value for the var category change:
var category;
$('#mainCategory input[type="checkbox"]').change(function (event) {
checkboxID = event.target.id;
category="category"+checkboxID;
$('#' + category).find('input[type="checkbox"]').off("change").on("change", function (event) {
$('#category'+checkboxID+' :input').attr('class','' );
console.log("var: "+category);
});
});
You need to re-add the listener because new elements will be targeted as var category changes.
I am trying to toggle the value of a checkbox using the following code:
<div class="control-group">
<label class="control-label checkbox" for="IsViewAsWebpage">
{{#if this.IsViewAsWebpage}}
<input type="hidden" id="IsViewAsWebpage" name="IsViewAsWebpage" value="true"/>
<input type="checkbox" class="enable-checkbox" checked />
{{else}}
<input type="hidden" id="IsViewAsWebpage" name="IsViewAsWebpage" value="false"/>
<input type="checkbox" class="enable-checkbox" />
{{/if}}
<span>View as Webpage</span>
</label>
</div>
'click .enable-checkbox': function (e) {
if (e.currentTarget.parentElement.htmlFor == "IsViewAsWebpage") {
this.$('#IsViewAsWebpage').is(':checked');
}
}
I know I am misssing something in the click function. I would basically want to toggle the checkbox value when the user clicks on it. Can someone point me to the right directions pls. Thank you.
When your checkbox gets clicked, it's going to toggle. That's the way checkboxes work.
If you want the hidden input to change value when the checkbox is toggled, I think what you want is this:
$(".enable-checkbox").change(function (e) {
if($(this).parent().attr("for") == "IsViewAsWebpage") {
var checked = $(this).is(":checked"); // Returns true/false.
$('#IsViewAsWebpage').attr("value", checked); // Sets true/false.
}
});
If you want to use handlebars.js to switch content when you click an check box, you will need to replace your content by calling handlebars each time you make a modification to your checkbox
$(".enable-checkbox").change(function (e) {
if($(this).parent().attr("for") == "IsViewAsWebpage") {
var checked = $(this).is(":checked");
IsViewAsWebpage = checked;
$("#yourcontainer").html(Handlebars.compile(yourtemplatesource));
}
}
then your IsViewAsWebpage variable should be global and your mustache condition should only be :
{{#if IsViewAsWebpage}}
But this is complicated for nothing... just use Aesthete solution, it will save you a lot of time.
Hello guys i have the below html for a number of products on my website,
it displays a line with product title, price, qty wanted and a checkbox called buy.
qty input is disabled at the moment.
So what i want to do is,
if the checkbox is clicked i want the input qty to set to 1 and i want it to become enabled.
I seem to be having some trouble doing this. Could any one help
Now i can have multiple product i.e there will be multiple table-products divs within my html page.
i have tried using jQuery to change the details but i dont seem to be able to get access to certain elements.
so basically for each table-product i would like to put a click listener on the check box that will set the value of the input-text i.e qty text field.
so of the below there could be 20 on a page.
<div class="table-products">
<div class="table-top-title">
My Spelling Workbook F
</div>
<div class="table-top-price">
<div class="price-box">
<span class="regular-price" id="product-price-1"><span class="price">€6.95</span></span>
</div>
</div>
<div class="table-top-qty">
<fieldset class="add-to-cart-box">
<input type="hidden" name="products[]" value="1"> <legend>Add Items to Cart</legend> <span class="qty-box"><label for="qty1">Qty:</label> <input name="qty1" disabled="disabled" value="0" type="text" class="input-text qty" id="qty1" maxlength="12"></span>
</fieldset>
</div>
<div class="table-top-details">
<input type="checkbox" name="buyMe" value="buy" class="add-checkbox">
</div>
<div style="clear:both;"></div>
</div>
here is the javascript i have tried
jQuery(document).ready(function() {
console.log('hello');
var thischeck;
jQuery(".table-products").ready(function(e) {
//var catTable = jQuery(this);
var qtyInput = jQuery(this).children('.input-text');
jQuery('.add-checkbox').click(function() {
console.log(jQuery(this).html());
thischeck = jQuery(this);
if (thischeck.is(':checked'))
{
jQuery(qtyInput).first().val('1');
jQuery(qtyInput).first().prop('disabled', false);
} else {
}
});
});
// Handler for .ready() called.
});
Not the most direct method, but this should work.
jQuery(document).ready(function() {
jQuery('.add-checkbox').on('click', function() {
jQuery(this)
.parents('.table-products')
.find('input.input-text')
.val('1')
.removeAttr('disabled');
});
});
use
jQuery('.add-checkbox').change(function() {
the problem is one the one hand that you observe click and not change, so use change rather as it really triggers after the state change
var qtyInput = jQuery(this).children('.input-text');
another thing is that the input is no direct child of .table-products
see this fiddle
jQuery('input:checkbox.add-checkbox').on('change', function() {
jQuery(this)
.parent()
.prev('div.table-top-qty')
.find('fieldset input:disabled.qty')
.val(this.checked | 0)
.attr('disabled', !this.checked);
});
This should get you started in the right direction. Based on jQuery 1.7.2 (I saw your prop call and am guessing that's what you're using).
$(document).ready(function() {
var thischeck;
$('.table-products').on('click', '.add-checkbox', function() {
var qtyInput = $(this).parents('.table-products').find('.input-text');
thischeck = $(this);
if (thischeck.prop('checked')) {
$(qtyInput).val('1').prop('disabled', false);
} else {
$(qtyInput).val('0').prop('disabled', true);
}
});
});
Removing the property for some reason tends to prevent it from being re-added. This works with multiple tables. For your conflict, just replace the $'s with jQuery.
Here's the fiddle: http://jsfiddle.net/KqtS7/5/