Multiple Selectors on If Statement - javascript

So, I'm trying to make sure a button is disabled to prevent a user from saving data from form field entries whenever two conditions are met:
The checkbox is checked
There's nothing inside the form field in question ( #read_return_response_rate_ids )
This is what I have to that end:
$('body').on("change","#tab3 #read_return_response_rate_ids", function(){
if ($(this).is('')) && ($('input:checkbox').is(':checked')) {
$('.create_read_btn').attr('disabled', 'disabled');
} else {
$('.create_read_btn').removeAttr('disabled');
}
});
The error it's giving me in the console is totally useless towards debugging purposes.
Uncaught SyntaxError: Unexpected token /
It's my thought that this is where the problem exists:
if ($(this).is('')) && ($('input:checkbox').is(':checked'))
Basically, I don't think I can have multiple selectors as I have them structured, but I don't know. Does anyone have any thoughts on why this is returning an error? I confirmed that this code block is where the error originates by selectively commenting out other blocks of code and whittling it down to this one.

There are syntax errors (parenthesis chars note required):
Change:
if ($(this).is('')) && ($('input:checkbox').is(':checked')) {
by
if ($(this).is('') && $('input:checkbox').is(':checked')) {

The argument to .is() must be a selector or jQuery collection; it tests whether the specified element matches the selector or is the same set of objects. If you want to test whether an input field is empty, you need to use .val() to get the value.
if ($(this).val() == '' && $('input:checkbox').is(':checked')) {

Related

Most efficient js/jquery way to prevent submission of empty fields (including spaces)

I have an advanced search form in a custom CMS. I need to check to make sure that the user doesn't try to submit the form without at least one field populated. No problem; this is a very stripped-down version:
var noText = false;
if(!$('#advancedId').val() && !$('#advancedTitle').val() &&
$('#advancedCoupon').val() && !$('#advancedDesc').val() ) {
noText = true;
}
if(noText) {
alert("You haven't provided any search terms. Please fill in/select at least one field.");
noText = false;
return false;
}
But we have that one QA guy who just has to really do his job, and deliberately tries searches that there's no way our client would ever do. He submitted a bug indicating that if he entered a space in every field, it passes and tries to submit.
So I tried trimming the values like this:
if(!$('#advancedId').val().trim() && !$('#advancedTitle').val().trim() &&
$('#advancedCoupon').val().trim() && !$('#advancedDesc').val().trim() ) {
noText = true;
}
This of course works if I actually enter a space in all of the fields, but throws a "Cannot read property 'trim' of null" error if I try to submit it with a space in one field, and nothing in the others.
Yes, I could do something like this:
if($('#advancedId').val()) {
$('#advancedId').val($('#advancedId').val().trim());
}
Yes, I could make it somewhat shorter with a terniary, but I'd still have to do that for over a dozen fields. Is there a better way to do this?
I would probably select them all and then do a filter. Though to make it less tightly coupled, I'd probably put a class on them and select with that instead of all the ids.
//select all the fields concerned and filter on them for non-blank values
var nonBlankFields = $('#advancedId, #advancedTitle, #advancedCoupon, #advancedDesc').filter(function(){
//default to an empty string if for some reason the value doesn't exist
return ( this.value || '' ).trim().length > 0
});
if (!nonBlankFields.length) {
alert("You haven't provided any search terms. Please fill in/select at least one field.");
return false;
}

Comparing el.text() === "string" results in false, even when element contains "string"

In the below code, the else and not the if is always executed even though the alert tells me that state does in fact contain the string payment.
var state = $('.check-state').text();
alert(state); // payment
if (state === "payment")
alert('hello');
else
alert('not match')
Why is that?
I am guessing your HTML look sort of like this:
<div class="check-state">
payment
</div>
Then the .text() will return everything between the > and the <, including the whitespace. So what you get is "\n payment\n", not "payment".
The solution is to trim the whitespace away, using jQuerys $.trim():
var state = $.trim($('.check-state').text());
On a side note, I would recommend you to use console.log() instead of alert() for debugging. In most browsers, that would have allowed you to detect where the error was since you would have clearly seen the whitespace.

javascript variables always not equal

I have two variables, totalGuess and condensedAnswer. I am creating a jQuery click event and if totalGuess doesn't equal condensedAnswer then the click event will not occur and a div called message will display the message "Sorry, but your answer is incorrect. Please try again."
The problem is, totalGuess in the if statement is never equal to condensedAnswer. I've tried seeing typeof and they are both strings. I've tried console.log(totalGuess+"\n"+condensedAnswer); and they both return the same value. I've tried hardcoding the condensedAnswer, and totalGuess was able to be equal to the hardcoded answer. But when I tried comparing condensedAnswer with the hardcoded answer, it's not equal, even though the console.log value for condensedAnswer is the same. I'm not what's wrong.
Here's the code snippet:
$('.submitGuess').click(function(e){
var totalGuess = "";
var condensedAnswer = answer.replace(new RegExp(" ","g"), "");
$('.crypto-input').each(function(){
totalGuess += $(this).val();
});
// if incorrect guess
if(totalGuess !== condensedAnswer) {
$('.message').text("Sorry, but your answer is incorrect. Please try again.");
e.preventDefault();
}
// if user wins, congratulate them and submit the form
else {
return true;
}
});
If it helps, here's the page, just a random test cryptogram plugin for Wordpress:
http://playfuldevotions.com/archives/140
The problem has nothing to do with the check. The problem is the fact your value you are checking against has hidden characters. However you are getting that string has the issue.
Simple debugging shows the problem
> escape(totalGuess)
"God%27sMasterpieceMatthew15%3A99Psalms129%3A158"
> escape(condensedAnswer)
"God%27sMasterpieceMatthew15%3A99Psalms129%3A158%00"
It has a null character at the end.
Now looking at how you fill in the answer you have an array with numbers
"071,111,100,039,...49,053,056,"
Look at the end we have a trailing comma
when you do a split that means the last index of your array is going to be "" and hence why you get a null.
Remove the trailing comma and it will magically work.

Determine if SelectBox containing no options exists using jQuery

So this question is asked a lot on the net and I see the answer is to check if the .length is > 0.
So in my case a select box may or may not exist. If it exists, it may have no options.
I have to code for the following:
If selectbox exists ...
if there are no select box options ...
disable a text area
I have therefore written the following:
$(document).ready(function () {
"use strict";
alert('running globals');
// Only process this block if the contactEmailAddress select box exists
if ($('contactEmailAddress').length > 0) {
alert('on the comm page');
// If there are no contacts ...
if ($('#contactEmailAddress option').size() === 0) {
alert('disabling the message box');
$('#message').attr("disabled", "disabled");
}
}
});
The problem is, because the select box has no options, it's decided the selectbox.length is 0. So this block never fires.
I need another way.
You're missing the "ID selector" from the first $, instead searching for elements named contactEmailAddress, rather than elements with an ID of contactEmailAddress.
if ($('#contactEmailAddress').length > 0) {
Note you can just do $('#contactEmailAddress option').size() directly without worrying if the select exists or not; no exception or error will be thrown.
You can determine an element exist with using pure javascript.
if( document.getElementById("contactEmailAdress") )
or
if( document.getElementsByClassName("option")[0] )

Show alert after all requirements have been met

I have a form where the user can 1.) check one option and be done. or 2.) check the other option and fill out a text field.
Whole thing is, after all is said and done I'd like for my alert to show, but it doesn't.
$('.know-your-role').show('fast', function() {
var $checkboxes = $('input:checkbox.checkchoice');
if($checkboxes.is(':checked')){
// show this after checked and the input has been filled.
alert('cool');
}else if($checkboxes.is(':checked') & $(".year").va() != "" ){
alert('cool');
}
});
How do I get the alert to show after all requirements (checkboxes and input) have been met?
I've made a fiddle here to show what I'm working with.
Thank you for your help in advance.
As well as the previous correct answers (missing & and misspelled val) there is a more fundamental logical issue here. You seem to have this structure:
if (conditionA) {
// behaviorA
} else if (conditionA && conditionB) {
// behaviorB
}
You will never reach behaviorB with such logic. If conditionA fails then conditionA && conditionB will certainly also fail.
Do you need to reverse the order of your if and else-if blocks?
Missing '&'
$checkboxes.is(':checked') && $(".year").val() != ""
You should use && instead of & for boolean comparisons, and also you appear to have mis-typed val as va.
I would suggest having two events, one on the 'Teacher' check box being checked and one on the year field being completed. Both events can trigger a single function that shows your alert and whatever other logic you want. So there is little duplication.
This helps to separate the events from the logic that shows/hides the year field and more easily allows you to perform different actions for the two events if that's a requirement.

Categories