Check checkbox depending of price in span - javascript

So I have a donation form and people can select different amounts to donate, so I want to automatically check a checkbox if the donation amount is bigger or equal than 20.
This the html (the data total stays the same the text is the element that change)
<span class="give-final-total-amount" data-total="20.00">$455.00</span>
<input type="checkbox" value="2" name="group[12581][2]" id="mce-group[12581]-12581-1">
This what I'm trying with jQuery
$( document ).ready(function() {
if ($(".give-final-total-amount").text() >= 20.00) {
jQuery("#mce-group[12581]-12581-1").prop("checked", true);
}
else {
$("#mce-group[12581]-12581-1").prop("checked", false);
}
});

The dollar sign is preventing your comparison from working. See additional comments below:
$(function() {
// Get a reference to the checkbox
var chk = document.getElementById("mce-group[12581]-12581-1");
// You can't compare the value of the span against a number if the value is not-numeric
// you have to remove the dollar sign first
if ($(".give-final-total-amount").text().replace("$", "") >= 20) {
// No need for JQuery on this, just set the checked property to true
chk.checked = true;
} else {
// Set checked property to false
chk.checked = false;
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<span class="give-final-total-amount" data-total="20.00">$455.00</span>
<input type="checkbox" value="2" name="group[12581][2]" id="mce-group[12581]-12581-1">

Related

jQuery toggle switch checkbox - changing "checked" attribute delay

I created a toggle switch checkbox and aplied the logic below:
1] If user clicks on toggle switch class="os_section-slider" the script will check if the input containing element's name is checked.
1-A] If the element is checked then change it to UNchecked and add that element into array named os_tagsToRemove
1-B] If the element is UNchecked then change it to checked and add that element into array named os_tagsToAdd
HTML
<span class="os_section-name">first</span>
<input type="checkbox" class="os_section-check" id="first" checked="checked">
<label class="os_section-slider" for="first"></label>
<div class="line-space-between"></div>
<span class="os_section-name">second</span>
<input type="checkbox" class="os_section-check" id="second">
<label class="os_section-slider" for="second"></label>
JS
$(".os_section-slider").click(function() {
if($(this).prev().is(":checked")) { //if checked
$(this).prev().attr("checked", false);
var os_tagName = $(this).prev().attr("id").toString();
os_tagsToRemove.push(os_tagName);
os_tagsToAdd.splice($.inArray(os_tagName, os_tagsToAdd),1);
} else { //if unchecked
$(this).prev().attr("checked", true);
var os_tagName = $(this).prev().attr("id").toString();
os_tagsToAdd.push(os_tagName);
os_tagsToRemove.splice($.inArray(os_tagName, os_tagsToRemove),1);
}
});
My problem is, when my page reloads and my toggle switch appears in a modal box and I try to click on the switcher button I have to click 2 times until the checked attribute is added/removed.
The first click always only pushes the value into the array or removes it from the array but doesn't apply $(this).prev().attr("checked", true); nor $(this).prev().attr("checked", false);.
But after the second click on each switcher button, everything from that moment works fine.
Add this to load your add/remove arrays:
// Onload remove array fill
$("[type='checkbox']").each(function(){
if( $(this).is(":checked") ){
os_tagsToRemove.push($(this).attr("id"));
}else{
os_tagsToAdd.push($(this).attr("id"));
}
});
Then, your logic was all reversed.
First, when you click on the label, which is defined as for="anID", the checked state of the coresponding checkbox already changes. You do not have to script that.
Then, when you look if it is checked, you have to know that this verification is made AFTER the checkbox state has changed. So I reversed your if conditions.
var os_tagsToAdd = [];
var os_tagsToRemove = [];
$(".os_section-slider").click(function() {
console.clear();
var os_tagName = $(this).prev().attr("id");
//if checked AFTER the click
if($(this).prev().is(":checked")) {
if($.inArray(os_tagName, os_tagsToAdd) == -1){
os_tagsToAdd.push(os_tagName);
}
os_tagsToRemove.splice($.inArray(os_tagName, os_tagsToRemove),1);
//if unchecked AFTER the click
} else {
if($.inArray(os_tagName, os_tagsToRemove) == -1){
os_tagsToRemove.push(os_tagName);
}
os_tagsToAdd.splice($.inArray(os_tagName, os_tagsToAdd),1);
}
console.log( os_tagsToAdd );
console.log( os_tagsToRemove );
});
// Onload remove array fill
$("[type='checkbox']").each(function(){
if( $(this).is(":checked") ){
os_tagsToRemove.push($(this).attr("id"));
}else{
os_tagsToAdd.push($(this).attr("id"));
}
});
console.log( os_tagsToAdd );
console.log( os_tagsToRemove );
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<span class="os_section-name">first</span>
<input type="checkbox" class="os_section-check" id="first" checked="checked">
<label class="os_section-slider" for="first">Label</label>
<div class="line-space-between"></div>
<span class="os_section-name">second</span>
<input type="checkbox" class="os_section-check" id="second">
<label class="os_section-slider" for="second">Label</label>

