get form element by using local variable in javascript function - javascript

get form element by using local variable in javascript function.
I need something like this..
function validateTxnProperties()
for (i = 1; i < 37; i++) {
if(checkMaxLength(document.formCollection.otherDocument<%=i%>Comments)){
return false;
}
}
}
I need to replace below code with for loop.
if(checkMaxLength(document.formCollection.otherDocument1Comments)){
return false;
}
if(checkMaxLength(document.formCollection.otherDocument2Comments)){
return false;
}
......
if(checkMaxLength(document.formCollection.otherDocument36Comments)){
return false;
}
Please update the question if i use wrong terms.

#Mark E is correct, bracket notation is probably the way to go in this situation, but the for loop variable i needs to be declared somewhere, thus the var keyword in the loop, finally you want to put the condition you want to test in another function so that the loop doesn't terminate after the first return false;:
function condition(variable){
if (checkMaxLength(document.formCollection["otherDocument" + variable + "Comments"])) {
return false;
}
}
for (var i = 0; i < 37; i++) {
condition(i);
}
Unless you do want the loop to terminate after the first return false* if so structure it like this:
for (var i = 0; i < 37; i++) {
if (checkMaxLength(document.formCollection["otherDocument" + variable + "Comments"])) {
return false;
}
}
If you wish for me to elaborate please do not hesitate to ask.

Related

Get object out of observable array

