As part of a validate onsubmit function, I wish a function isFilled(var str) to be invoked. However, it is failing to be invoked successfully and as a result the validateForm() function is terminated prematurely.
<script type = "text/javascript">
function validateForm(){
...
alert(isFilled("bla bla bla"));
...
}
function isFilled(var str){ // checks that the given string isn't empty
if(str == "" || str == " "){
return false;
}else{
return true;
}
}
</script>
Furthermore I am not being informed by the browser's console of the error. Should I wrap my code in try/catch statements? If so, how?
Declaring function arguments is incorrect in javascript. Corrected code:
function isFilled(str){ // checks that the given string isn't empty
if(str == "" || str == " "){
return false;
}else{
return true;
}
}
You're trying to declare a variable in a function parameter. Just give it a parameter name
str can be called whatever you want it to be:
function isFilled(parameter){ // checks that the given string isn't empty
if(parameter == "" || parameter == " "){
return false;
}else{
return true;
}
}
Related
I want to return false and return from function if I find first blank textbox
function validate(){
$('input[type=text]').each(function(){
if($(this).val() == "")
return false;
});
}
and above code is not working for me :(
can anybody help?
You are jumping out, but from the inner loop, I would instead use a selector for your specific "no value" check, like this:
function validate(){
if($('input[type=text][value=""]').length) return false;
}
Or, set the result as you go inside the loop, and return that result from the outer loop:
function validate() {
var valid = true;
$('input[type=text]').each(function(){
if($(this).val() == "") //or a more complex check here
return valid = false;
});
return valid;
}
You can do it like this:
function validate(){
var rv = true;
$('input[type=text]').each(function(){
if($(this).val() == "") {
rv = false; // Set flag
return false; // Stop iterating
}
});
return rv;
}
That assumes you want to return true if you don't find it.
You may find that this is one of those sitautions where you don't want to use each at all:
function validate(){
var inputs = $('input[type=text]');
var index;
while (index = inputs.length - 1; index >= 0; --index) {
if (inputs[index].value == "") { // Or $(inputs[index]).val() == "" if you prefer
return false;
}
}
// (Presumably return something here, though you weren't in your example)
}
I want to add something to existing answers to clear the behavior of $(selector).each and why it doesn't respect return false in OP's code.
return keyword inside $(selector).each is used to break or continue the loop. If you use return false, it is equivalent to a break statement inside a for/while loop. Returning non-false is the same as a continue statement in a for loop; it will skip immediately to the next iteration. Source
Because you're returning false, the loop breaks and the function ends up returning undefined in your case.
Your option is to use a var outside $.each or avoid using it altogether as #TJCrowder wrote.
I have simple javascript functions which executing a simple string based on some data. Javascript functions i am using are
function checkdata() {
var data = document.getElementById('data').value;
if (data != '') {
console.log("Hello");
return false;
} else {
return true;
}
}
function gotothen() {
console.log("Bye");
}
function changemode(value) {
if (value == 0) {
checkdata();
gotothen();
}
if (value == 1) {
checkdata();
gotothen();
}
}
and the html code i am using are
<input type="text" name="data" id="data">
Hotel
Flight
so if i enter any value to textbox and click on any of the hyperlink it calls changemode() function. there are two function i am calling in changemode() function. One is checkdata() and the other is gotothen(). So if textbox value is not blank then it should not call gotothen() function but it is calling. It should stop after printing "Hello" only but it is calling gotothen() function too after using return false. So how can i stop the execution of gotothen() function if text-box value is not blank ?
It looks like your code is returning false but not actually using that.
You'll want a piece of logic like
if(checkdata()){
gotothen();
}
and you can put it on the outside of your changemode block, like this:
function changemode(value) {
if( checkdata()){
if(value == 0) {
gotothen();
}
if(value == 1) {
gotothen();
}
}
}
because function checkdata has return value, you should capture it for deciding to call gotothen or not.
var check = checkdata();
if (check != false) {
gotothen();
}
or simplify that to:
if (checkdata() != false) gotothen();
and we can simplify again:
if (true_value != false) ...
with:
if (true_value) ...
You are calling gotothen() no matter what. The result from checkdata() doesn't change anything. You don't usr it in the changemode() function, and the changemode function is the one that should eventually return true or false.
You should change your code so that the result from checkdata() is the condition to calling gotothen(). It should be:
if (checkdata())
gotothen();
// ... further execution
I have a function expression like this :
var inputChecker = function(field) {
return function() {
if(field === '' || field === 'undefined' || field === null) {
return false;
}
return true;
}
}
that I want to use in several different function expressions :
(function($) {
if(inputChecker(x)) {}
})(jQuery);
(function($) {
})(jQuery);
But the problem is inputChecker is not visible in these function expressions when it's declared out of their bodies ? I don't understand why? Isn't inputChecker supposed to be global ?
Dystroy's answer is definitely simpler. But if you want it your way...
The return value of the inputChecker is a function, not boolean. If you want to call the returned function, use () expression:
var fn = inputChecker(x); // gets the function
fn(); // calls the returned function
or shorter
inputChecker(x)();
In your code
(function($) {
if(inputChecker(x)()) {
// custom code here if x is defined
}
})(jQuery);
Note: if you want to check if variable is not undefined, strip the apostrophes - undefined is constant, not string
if(field===undefined)
What you wrote is a function factory. It doesn't return a boolean but a function able to check a property.
This kind of functions is sometimes useful but :
you're here, in the returned function, checking the value of the property received by the factory. As this value can't change (it's embedded in the closure), the produced function holds no more information than just true or false. So it's useless.
you're calling inputChecker(x) as if it was a boolean instead of a function.
So what you probably want is simply
var checkInput = function(field) {
if(field === '' || field === 'undefined' || field === null){
return false;
}
return true;
}
But if you really want to generate different checking functions, dependent on another value, you could use the function factory pattern like this:
var x = true;
var checkInput = (function (x) {
if (x === true) {
return function(field) {
if(field === '' || field === 'undefined' || field === null){
return false;
}
return true;
}
} else {
return function(field) {
//evaluate field differently
}
}
}(x));
Now, dependig on what x is, one or another function will be assigned to checkInput.
Trying to learn JavaScript, makin decent progress I guess, but I'm stuck at validating a form, tried to see if anybody has the same problem, search didn't turn anything up. So would you please help me?
var minlength = 6;
var pwlength = document.getElementById('psswrd');
var invalid = " ";
function validate() {
if (pwlength.length < minlength && pwlength == invalid) {
alert("Password not valid");
else {
alert("Password okay!");
}
}
submitbtn.onClick = validate();
It is not obvious where you call this - I have wrapped it in a window.onload
you do not access the button correctly. Either of
document.forms[0].submitbtn
document.getElementById("submitbtn") or
document.getElementsByName("submitbtn")[0] will work depending on how you name or ID the button HOWEVER do not assign onclick handlers to submit buttons, instead assign submit handler to the form
there is no point of testing for a single space since that is less than 6 chars anyway.
&& is AND, you mean || OR
onclick must be all lowercase.
You assign the onclick to the result of validate instead of validate
You do not stop the submission
I have taken the trim from here
and I assume the form has ID="form1"
window.onload=function()
document.getElementById("form1").onsubmit = validate;
}
if(typeof String.prototype.trim !== 'function') { // let's help older IEs
String.prototype.trim = function() {
return this.replace(/^\s+|\s+$/g, '');
}
}
function validate() {
var minlength = 6;
var pw = document.getElementById('psswrd');
if (pw.value.length < minlength || pw.value.trim() == "") {
alert("Password not valid");
pw.focus();
return false;
}
return true; // allow submission
}
var minlength = 6;
var pwlength = document.getElementById('psswrd');
var invalid = " ";
function validate() {
if (pwlength.length < minlength && pwlength == invalid) {
alert("Password not valid");
}
else {
alert("Password okay!");
}
}
You have a few problems here.
1) pwlength.length won't get you very far. pwlength is equal to an html object, not the value of an html object. Change the actual variable to the following and you should get the correct results:
var pwlength = document.getElementById('psswrd').value;
2) Before the else part of your if ... else statement, you need to end the if statement by closing it with a curly bracket (}). Change that part to the following:
} else {
3) Your validation to check and see if the length == invalid is odd. Double check that and get rid of it.
4) Your onclick event needs to look something like this:
submitbtn.onclick = function(){ validate() };
Notice: lowercase event keyword and function() { ... }; wrapped around the function you want to run.
"return false;" for form submission is working for the rest of my code, just not this section. Any ideas why?
function checkForm() {
$("select[name*=lic_company]").each(function() {
if($(this).val() != '') {
var i1 = $(this).parent("td").next("td").children("select");
var i2 = i1.parent("td").next("td").children("input");
var i3 = i2.parent("td").next("td").children("input");
if(i1.val() == '') {
i1.parent("td").addClass("formErrorTD");
i1.addClass("formError");
alert("You must enter a state for this license");
return false;
}
if(i2.val() == '') {
i2.parent("td").addClass("formErrorTD");
i2.addClass("formError");
alert("You must enter an expiration date for this license");
return false;
}
if(i3.val() == '') {
i3.parent("td").addClass("formErrorTD");
i3.addClass("formError");
alert("You must enter a license number for this license");
return false;
}
}
});
}
and it's being called by
$("#addAgentForm").submit(checkForm);
You are calling return false; within a closure that is an argument passed to .each. Therefore, .each is capturing the return false;. To get around this you need need to have a boolean flag that holds the state of the form:
function checkForm() {
var okay = true;
$("select[name*=lic_company]").each(function() {
...
return okay = false;
...
});
return okay;
}
And everything will work fine.
Your return false statements are inside the anonymous function passed to .each(), so only return a value from that function, not the entire call to checkForm().
If I had to guess, it's because you're returning from the function passed to your each call, meaning all you're really doing is exiting your each function while your main validation function finishes without a hitch.