execute a function once in a for loop - javascript

I have to check a list of array using for loop, then do ONE single function base on the result, like
for(var i=0;i<settingData.length;i++){
if(settingData[i].a !== '' && $scope.settingData[i].b){
save();
}else{
alert('missing fields');
}
}
how can I make the save() to execute once? because when I put an alert it will trigger few times because it's within a for loop. I can't take it out because I have to check through all of my array..

Add a break after you save function:
for(var i=0;i<settingData.length;i++){
if(settingData[i].a !== '' && $scope.settingData[i].b){
save();
break;
}else{
alert('missing fields');
}
}

You can set a missingFields variable.
var missingFields = false;
for(var i=0;i<settingData.length;i++){
if(! (settingData[i].a !== '' && $scope.settingData[i].b) ) {
missingFields = true;
alert('missing fields');
break;
}
}
if (!missingFields) {
save();
}

Related

Jquery: check if variable is defined after keyup() function

Am creating register form with jquery function keyup(),
for example if input is correct I assign it to a txtuname variable,then I press register button and I need to know that all form variables are correct and defined.Code below is not working:
<script type="text/javascript">
$("document").ready(function() {
$("#txtuname").keyup(function() {
if ($("#txtuname").val().length < 6) {
jQuery("label[for='txtuname']").text("user name is too short");
}
if ($("#txtuname").val().length >= 6) {
var txtuname = $("#txtuname").val();
jQuery("label[for='txtuname']").text("");
}
});
$("#submitRegistration").click(function() {
if (typeof txtuname == 'defined') {
alert("defined");
}
if (typeof txtuname == 'undefined') {
alert("undefined");
}
});
});
</script>
Modified code. Main point of this code is that txtuname should be visible in both scopes of keyup event listner and click listner. So if there are more lements, create Validation object and just check whether all the values was set and correct. And yes, use or $ or jQuery in your code.
$("document").ready(function(){
var txtuname = null;
$("#txtuname").keyup(function(){
if($("#txtuname").val().length<6){
jQuery("label[for='txtuname']").text("user name is too short");
}
if($("#txtuname").val().length>=6){
txtuname=$("#txtuname").val();
jQuery("label[for='txtuname']").text("");
}
});
$("#submitRegistration").click(function(){
if( txtuname == null || txtuname.length < 6) ){
alert("incorrect");
}
else{
alert("correct");
}
});
});
Updated check of variable using comment of #Rhumborl , thx
Replace code with below condition -
if( typeof txtuname !== 'undefined' && txtuname.length >= 6) ){
//proceed further
}else{
alert('Please correct entries.');
return false;
}
I would put the validation logic in a function and call that, you can update this with your specific requirements and only do it once:
function isValidName(field) {
var myName = field.val().trim();
// some of this is redundant but just to show possibilities
var isValid = myName.length && myName.length >= 6 && myName && undefined !== myName && myName != " ";
var myLabel = $("label[for='" + field.attr('id') + "']");
if (isValid) {
myLabel.text("");
} else {
myLabel.text("user name is too short");
}
return isValid;
}
$("document").ready(function() {
$("#txtuname").keyup(function() {
isValidName($(this));
});
$("#submitRegistration").click(function() {
var nameIsValid = isValidName($("#txtuname"));
if (nameIsValid) {
alert("valid");
} else {
alert("undefined or invalid");
}
});
});
You are using $ as well as jQuery window.jQuery object in your code. Do not use both at time , you can check by both
jQuery("document").ready(function() { jQuery("#txtuname").keyup(function(){ if(jQuery("#txtuname").val().length<6){
jQuery("label[for='txtuname']").text("user name is too short");
}
if(jQuery("#txtuname").val().length>=6){
var txtuname=jQuery("#txtuname").val();
jQuery("label[for='txtuname']").text("");
}
});
jQuery("#submitRegistration").click(function(){
if(typeof txtuname =='defined'){
alert("defined");
}
if(typeof txtuname =='undefined'){
alert("undefined");
}
});
});
Or use by replace jQuery by $ sign. It will work.
you can try this way too......
$("document").ready(function(){
var txtuname;
$("#txtuname").keyup(function(){
if($("#txtuname").val().length<6){
jQuery("label[for='txtuname']").text("user name is too short");
}
if($("#txtuname").val().length>=6){
txtuname=$("#txtuname").val();
jQuery("label[for='txtuname']").text("");
}
});
$("#submitRegistration").click(function(){
if(typeof txtuname=="undefined"){
alert("undefined");
}
else{
alert("defined");
}
});
});

