Reputation:
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.
Upvotes: 1
Views: 590
Reputation: 12106
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');
}
Upvotes: 0
Reputation: 21489
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="">
Upvotes: 0
Reputation: 21881
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
}
Upvotes: 1
Reputation: 629
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
}});
Upvotes: 0