Welcome to the Treehouse Community
Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.
Looking to learn something new?
Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.
Start your free trial
James Moran
7,271 PointsWhy does code work inside function, but doesn't inside function call?
Hello,
I'm trying to disable a button on a form when an element on the page has the class "is-invalid". However, although my isValid() function returns true, if(isValid) does not run.
function isValid(targetName, className) {
$(targetName).each(function () {
if ($(this).hasClass(className)) {
console.log('false');
return false;
} else {
console.log('true');
return true;
}
});
}
$("fieldset *").keyup(function () {
if (isValid("fieldset *", "is-invalid")) {
console.log('valid');
$("button").removeAttr("disabled");
} else {
console.log('invalid');
$("button").attr("disabled", "disabled");
}
});
Here is a picture of the console: http://imgur.com/guGY6Ch
Thank you to anyone who helps!
2 Answers

mikes02
Courses Plus Student 16,968 PointsCouldn't you simplify this? This seems a bit heavy handed for what you are trying to do. Have you considered:
var $fieldset = $('fieldset *');
$fieldset.keyup(function () {
$(this).hasClass('is-invalid') ? $('button').prop('disabled', true) : $('button').prop('disabled', false);
)};
James Moran
7,271 PointsThank you Mike. I made a slight tweak and it works!
var $fieldset = $('fieldset *');
$fieldset.keyup(function () {
$fieldset = $('fieldset *');
$('fieldset:visible *').hasClass('is-invalid') ? $('button').prop('disabled', true) : $('button').prop('disabled', false);
});

mikes02
Courses Plus Student 16,968 PointsGreat, glad to set you on the right track. Although, I don't think you should have to define $fieldset within your keyup function, you've already defined it above. Have you tested it without the duplication?
James Moran
7,271 PointsYes! I need $fieldset again as it updates the validation.
Without it, the classes stay the same