Javascript - while loop doesn't show success option

Why my code never alerts "be happy"?
It works for every other option, but not this one. Why so?
var i = "";
while (i != "YES"){
if(i == "NO"){
alert("You should be!");
}
else if(i == "YES") {
alert("Be happy!")
}
else{
if(i == ""){
}
else {
alert("C'mon dude... Answer simply yes or no!");
}
}
i = prompt("Are You happy?").toUpperCase();
}
Because when you enter the loop, the condition just ensure that i will never be 'Yes' when the loop starts.
Pull your i = prompt("Are You happy?").toUpperCase(); to the start of the loop.
When the user is prompted to write down "YES", you exit the while loop. Put it on top
var i = "";
while (i != "YES"){
i = prompt("Are You happy?").toUpperCase(); //*************** Put it here
if(i == "NO"){
alert("You should be!");
}
else if(i == "YES") {
alert("Be happy!")
}
else{ //Not needed (do else { alert("com...")} )
if(i == ""){
}
else {
alert("C'mon dude... Answer simply yes or no!");
}
}
}

jConfirm message cannot work properly

The confirmation popup always return true. Please advice the correction needed.
$('#btnDelete').click(function () {
var check = false;
var aCheckbox = document.getElementsByTagName('input');
for (var i = 0; i < aCheckbox.length; i++) {
if (aCheckbox[i].type === 'checkbox' && aCheckbox[i].checked) {
check = true;
}
}
if (check === true) {
return jConfirm('Do u really want to delete?', 'Confirmation');
} else {
jAlert("Please select serial number", 'Alert');
return false;
}
});
Hope this help :
if (check === true) {
var answer = confirm('Do u really want to delete?', 'Confirmation');
if(answer)
return true;
else
return false;
}
else {
jAlert("Please select serial number", 'Alert');
return false;
}
Yes it creates problem you need to use third parameter as callback function of jconfirm like,
if (check === true) {
jConfirm('Do u really want to delete?', 'Confirmation', function(r) {
jAlert('Confirmed: ' + r, 'Confirmation Results');
});
return false;
} else {
.....
Also remove extra closing }); from your code, see last two lines.

Checkbox in HTML turns off a function in a .js file

