So, I have some faux checkboxes (so I could style them) that work with jQuery to act as checked or not checked. There are a number of faux checkboxes in my document, and for each one I have a click function:
var productInterest = [];
productInterest[0] = false;
productInterest[1] = false;
productInterest[2] = false;
// here is one function of the three:
$('#productOne').click(function() {
if (productInterest[0] == false) {
$(this).addClass("checkboxChecked");
productInterest[0] = true;
} else {
$(this).removeClass("checkboxChecked");
productInterest[0] = false;
}
});
The problem seems to be that there is an error in the if statement, because it will check, but not uncheck. In other words it will add the class, but the variable won't change so it still thinks its checked. Anybody have any ideas? Thanks for your help.
UPDATE: So, I need to show you all my code because it works in the way I supplied it (thanks commenters for helping me realize that)... just not in the way its actually being used on my site. so below please find the code in its entirety.
Everything needs to happen in one function, because the UI and data for each checkbox need to be updated at once. So here is the complete function:
$('input[name=silkInterest]').click(function() { // they all have the same name
var silkInterest = [];
silkInterest[0] = false;
silkInterest[1] = false;
silkInterest[2] = false;
if ($(this).is('#silkSilk')) { // function stops working because the .is()
if (silkInterest[0] == false) {
$(this).addClass("checkboxChecked");
silkInterest[0] = true;
} else {
$(this).removeClass("checkboxChecked");
silkInterest[0] = false;
}
alert(silkInterest[0]);
}
if ($(this).is('#silkAlmond')) {
if (silkInterest[1] == false) {
$(this).addClass("checkboxChecked");
silkInterest[1] = true;
} else {
$(this).removeClass("checkboxChecked");
silkInterest[1] = false;
}
}
if ($(this).is('#silkCoconut')) {
if (silkInterest[2] == false) {
$(this).addClass("checkboxChecked");
silkInterest[2] = true;
} else {
$(this).removeClass("checkboxChecked");
silkInterest[2] = false;
}
}
var silkInterestString = silkInterest.toString();
$('input[name=silkInterestAnswer]').val(silkInterestString);
// This last bit puts the code into a hidden field so I can capture it with php.
});
I can't spot the problem in your code, but you can simply use the class you're adding in place of the productInterest array. This lets you condense the code down to a single:
// Condense productOne, productTwo, etc...
$('[id^="product"]').click(function() {
// Condense addClass, removeClass
$(this).toggleClass('checkboxChecked');
});
And to check if one of them is checked:
if ($('#productOne').hasClass('checkboxChecked')) {...}
This'll make sure the UI is always synced to the "data", so if there's other code that's interfering you'll be able to spot it.
Okay, just had a palm to forehead moment. In regards to my revised code- the variables get reset everytime I click. That was the problem. Duh.
Related
I have a flip toggle button().I am writing a function on change of toggle button,on change I am declaring js confirm box ,if confirms true the button remains in changed state,else it will revert in its previous state.My issue is the function is getting iterating(looping).Please suggest
To me it looks quite ok. Maybe you just forgot to encapsulate your code in $(document).ready - this is necessary because otherwise your Javascript function will be loaded before the HTML DOM has been loaded - so your function will fail to access the DOM elements.
$(document).ready(function() {
$("#btn").on("change", function() {
var txt;
var btnStatus = $("#btn").val();
console.log("btnstataus>>>>>" + btnStatus);
var r = confirm("Are you sure to change?");
if (r == true) {
if (btnStatus == "on") {
$("#btn").val("on");
} else {
$("#btn").val("off");
}
} else {
if (btnStatus == "on") {
$("#btn").val("off");
} else {
$("#btn").val("on");
}
}
});
});
Here is a working sample of your code:
https://plnkr.co/edit/AdzcN04F1fsLe9xw454j?p=preview
Ok, I have a form with lots of different inputs, each has the same class name on it. What I need to do is loop though all of these inputs, which the user can add more to, with an AJAX call, making sure all inputs are four numbers only.
Now I can get it to check that it is of a length but when I try to add a check to make sure its a number, it does not seem to work, this is my current code:
var ValidMyData = function() {
$('#FORM-ID-HERE').on('submit',function(e) {
e.preventDefault();
Numbers = $('.NumberClass');
//Check if job number is only 4 in length
function CheckNumbers() {
$(Numbers).each(function() {
var GetCurrentInput = $(this).val();
if( GetCurrentInput.length != 4 ) {
return $(this).css("background-color","#FF0004");
} else {
return $(this).css("background-color","transparent");
} //End of if
}); //End of each
} //end of inner function
}); //end of on submit function
} //end of valid check function
ValidMyData();
This works, if the inputs on my number field are not four in length, it makes the background color red, and then removes that background color if its then changed to be four.
I have tried some things but nothing as worked. I have mainly being playing with the IsNumeric() function, by adding that on my if check. Also, although this works, I don't think my return call is working right, I think I am doing something wrong but can not put my finger on it :). - When I console.log the CheckNumbers() inner function, I get undefined back.
All help most welcome.
Thanks
this code will check if it is 4 characters and if it's a number:
var ValidMyData = function() {
$('#FORM-ID-HERE').bind('submit',function(e) {
Numbers = $('.NumberClass');
//Check if job number is only 4 in length
function CheckNumbers() {
Numbers.each(function() {
var GetCurrentInput = $(this).val();
if( GetCurrentInput.length != 4 || !/([0-9])+/.test(String(GetCurrentInput))) {
return $(this).css("background-color","#FF0004");
e.preventDefault();
} else {
$(this).css("background-color","transparent");
} //End of if
}); //End of each
} //end of inner function
}); //end of on submit function
} //end of valid check function
ValidMyData();
EDIT
I updated the answer using your own code, which now will submit the form if all the inputs are filled correctly, else it highlights it and doesn't submit the form.
I have here script for Enabled and Disabled submit button. I tried to use each function but isn't working. Every fields had it's value from database. The process should not allowed to submit if one of the fields was empty. Every fields has a value because I used it for editing window. Any help will appreciate. Thanks..
And this my fiddle http://jsfiddle.net/cj6v8/
$(document).ready(function () {
var saveButton = $("#save");
var empty = true;
$('input[type="text"]').change(function () {
$('.inputs').each(function () {
if ($(this).val() != "") {
empty = false;
} else {
empty = true;
}
});
if (!empty) {
saveButton.prop("disabled", false);
} else {
saveButton.prop("disabled", true);
}
});
}); // END OF DOCUMENT READY
The problem is the first else statement.
When $('.inputs').each(... iterates through your fields the empty variable is re-assigned a new value for every input field. In other words, the way you did it, only the last field was significant. (To test it, try this: leave the last one empty, and the button will be disabled, no matter what you put in the first two fields.)
Instead, try initializing empty at false just before the loop (you assume your fields are all filled with something), and then, when you iterate, as soon as you come across an empty field, set empty to true.
var empty = false;
$('.inputs').each(function() {
if($(this).val() == "")
empty = true;
});
As you can see, I removed the problematic else.
you need to init empty to false and cange it only if you find empty inputs inside to loop. http://jsfiddle.net/cj6v8/1/
If you don't want to submit when at least one field is empty you'll need to do this:
....
var empty = true;
$('input[type="text"]').change(function () {
empty = false;
$('.inputs').each(function () {
if ($(this).val() == "") {
empty = true;
break;
}
}
...
each is asynchronous, http://jsfiddle.net/cj6v8/4/
$(document).ready(function() {
var saveButton = $("#save");
$('input[type="text"]').change(function() {
var empty = true;
var inputs = $('.inputs');
inputs.each(function(i) {
if ($(this).val().length == 0) {
console.log($(this).val());
empty = false;
}
if (i === inputs.length-1) saveButton.attr("disabled", !empty);
});
});
});// END OF DOCUMENT READY
<script>
function no_email_confirm() {
if (document.getElementsByName("no_email")[0].checked == false) {
return true;
} else {
var box= confirm("Sure?");
if (box==true)
return true;
else
document.getElementsByName("no_email")[0].checked == false;
}
}
</script>
And here is my HTML for the checkbox:
<input type="checkbox" id="no_email" name="no_email" onchange="no_email_confirm()"></input>
For some reason, this gives me the confirm pop up the first time I check the box, but not for any click after that. Also, even if I click "Cancel" it still checks the check box. I've searched on here and for some reason, no matter what I try, I can't get it to work properly.
It should confirm if they really want to check the box, if they select "Yes" then it checks it, if not, then it doesn't check it. I can get it to work without the name no_email, but I can't change that..
Anyone have any ideas?
Looks like you've got several errors in there, most notably using == when you probably meant =. Instead, add an event listener and make sure the assignment works:
var box = document.querySelector('#no_email');
box.addEventListener('change', function no_email_confirm() {
if (this.checked == false) {
return true;
} else {
var confirmation= confirm("This means that the VENDOR will NOT RECEIVE ANY communication!!!!");
if (confirmation)
return true;
else
box.checked = false;
}
});
http://jsfiddle.net/A3VGg/1/
Problem statement:
It is necessary for me to write a code, whether which before form sending will check all necessary fields are filled. If not all fields are filled, it is necessary to allocate with their red colour and not to send the form.
Now the code exists in such kind:
function formsubmit(formName, reqFieldArr){
var curForm = new formObj(formName, reqFieldArr);
if(curForm.valid)
curForm.send();
else
curForm.paint();
}
function formObj(formName, reqFieldArr){
var filledCount = 0;
var fieldArr = new Array();
for(i=reqFieldArr.length-1; i>=0; i--){
fieldArr[i] = new fieldObj(formName, reqFieldArr[i]);
if(fieldArr[i].filled == true)
filledCount++;
}
if(filledCount == fieldArr.length)
this.valid = true;
else
this.valid = false;
this.paint = function(){
for(i=fieldArr.length-1; i>=0; i--){
if(fieldArr[i].filled == false)
fieldArr[i].paintInRed();
else
fieldArr[i].unPaintInRed();
}
}
this.send = function(){
document.forms[formName].submit();
}
}
function fieldObj(formName, fName){
var curField = document.forms[formName].elements[fName];
if(curField.value != '')
this.filled = true;
else
this.filled = false;
this.paintInRed = function(){
curField.addClassName('red');
}
this.unPaintInRed = function(){
curField.removeClassName('red');
}
}
Function is caused in such a way:
<input type="button" onClick="formsubmit('orderform', ['name', 'post', 'payer', 'recipient', 'good'])" value="send" />
Now the code works. But I would like to add "dynamism" in it.
That it is necessary for me: to keep an initial code essentially, to add listening form fields (only necessary for filling).
For example, when the field is allocated by red colour and the user starts it to fill, it should become white.
As a matter of fact I need to add listening of events: onChange, blur for the blank fields of the form. As it to make within the limits of an initial code.
If all my code - full nonsense, let me know about it. As to me it to change using object-oriented the approach.
Give me pure Javascript solution, please. Jquery - great lib, but it does not approach for me.
To keep your HTML clean, I suggest a slightly different strategy.
Use a framework like jQuery which makes a lot of things much more simple.
Move all the code into an external script.
Use the body.onLoad event to look up all forms and install the checking code.
Instead of hardcoding the field values, add a css class to each field that is required:
<input type="text" ... class="textField required" ...>
Note that you can have more than a single class.
When the form is submitted, examine all fields and check that all with the class required are non-empty. If they are empty, add the class error otherwise remove this class. Also consider to add a tooltip which says "Field is required" or, even better, add this text next to the field so the user can see with a single glance what is wrong.
In the CSS stylesheet, you can then define a rule how to display errors.
For the rest of the functionaly, check the jQuery docs about form events.
Has made.
function formsubmit(formName, reqFieldArr){
var curForm = new formObj(formName, reqFieldArr);
if(curForm.valid)
curForm.send();
else{
curForm.paint();
curForm.listen();
}
}
function formObj(formName, reqFieldArr){
var filledCount = 0;
var fieldArr = new Array();
for(i=reqFieldArr.length-1; i>=0; i--){
fieldArr[i] = new fieldObj(formName, reqFieldArr[i]);
if(fieldArr[i].filled == true)
filledCount++;
}
if(filledCount == fieldArr.length)
this.valid = true;
else
this.valid = false;
this.paint = function(){
for(i=fieldArr.length-1; i>=0; i--){
if(fieldArr[i].filled == false)
fieldArr[i].paintInRed();
else
fieldArr[i].unPaintInRed();
}
}
this.send = function(){
document.forms[formName].submit();
}
this.listen = function(){
for(i=fieldArr.length-1; i>=0; i--){
fieldArr[i].fieldListen();
}
}
}
function fieldObj(formName, fName){
var curField = document.forms[formName].elements[fName];
this.filled = getValueBool();
this.paintInRed = function(){
curField.addClassName('red');
}
this.unPaintInRed = function(){
curField.removeClassName('red');
}
this.fieldListen = function(){
curField.onkeyup = function(){
if(curField.value != ''){
curField.removeClassName('red');
}
else{
curField.addClassName('red');
}
}
}
function getValueBool(){
if(curField.value != '')
return true;
else
return false;
}
}
This code is not pleasant to me, but it works also I could not improve it without rewriting completely.
jQuery adds a lot of benefit for a low overhead. It has a validation plugin which is very popular. There are some alternatives as well but I have found jQuery to be the best.
Benefits
small download size
built in cross browser support
vibrant plug-in community
improved productivity
improved user experience