1
let a = $('#plustitle').val().trim();  // input type text
let b = $('#plustags').val().trim(); // input type text
let c = $('#plustory').val().trim(); // textarea

I need to check if any of the above variable is empty, i.e. have value "";

Using jquery each loop - there is a lot of code.

Is there a way to do it in a shorter way.

2
  • Sorry, you've made me insecure about my logic but it was correct^^ !a || !b is the same as !(a && b) and therefore if(!(a && b && c)) Commented Dec 1, 2018 at 18:15
  • @Andreas, I see, pls place the answer, I think there is no shorter way Commented Dec 1, 2018 at 18:19

4 Answers 4

1

If we use the fact that an empty string will be falsy we could achieve your requirement with

if (!(a && b && c)) {
  // one of them is empty
} 
Sign up to request clarification or add additional context in comments.

Comments

0

considering "let" is being used, I assume you have ES6 support. You can use below code after pushing these values to an array:

   let a = $('#plustitle').val().trim();  // input type text
   let b = $('#plustags').val().trim(); // input type text
   let c = $('#plustory').val().trim(); // textarea 
   let someValues = [a, b, c]; // if separate variables are not required, directly push to array   
   someValues.forEach(x =>{ if(!x) {
       //do operation when empty
   }});

2 Comments

if ([a, b, c].some(x => !x)) {...}
OP doesn't want to use loop as mentioned
0

Join all variables and check length of result

let a = $('#plustitle').val().trim();
let b = $('#plustags').val().trim();
let c = $('#plustory').val().trim(); 

if ((a+b+c).length == 0)
  console.log("empty");
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="text" id="plustitle" value="">
<input type="text" id="plustags" value="">
<input type="text" id="plustory" value="">

Also you can simplify your code and use one selector

var values = $('#plustitle, #plustags, #plustory').map(
  (i, ele) => ele.value.trim()
).toArray().join('');

if (values.length == 0)
  console.log("empty");

var values = $('#plustitle, #plustags, #plustory').map(
  (i, ele) => ele.value.trim()
).toArray().join('');

if (values.length == 0)
  console.log("empty");
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="text" id="plustitle" value="">
<input type="text" id="plustags" value="">
<input type="text" id="plustory" value="">

1 Comment

"Also you can simplify your code" - Only if puerto doesn't need the values. Otherwise you would have to get them twice from the DOM
0

You could abstract it the following way:

function isEmpty(id) {
  return ($('#' + id).val().trim() == '');
}

if(!isEmpty('plusTitle') && !isEmpty('plustags') && !isEmpty('plustory')) {
  console.log('none is empty');
}

1 Comment

Not using comparison operator

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.