tetxtbox enable/disable on checkbox select/unselect using Javascript

I have a table with three columns and multiple rows. 2nd and third column consist of a textbox(first child of a container) and a checkbox respectively.
Textbox
<td class="SBS1 c4">
<input class="Medium InputText" type="text" name="QR~QID33#1~1~1~TEXT" id="QR~QID33#1~1~1~TEXT" value="" disabled="">
<label class="offScreen" for="QR~QID33#1~1~1~TEXT">&nbsp; - &nbsp; - hh</label>
</td>
Checkbox
<td class="SBS2 c7">
<input type="checkbox" id="QR~QID33#2~1~1" name="QR~QID33#2~1~1" value="Selected">
<label class="q-checkbox q-checked" for="QR~QID33#2~1~1"></label>
<label class="offScreen" for="QR~QID33#2~1~1">&nbsp; - 󠆺random text</label>
</td>
I have to disable and enable the textboxes in each row on checkbox check and uncheck respectively using javascript. but there seem to be some pagelifecycle issues with the script I am using. Here is the Javascript that I am using in my Qualtrics survey JS interface,
Qualtrics.SurveyEngine.addOnload(function()
{
/*Place Your JavaScript Here*/
var count=document.getElementsByClassName("q-checkbox").length;
for(var i=0;i<count;i++)
{
document.getElementsByClassName("q-checkbox")[i].parentNode.addEventListener("click",hideFunc);
}
function hideFunc()
{
console.log(this.className);
if(this.classList.contains("checkers"))
{
//this.classList.toggle("checkers");
this.previousSibling.previousSibling.previousSibling.firstChild.disabled="false";
this.classList.add("checkers");
return;
}
else
if(!(this.classList.contains("checkers")))
{
this.previousSibling.previousSibling.previousSibling.firstChild.disabled="true";
this.classList.remove("checkers");
return;
}
}
});
I am just trying to toggle or add/remove the class "checkers"and setting "disabled" property of the texboxes accordingly. The code above in HideFunc is one of the work-around I have tried but it is not working.
Is there another way to check for checkbox change?
As the first comment hinted, a better approach is to check the status of the checkbox rather than add/remove a class. Also, making use of prototypejs makes it easier. Try this:
Qualtrics.SurveyEngine.addOnload(function() {
var qid = this.questionId;
$(qid).select('tr.Choice').each(function(choice,idx) { //loop through each row
var cbox = choice.select('td.SBS2').first().down(); //cbox enables 1st question in row
var txtEl = choice.select('td.SBS1').first().down(); //text input to be enabled/disabled
if(cbox.checked == false) { //initialize text input disabled status
txtEl.value = null; //blank text input
txtEl.disabled = true; //disable text input
}
cbox.on('click', function(event, element) { //enable/disable text input on cbox click
if(cbox.checked == false) { //unchecked
txtEl.value = null; //blank text input
txtEl.disabled = true; //disable text input
}
else { //checked
txtEl.disabled = false; //enable text input
}
}); //end on function
}); //end row loop
});
This is another solution I could come up with ,apart from the correct solution by T. Gibbons
var $j= jQuery.noConflict();
$j("td.SBS2 ").click(function(){
$j(this).closest("tr").find(".InputText").prop("disabled",$j(this).children("input")[0].checked);
$j(this).closest("tr").find(".InputText").prop("value","");
var len=document.getElementsByClassName("InputText").length;
for(var i=0;i<=len;i++)
{
document.getElementsByClassName("InputText")[i].style.width="300px";
}
});