Why is m "undefined" in this code:
currentViewModel = ko.mapping.fromJS(viewModel);
currentViewModel.getReport = function(reportId) {
for(var i=0;i<currentViewModel.availableReports().length;i++) {
if(currentViewModel.availableReports()[i].id == reportId) {
var m = currentViewModel.availableReports()[i];
return currentViewModel.availableReports()[i];
}
}
}
I call getReport() as an onclick event and I want to send the report object to a view (modal) I can do a foreach on the availableReports and it's all there. When I run through the debugger, it loops through the array and finds the right one. But why can't I pull it out of the array? "m" remains undefined the the function returns undefined.
What am I missing here?
EDIT: there is a follow up question here:
Can knockout.js wait to bind until an onClick?
You just need to change if(currentViewModel.availableReports()[i].id ... to if(currentViewModel.availableReports()[i].id() ... because after mapping id will become an observable, i.e. function.
Updated code:
currentViewModel = ko.mapping.fromJS(viewModel);
currentViewModel.getReport = function(reportId) {
for (var i = 0; i < currentViewModel.availableReports().length; i++) {
if (currentViewModel.availableReports()[i].id() == reportId) {
var m = currentViewModel.availableReports()[i];
return currentViewModel.availableReports()[i];
}
}
}
Demo - Fiddle.
I'll repeat the solution from #NikolayErmakov's answer here, but want to add two things to get a more complete answer. You end with:
...m remains undefined and the function returns undefined.
What am I missing here?
You're missing two things:
The var m bit of the first statement inside the if is hoisted to the top of the current scope (the top of the function). This is why the debugger can tell you what m is, even if you never reach the line of code it's on.
If a function invocation reaches the end of a function (as is the case for you, since you never go inside the if) without seeing an explicit return statement, it will return undefined.
To better understand this, you should interpret your function like this:
currentViewModel.getReport = function(reportId) {
var m;
for (var i = 0; i < currentViewModel.availableReports().length; i++) {
if (currentViewModel.availableReports()[i].id == reportId) {
m = currentViewModel.availableReports()[i];
return currentViewModel.availableReports()[i];
}
}
return undefined;
}
Some people (e.g. Douglas Crockford) do recommend placing var statements at the top of a function, though it's a matter of style to some degree. I don't think many people explicitly return undefined at the end of a function, though in your case I might be explicit about that scenario and return null (or throw an Error even).
As promised, I'll repeat the actual solution, as I concur with the other answer:
you need to invoke id as a function to get its value (because the mapping plugin will map to observable()s.
In addition:
I'd retrieve the array only once
I'd suggest using === instead of ==
Here's my v0.5 version:
currentViewModel.getReport = function(reportId) {
var m = null, reports = currentViewModel.availableReports();
for (var i = 0; i < reports.length; i++) {
if (reports[i].id() === reportId) {
m = reports[i];
return m;
}
}
return m;
}
But I'd optimize it to this v1.0:
currentViewModel.getReport = function(reportId) {
var reports = currentViewModel.availableReports();
for (var i = 0; i < reports.length; i++) {
if (reports[i].id() === reportId) {
return reports[i];
}
}
return null;
}
For completeness, here's another version that utilizes filter on arrays:
currentViewModel.getReport = function(reportId) {
var reports = currentViewModel.availableReports().filter(function(r) { return r.id() === reportId; });
return reports.length >= 1 ? reports[0] : null;
}

how to check the presence of the element in the array?

please help solve the problem.
live example is here: https://jsfiddle.net/oqc5Lw73/
i generate several tank objects:
var Tank = function(id) {
this.id = id;
Tank.tanks.push(this);
}
Tank.tanks = [];
for (var i = 0; i < 3; i++) {
new Tank(i);
}
Tank.tanks.forEach(function(tank, i, arr) {
console.log(tank);
});
console.log('summary tanks: ' + Tank.tanks.length);
after i delete tank with random index:
var tankDel = Math.floor(Math.random() * (3));
Tank.tanks.splice(tankDel, 1);
Tank.count -= 1;
Tank.tanks.forEach(function(tank, i, arr) {
console.log(tank);
});
console.log('summary tanks: ' + Tank.tanks.length);
i try check tanks massive. if tanks massive contain tank with property 'id' = 0 then i need display alert('tank with id 0 is dead').
but console output follow error message:
Uncaught SyntaxError: Illegal break statement
break is to break out of a loop like for, while, switch etc which you don't have here, you need to use return to break the execution flow of the current function and return to the caller. See similar post here: illegal use of break statement; javascript
Tank.tanks.forEach(function(tank, i, arr) {
if(tank.id == 0) {
tank0Dead = false;
return;
};
});
if(tank0Dead == true) {
alert('tank with id 0 is dead');
};
jsfiddle : https://jsfiddle.net/oqc5Lw73/6/
You can't quit from forEach using break. Just remove break, and it will work.
P.S: honestly, it is better to refactor that code:)
Your only problem is that you can't use the break; statement in a forEach function.
But you can in a for() loop, so here is the equivalent code with a for :
for (var i = 0; i < Tank.tanks.length; i++){
if (Tank.tanks[i].id == 0){
tank0Dead = false;
break;
}
}
https://jsfiddle.net/oqc5Lw73/5/
But I agree with #dimko1 about the idea of refactoring the code
You can not break a forEach callback, simply because it's a function.
Here's updated working jSfiddle
If you really want to break it, you can use exception like code below.
try {
[1,2,3].forEach(function () {
if(conditionMet) {
throw Error("breaking forEach");
}
});
} catch(e) {
}
Otherwise you can use jQuery's each() method. when it's callback returns false it stops.
jQuery.each([1,2,3], function () {
if(conditionMet) {
return false;
}
});

JavaScript each in grep function

I have problem using grep function. My code is
var zapis = jQuery.grep(ListaGrupa, function(v, k) {
console.log($(that).attr("kursid"));
if (v.grupa.ID == $(that).attr("kursid")) {
idZaBrisanje = v.kategorija.Id;
return true;
}
if ($.each(v.grupa.Podgrupe, function(kljuc, vrednost) {
if (vrednost.podgrupa.ID == $(that).attr("kursid")) {
idZaBrisanje = vrednost.podkategorija.Id;
return true;
}
}))
return false;
})[0];
But is seems return true is in each scope, so in wont affect on grep function, so I get empty results.
Any help?
Yes, the return true in this case will act instruct your each function to continue the iteration. It will not break out of your grep function.
Instead, you may want to set a flag, and then return false, so as to terminate the iteration:
var found = false;
$.each(function() {
if(condition) {
found = true;
return false;
}
});
if(found)
return true;
Furthermore, $.each will always return the iterated object, which will always be truthy, so you can't use that inside a condition the way you're doing.
This is a scenario where you may reconsider whether jQuery is actually helping you. You may consider falling back to a regular for loop here, which would allow you to return out of the grep function immediately from within the iteration.
for(var i = 0; l = v.grupa.Podgrupe; i<l; i++) {
var vrednost = v.grupa.Podgrupe[i];
if(condition)
return true;
}

best syntax to set a global boolean variable in a loop in a function in javascript

So this is what I have right now:
var flag = false;
(function() {
for (var i = 0; i < 5; i += 1) {
// some code ....
// How can I rewrite the following?
if (!flag) {
flag = true;
// can't break
}
}
})();
console.log(flag);
http://jsfiddle.net/btc6wjw9/
My goal is set the flag to true when the function executes. What is the more elegant syntax with the same or better performance?
Thanks!
Update:
I have since learned that changing a boolean value is faster than checking it:
http://jsfiddle.net/xq7n7bry/
var flag = false;
(function() {
for (var i = 0; i < 5; i += 1) {
// some code ....
}
flag = true;
})();
console.log(flag);
I don't really understand the point of your question, but if you want to set it to true when the function is called, just set it to true when the function is called.
One way to rewrite:
if (!flag) {flag = true;}
is
flag = (!flag ? true: flag );
This is not necessarily better, as an assignment will be made at each iteration.

Why does the following javascript function always return true?

I have the following function, it will always return True. Any ideas why and how to avoid it? Thanks folks.
function validateStatuses(xyx){
var umm = ugh[xyx];
var selects = $('#cont_'+ugh.xyz+' .status_select');
var codes = $('#cont_'+ugh.xyz+' .status_code');
for (var i = 0; i < selects.length; i++) {
var value = selects[i].options[selects[i].selectedIndex].value;
if (value == 'new'){
for (var j = 0; j < codes.length; j++) {
var blagh = codes[j].options[codes[j].selectedIndex].value;
if(blagh == 13){
$('#info_dialog').html('');
$('#info_dialog').append("<p>You are trying to process a bill ("+bill.name+") with a STATUS of NEW and a STATUS CODE of NONE. Please correct this issue before you proceed!</p><hr />");
$('#info_dialog').dialog({
buttons:{
Cancel: function(){
$(this).dialog('close');
}
}
});
billCounterAdd();
return false;
}//end if
}//end for
}else{
return true; //this is the problem;
}//end if
}//end for
}//end Function
I dare say you have at least one select whose value isn't 'new'. Because you've done a return true; in the else clause, the first select with a value that isn't 'new' will cause the function to return true.
It looks like it does have a false return route (if there's a 'new' select at the beginning and there's a code select with the value 13), but perhaps that test case didn't come up in your testing.
In terms of figuring out what's wrong with things like this, there's nothing quite like walking through the code and watching it run line-by-line in a decent debugger. All major browsers have them built in now (finally), so you can see exactly what's happening and inspect variables, etc.

Categories

Resources