Reputation:
I have five variables in my JavaScript code. I want to combine all these variable into one single variable.
My five variables:
var description = $("#description").val();
var keywords = $("#keywords").val();
var author = $("#author").val();
var robots = $("#robots").val();
var revisit_after = $("#revisitafter").val();
I want all these variables to be combined into one variable, like this:
var all_fields = title,description,keywords,author,robots,revisit_after ;
If this worked, I could easily validate my input fields like this:
if(all_fields == "")
{
alert('Empty Field detected');
}
HTML:
<input type="text" class="text_boxes" placeholder="Title" id="title"><br>
<input type="text" class="text_boxes" placeholder="Description" id="description"><br>
<input type="text" class="text_boxes" placeholder="author" id="author"><br>
<input type="text" class="text_boxes" placeholder="Keywords" id="keywords"><br>
Is there any way to them into a single variable?
Upvotes: 0
Views: 252
Reputation: 44712
Instead of putting them all into an array manually, you can use jQuery to enumerate them all based on their field type and verify they are not empty:
function check() {
$("input[type='text']").not(".no-verify").each(function (i, element) {
if ($(this).val() == "") {
alert("Empty field detected!");
}
});
}
Advantages of this approach:
no-verify
.Upvotes: 2
Reputation: 10349
If you want to check that they all have a value, use &&
:
var all_fields = title && description && keywords && author && robots && revisit_after;
if(!all_fields)
{
alert('Empty Field detected');
}
This works because &&
checks that a value is "truthy" meaning it has some sort of value (read more on this, it's a bit complex). Therefore, if any of them are empty, it would make all_fields
false. A limitation would be if one of them were to have the value 0
, which is technically a value, but is not "truthy". However, I believe jquery's val()
always returns a string, and "0"
is truthy.
Upvotes: 1
Reputation: 5985
Not knowing if you're allowed to change this or not, I would personally write a new array at the end of whatever you're doing, something like this:
var arr = [];
var empty = false;
var description = $("#description").val();
var keywords = $("#keywords").val();
var author = $("#author").val();
var robots = $("#robots").val();
var revisit_after = $("#revisitafter").val();
arr.push(description, keywords, author, robots, revisit_after);
Then check your array
arr.each(function(i){
if(arr[i] == ""){
empty = true;
}
});
if(empty) console.log("Something is missing");
or if you like your code faster, use a for loop:
for(var i = 0; i <= arry.length; i++){
if(arr[i] == ""){
empty = true;
}
}
if(empty) console.log("Something is missing");
Upvotes: 2
Reputation: 12552
Try an object literal.
var all_fields = {
"title": title,
"description": description,
"yada" : yada
}
Upvotes: 0