Add another condition to Show/Hide Divs

I have the follow script on a form.
jQuery(document).ready(function($) {
$('#bizloctype').on('change',function() {
$('#packages div').show().not(".package-" + this.value).hide();
});
});
</script>
Basically, depending on the value of the select box #bizloctype (value="1","2","3" or "4") the corresponding div shows and the rest are hidden (div class="package-1","package-2","package-3", or "package-4"). Works perfectly.
BUT, I need to add an additional condition. I need the text box #annualsales to be another condition determining which div shows (if the value is less than 35000 then it should show package-1 only, and no other packages.
I think the below script works fine when independent of the other script but I need to find out how to marry them.
<script>
$("#annualsales").change(function(){
$(".package-1,.package-2,.package-3,.package-4").hide();
var myValue = $(this).val();
if(myValue <= 35000){
$(".package-1").show();
}
else
{
$(".package-2").show();
}
});
</script>
Help please?
I would remove the logic from the anonymous functions and do something like this:
// handle display
function displayPackage( fieldID ) {
var packageType = getPackageType(fieldID);
$('#packages div').show().not(".package-" + packageType).hide();
}
// getting the correct value (1,2,3 or 4)
function getPackageType( fieldID ) {
// default displayed type
var v = 1;
switch(fieldID) {
case 'bizloctype':
// first check it annualsales is 1
v = (getPackageType('annualsales') == 1) ?
1 : $('#' + fieldID).val();
break;
case 'annualsales':
v = (parseInt($('#' + fieldID).val(),10) <= 35000) ? 1 : 2;
break;
}
return v;
}
jQuery(document).ready(function($) {
$('#bizloctype,#annualsales').on('change',function() {
displayPackage($(this).attr('id'));
});
});
If I understand your question properly, try this code out. It first adds an onChange listener to #annualsales which is the code you originally had. Then, for the onChange listener for #bizloctype, it simply checks the value of #annualsales before displaying the other packages.
jQuery(document).ready(function($) {
// Check value of #annualsales on change
$("#annualsales").change(function(){
$(".package-1,.package-2,.package-3,.package-4").hide();
var myValue = $(this).val();
if(myValue <= 35000){
$(".package-1").show();
}
// Only show other packages if value is > 35000
$('#bizloctype').on('change',function() {
$(".package-1,.package-2,.package-3,.package-4").hide();
if ($('#annualsales').val() <= 35000) {
$(".package-1").show();
} else {
$('#packages div').show().not(".package-" + this.value).hide();
}
});
});
Since you already use JQuery you can use the data() function to create a simple but dynamic condition system. For example, you could annotate each element with the required conditions and then attach change listeners to other elements to make the condition active or inactive for the elements.
For example, with this HTML:
<div id="conditions">
Condition 1: <input type="checkbox" id="check1" /> <= check this<br/>
Condition 2: <input type="checkbox" id="check2" /><br/>
Condition 3: <input type="text" id="value1" /> <= introduce 1001 or greater<br/>
Condition 4: <input type="text" id="value2" /><br/>
</div>
<p id="thing" data-show-conditions="check1 value1-gt-1000"
style="display: none;">
The thing to show.
</p>
And this Javascript:
function setShowCondition(el, condition, active) {
var conditions = $(el).data('conditions') || {};
conditions[condition] = active;
$(el).data('conditions', conditions);
var required = ($(el).data('show-conditions') || "").split(" ");
var visible = required.every(function (c) {
return conditions[c];
});
if (visible) {
$(el).show();
} else {
$(el).hide();
}
}
$("#conditions input[type='checkbox'").change(function () {
setShowCondition('#thing',
$(this).attr('id'),
$(this).is(':checked'));
});
$("#value1").change(function () {
var number = parseInt($(this).val());
setShowCondition('#thing', 'value1-gt-1000', number > 1000);
});
You can maintain conditions easily without having to nest and combine several if statements.
I've prepared a sample to show this in https://jsfiddle.net/2L5brd80/.

Validating a checkbox after already validating other sections of a form [duplicate]

I have a form with multiple checkboxes and I want to use JavaScript to make sure at least one is checked. This is what I have right now but no matter what is chosen an alert pops up.
JS (wrong)
function valthis(){
if (document.FC.c1.checked) {
alert ("thank you for checking a checkbox")
} else {
alert ("please check a checkbox")
}
}
HTML
<p>Please select at least one Checkbox</p>
<br>
<br>
<form name = "FC">
<input type = "checkbox" name = "c1" value = "c1"/> C1
<br>
<input type = "checkbox" name = "c1" value = "c2"/> C2
<br>
<input type = "checkbox" name = "c1" value = "c3"/> C3
<br>
<input type = "checkbox" name = "c1" value = "c4"/> C4
<br>
</form>
<br>
<br>
<input type = "button" value = "Edit and Report" onClick = "valthisform();">
So what I ended up doing in JS was this:
function valthisform(){
var chkd = document.FC.c1.checked || document.FC.c2.checked||document.FC.c3.checked|| document.FC.c4.checked
if (chkd == true){
} else {
alert ("please check a checkbox")
}
}
I decided to drop the "Thank you" part to fit in with the rest of the assignment. Thank you so much, every ones advice really helped out.
You should avoid having two checkboxes with the same name if you plan to reference them like document.FC.c1. If you have multiple checkboxes named c1 how will the browser know which you are referring to?
Here's a non-jQuery solution to check if any checkboxes on the page are checked.
var checkboxes = document.querySelectorAll('input[type="checkbox"]');
var checkedOne = Array.prototype.slice.call(checkboxes).some(x => x.checked);
You need the Array.prototype.slice.call part to convert the NodeList returned by document.querySelectorAll into an array that you can call some on.
This should work:
function valthisform()
{
var checkboxs=document.getElementsByName("c1");
var okay=false;
for(var i=0,l=checkboxs.length;i<l;i++)
{
if(checkboxs[i].checked)
{
okay=true;
break;
}
}
if(okay)alert("Thank you for checking a checkbox");
else alert("Please check a checkbox");
}
If you have a question about the code, just comment.
I use l=checkboxs.length to improve the performance. See http://www.erichynds.com/javascript/javascript-loop-performance-caching-the-length-property-of-an-array/
I would opt for a more functional approach. Since ES6 we have been given such nice tools to solve our problems, so why not use them.
Let's begin with giving the checkboxes a class so we can round them up very nicely.
I prefer to use a class instead of input[type="checkbox"] because now the solution is more generic and can be used also when you have more groups of checkboxes in your document.
HTML
<input type="checkbox" class="checkbox" value=ck1 /> ck1<br />
<input type="checkbox" class="checkbox" value=ck2 /> ck2<br />
JavaScript
function atLeastOneCheckboxIsChecked(){
const checkboxes = Array.from(document.querySelectorAll(".checkbox"));
return checkboxes.reduce((acc, curr) => acc || curr.checked, false);
}
When called, the function will return false if no checkbox has been checked and true if one or both is.
It works as follows, the reducer function has two arguments, the accumulator (acc) and the current value (curr). For every iteration over the array, the reducer will return true if either the accumulator or the current value is true.
the return value of the previous iteration is the accumulator of the current iteration, therefore, if it ever is true, it will stay true until the end.
Check this.
You can't access form inputs via their name. Use document.getElements methods instead.
Vanilla JS:
var checkboxes = document.getElementsByClassName('activityCheckbox'); // puts all your checkboxes in a variable
function activitiesReset() {
var checkboxesChecked = function () { // if a checkbox is checked, function ends and returns true. If all checkboxes have been iterated through (which means they are all unchecked), returns false.
for (var i = 0; i < checkboxes.length; i++) {
if (checkboxes[i].checked) {
return true;
}
}
return false;
}
error[2].style.display = 'none'; // an array item specific to my project - it's a red label which says 'Please check a checkbox!'. Here its display is set to none, so the initial non-error label is visible instead.
if (submitCounter > 0 && checkboxesChecked() === false) { // if a form submit has been attempted, and if all checkboxes are unchecked
error[2].style.display = 'block'; // red error label is now visible.
}
}
for (var i=0; i<checkboxes.length; i++) { // whenever a checkbox is checked or unchecked, activitiesReset runs.
checkboxes[i].addEventListener('change', activitiesReset);
}
Explanation:
Once a form submit has been attempted, this will update your checkbox section's label to notify the user to check a checkbox if he/she hasn't yet. If no checkboxes are checked, a hidden 'error' label is revealed prompting the user to 'Please check a checkbox!'. If the user checks at least one checkbox, the red label is instantaneously hidden again, revealing the original label. If the user again un-checks all checkboxes, the red label returns in real-time. This is made possible by JavaScript's onchange event (written as .addEventListener('change', function(){});
You can check that atleast one checkbox is checked or not using this simple code. You can also drop your message.
Reference Link
<label class="control-label col-sm-4">Check Box 2</label>
<input type="checkbox" name="checkbox2" id="checkbox2" value=ck1 /> ck1<br />
<input type="checkbox" name="checkbox2" id="checkbox2" value=ck2 /> ck2<br />
<script>
function checkFormData() {
if (!$('input[name=checkbox2]:checked').length > 0) {
document.getElementById("errMessage").innerHTML = "Check Box 2 can not be null";
return false;
}
alert("Success");
return true;
}
</script>
< script type = "text/javascript" src = "js/jquery-1.6.4.min.js" > < / script >
< script type = "text/javascript" >
function checkSelectedAtleastOne(clsName) {
if (selectedValue == "select")
return false;
var i = 0;
$("." + clsName).each(function () {
if ($(this).is(':checked')) {
i = 1;
}
});
if (i == 0) {
alert("Please select atleast one users");
return false;
} else if (i == 1) {
return true;
}
return true;
}
$(document).ready(function () {
$('#chkSearchAll').click(function () {
var checked = $(this).is(':checked');
$('.clsChkSearch').each(function () {
var checkBox = $(this);
if (checked) {
checkBox.prop('checked', true);
} else {
checkBox.prop('checked', false);
}
});
});
//for select and deselect 'select all' check box when clicking individual check boxes
$(".clsChkSearch").click(function () {
var i = 0;
$(".clsChkSearch").each(function () {
if ($(this).is(':checked')) {}
else {
i = 1; //unchecked
}
});
if (i == 0) {
$("#chkSearchAll").attr("checked", true)
} else if (i == 1) {
$("#chkSearchAll").attr("checked", false)
}
});
});
< / script >
Prevent user from deselecting last checked checkbox.
jQuery (original answer).
$('input[type="checkbox"][name="chkBx"]').on('change',function(){
var getArrVal = $('input[type="checkbox"][name="chkBx"]:checked').map(function(){
return this.value;
}).toArray();
if(getArrVal.length){
//execute the code
$('#msg').html(getArrVal.toString());
} else {
$(this).prop("checked",true);
$('#msg').html("At least one value must be checked!");
return false;
}
});
UPDATED ANSWER 2019-05-31
Plain JS
let i,
el = document.querySelectorAll('input[type="checkbox"][name="chkBx"]'),
msg = document.getElementById('msg'),
onChange = function(ev){
ev.preventDefault();
let _this = this,
arrVal = Array.prototype.slice.call(
document.querySelectorAll('input[type="checkbox"][name="chkBx"]:checked'))
.map(function(cur){return cur.value});
if(arrVal.length){
msg.innerHTML = JSON.stringify(arrVal);
} else {
_this.checked=true;
msg.innerHTML = "At least one value must be checked!";
}
};
for(i=el.length;i--;){el[i].addEventListener('change',onChange,false);}
<label><input type="checkbox" name="chkBx" value="value1" checked> Value1</label>
<label><input type="checkbox" name="chkBx" value="value2"> Value2</label>
<label><input type="checkbox" name="chkBx" value="value3"> Value3</label>
<div id="msg"></div>
$('input:checkbox[type=checkbox]').on('change',function(){
if($('input:checkbox[type=checkbox]').is(":checked") == true){
$('.removedisable').removeClass('disabled');
}else{
$('.removedisable').addClass('disabled');
});
if(($("#checkboxid1").is(":checked")) || ($("#checkboxid2").is(":checked"))
|| ($("#checkboxid3").is(":checked"))) {
//Your Code here
}
You can use this code to verify that checkbox is checked at least one.
Thanks!!

jQuery check if checkbox is checked and update the value of the texbox with the checkbox's value and uncheck if it's empty

Here what I am trying to do is, if I check the checkbox the value of the respective checkbox should be appended to the textbox by using "," as delimiter between the values. And If the value of the checked respective checkbox is empty it should alert that email ID is invalid and uncheck that checkbox whose value is empty.
What's Working :
- If I check the checkbox the value is appending to the textbox.
- If I check the checkbox whose value is empty I'm getting alert.
- If I uncheck the values are automatically removed from the textbox.
What's Not working:
- Email ID validation isn't working. Function is written but it's not working. (No Errors in console)
- If I have selected few options by checking the boxes which has value and then if I select the checkbox whose value is empty I am not getting the invalid email ID alert.
Here is the code below.
HTML:
<label>Recipients : </label>
<input style="width:450px;" type="text" id="toaddress" name="toaddress"></input>
<br>
<div class="plist" style="padding:20px;">
<input type="checkbox" value="abcp#gmail.com">Pradeep</input><br>
<input type="checkbox" value="cd#gmail.com">Karthik</input><br>
<input type="checkbox" value="abcn#p.com">akfkl</input><br>
<input type="checkbox" value="ksake#po.com">afljs</input><br>
<input type="checkbox" value="">abc</input><br>
<input type="checkbox" value="">xyzop</input><br>
<input type="checkbox" value="abc#cto.com">jay</input><br>
<input type="checkbox" value="">raj</input><br>
</div>
JavaScript:
function updateTextArea() {
var allVals = [];
$('.plist :checked').each(function (i) {
if ($.trim($('.plist :checked').val()) === '' && validateEmail($('.plist :checked').val())) {
$(this)
alert("Email ID is invalid for the selected patient ! \n Example: abc#xyz.com");
} else {
allVals.push((i !== 0 ? "\r\n" : "") + $(this).val());
}
$('#toaddress').val(allVals).attr('rows', allVals.length);
});
}
$(function () {
$('.plist input').click(updateTextArea);
updateTextArea();
});
function validateEmail($email) {
var emailReg = /^([\w-\.]+#([\w-]+\.)+[\w-]{2,4})?$/;
if (!emailReg.test($email)) {
return false;
} else {
return true;
}
}
Link to JSFiddle is here
http://jsfiddle.net/RhjjA/
Check http://jsfiddle.net/RhjjA/3/
I changed the validateEmail
Changed the checked when you loop through it to $(this).
I was thinking about checking if the value is empty or not valid, because neither of those conditions are allowed to pass the check. So added ! infron of the validateEmail.
I added an $(this).attr('checked', false);
This should help you get on your way.
if ($.trim($(this).val()) === '' && validateEmail($(this).val())) {
$(this).attr('checked',false);
alert("Email ID is invalid for the selected patient ! \n Example: abc#xyz.com");
Your code works fine except for one tiny detail, after your if condition, you have added $(this). This isn't terminated with a semi-colon, nor is it required. Comment this line and try.
http://jsfiddle.net/RhjjA/5/
I did that from your first question : jsfiddle.net/hBGD6/4/
The 2 main problems were
if ("string is empty" AND "validateEmail" ) couldn't work (so all string were ok). should be if ("string is empty" OR "NOT validateEmail" )
the param used by validateEmail() was the return of a function which is null (or something undefined) which was invalid for emailReg.test()

Categories

Resources