I am looking to make a checkbox that when unchecked, will turn off a certain function in a .js file. Can someone help me?
popup.html
HTML Check box:
content.js
Turn off this function:
var tweet = new Array();
var tweetName = new Array();
function linkSnipe() {
for (var i = 0; i < 5; i++) {
tweetName[i] = document.getElementsByClassName("fullname js-action-profile-name show-popup-with-id")[0].innerHTML;
tweet[i] = document.getElementsByClassName("js-tweet-text")[i].innerHTML;
}
if (tweet[0].match(shoeName) == shoeName && tweet[0].match(filterer) != filterer && tweet[0].match(filter2) != filter2) {
if(checkon == "Tweets"){
document.getElementsByClassName("twitter-timeline-link")[0].click();
update();
}
}
else if (tweet[1].match(shoeName) == shoeName && tweet[1].match(filterer) != filterer && tweet[1].match(filter2) != filter2) {
if(checkon == "Tweets"){
document.getElementsByClassName("twitter-timeline-link")[1].click();
update();
}
}
else if (tweet[2].match(shoeName) == shoeName && tweet[2].match(filterer) != filterer && tweet[2].match(filter2) != filter2) {
if(checkon == "Tweets"){
document.getElementsByClassName("twitter-timeline-link")[2].click();
update();
}
}
else if (tweet[3].match(shoeName) == shoeName && tweet[3].match(filterer) != filterer && tweet[3].match(filter2) != filter2) {
if(checkon == "Tweets"){
document.getElementsByClassName("twitter-timeline-link")[3].click();
update();
}
}
else if (tweet[4].match(shoeName) == shoeName && tweet[4].match(filterer) != filterer && tweet[4].match(filter2) != filter2) {
if(checkon == "Tweets"){
document.getElementsByClassName("twitter-timeline-link")[4].click();
update();
}
}
else if(checkon == "Tweets") {
location.reload();
}
}
setTimeout("linkSnipe()", 250);
}
When the checkbox is checked, redefine the function as:
<input type=checkbox ..... onchange="doit()">
function doit() {
window.linkSnipe=function() {}
}
I've used this too:
function doit() {
window['linkSnipe']=function() {}
}
If you want to turn the function on and off by the checkbox:
<input type=checkbox ..... onchange="doit(this)">
var linkSnipeSave = linkSnipe;
function doit(ck) {
if (ck.checked)
window['linkSnipe']=linkSnipeSave
else {
linkSnipeSave = linkSnipe; //not sure if this line is needed...pls test
window['linkSnipe']=function() {}
}
}
You could simply have a Boolean variable that changes with the state of your check box. You could then put an if statement around the function call that will only trigger if the checkbox is checked.
http://jsfiddle.net/W5P8X/
//initialize some variables.
bike_checked = false;
car_checked = false;
//get elements by their ID from html
bike = document.getElementById("bike");
car = document.getElementById("car");
//add event listeners to the html elements we found above
bike.addEventListener("click", toggle_bike, false);
car.addEventListener("click", toggle_car, false);
//toggle bike_checked variable on click
function toggle_bike(){
if(bike_checked == true)
bike_checked = false;
else
bike_checked=true;
current_state();
}
//toggle car_checked variable on click
function toggle_car(){
if(car_checked == true)
car_checked = false;
else
car_checked=true;
current_state();
}
//output current state.
function current_state(){
if(car_checked == true)
alert('Car checked');
if(bike_checked == true)
alert('Bike checked');
}
I answered with only javascript and no jQuery, but you could probably make it a bit more concise with jQuery.
I hope this helps.

How to validate multiple functions with one IF statement - Javascript, jQuery

I want to validate multiple functions, and for each one returning false, do some animations.
Here's the code:
function validarChido(){
var dedo = $('#dedo_pick');
if(dedo.children().size() < 2){
dedo.animate({'background-color' : 'red'},200);
dedo.animate({'background-color' : '#EEE'},200);
return false;
}
else{return true;}
}
function validarEx(){
var valEx = $('#rate1');
if(valEx.children().size() < 2){
valEx.animate({'background-color' : 'red'},200);
valEx.animate({'background-color' : '#EEE'},200);
return false;
}
else{return true;}
}
$('#form').submit(function(){
if( validarChido() && validarEx() )
{return true }
else
{return false; }
});
When I send the form, I only see the first function doing the color animation, obviously because the form validation IF statement doesn't evaluate the next function because the first resulted in false here if( validarChido() && validarEx() )
Is there a way to evaluate all the functions and see the animation in each one and then send the form if everything is true?
Instead of returning false or true do something similar to the following:
function validarChido() {
var dedo = $('#dedo_pick');
if(dedo.children().size() < 2){
dedo.animate({'background-color' : 'red'},200);
dedo.animate({'background-color' : '#EEE'},200);
return "error";
}
else{return "";}
}
function validarEx(){
var valEx = $('#rate1');
if(valEx.children().size() < 2){
valEx.animate({'background-color' : 'red'},200);
valEx.animate({'background-color' : '#EEE'},200);
return "error";
}
else{return "";}
}
$('#form').submit(function(){
var check = validarChido();
check += validarEx();
if( check == "" )
{return true }
else
{return false; }
});
It can be something like this:
$('#form').submit(function(){
var validarChidoResult = validarChido(),
validarExResult = validarEx();
if( validarChidoResult && validarExResult )
{return true }
else
{return false; }
});
var result = validarChido();
result = validarEx() && result;
return result;

Categories