Checking textbox if it's empty in Javascript - javascript

I wrote a simple html file with a textbox and submit button, and it generates and document.write's a response dependant on what you submit. I want to have it generate a response saying to enter content if the box is empty. The textbox's id is chatinput, so I have the following the code in the beginning
var chatinput_box=document.getElementById('chatinput');
var chatinput=chatinput_box.value;
Then a have a conditional, although I can't get it to work correctly; I've tried
if(chatinput==""){}
if(chatinput.length=0){}
if(chatinput=null){}
and others but none have worked correctly. Does anyone have another idea?

It should be this:
var chatinput = document.getElementById("chatinput").value;
if (chatinput == "" || chatinput.length == 0 || chatinput == null)
{
// Invalid... Box is empty
}
Or shorthanded:
if (!document.getElementById("chatinput").value)
{
// Invalid... Box is empty
}
The = assigns a value whereas == checks whether the values are equal.

Just offering an alternative, not trying to steal thunder ...
Create an isEmpty function to reuse on a variety of items.
function isEmpty(val){
return ((val !== '') && (val !== undefined) && (val.length > 0) && (val !== null));
}
Then you can apply it to whatever element you want:
if(!isEmpty(chatinput)){
// hooray its got a value!
}
Not exactly original, its the concept stolen from PHP, but it comes in handy a lot.

Related

Efficient way to calculate if the fields are populated using the if condition in javascript when the field list is very large

I have a form which has lot of fields consider maybe 100. All of the fields are different such as it could be StartTime DateTime EndTime Value etc.. User can fill whichever the field they want and keep the remaining fields black.
Now on the Javascript or Node.js side I need to check if the fields are populated for each of them then based on that I need to create an XML file. As of now, I am trying to check if each field is populated using the if the condition. If I proceed in this method then I need to write 100 IF condition to manage all 100 fields which are time-consuming and redundant.
I was just curious if there is any better way of doing it. I tried searching but could not find any relevant post which gives me some sort of idea. If it's duplicate then I am really sorry.
Does anyone have a better idea?
As of now, I am checking something like this:
if(StartTime != '' && StartTime != null && StartTime != undefined)
{
append(StartTime)
}
if(DateTime != '' && DateTime != null && DateTime != undefine)
{
append(DateTime)
}
if(EndTime != '' && EndTime != null && EndTime != undefine)
{
append(EndTime)
}
if(Value != '' && Value != null && Value != undefine)
{
append(Value)
}
.
.
.
.
You could do something like this
const appendIf = () => {
if(val != '' && val != null && val != undefine) {
append(val);
}
};
appendIf(StartTime);
appendIf(DateTime);
appendIf(EndTime);
appendIf(Value);
If all the values are in an array or object, you could also just loop over that:
for(/* whatever for loop is needed*/) {
appendIf(currentValue);
}
I would suggest using a data structure where you can save the data you want to check on, and also if you're checking the same condition for every field then implement the logic in a function. Assuming you're using an array as the data structure the code would look like this:
const appendField = (field) => {
if (field != '' && field != null && field != undefined)
//here you can do something in this case append(field)
}
// myArr is the array where you have the data you want to check
myArr.forEach(field => appendField(field))
Looping over the keys in the object and checking the value for each unique key could be a good way to go. If you need to maintain the order of the keys, the forEach method allows you to pass in an index as well. i in the example.
const appendValues = (data) => {
const keys = Object.keys(data);
keys.forEach((key, i) => {
if (data[key]) {
// Append logic if value
append(data[key]);
} else {
// Logic if no value
}
})
};

Javascript - Waiting for user input (callbacks)

I've been looking at other questions trying to get my head around callbacks but I just can't make sense of it enough to use in my context. I'm writing a text based game which uses purely text input. When needed, I want the game to ask a question with a varying amount of answers and then wait until a valid response is given. Below is an example that doesn't work but explains what I'm trying to do. Can anyone provide me with any guidance? Thanks.
//main code
pEQUIP = ["foo", "foo", "foo"];
exItem = "ball";
function prompt(numPrompts, callback) {
//waits until user types a number <= numPrompts and presses enter, then returns the valid result entered
}
$('#gametext').append("<p>" + "What slot would you like to use to hold this item?" + "</p>");
//where a function would be stopping the code until a valid answer is given
if (prompt == "1") {
pEQUIP[0] = exItem;
} else if (prompt == "2") {
pEQUIP[1] = exItem;
} else if (prompt == "3") {
pEQUIP[2] = exItem;
}
//Just a quick n dirty way of testing it worked below:
$('#gametext').append("<p>" + pEQUIP[0] + pEQUIP[1] + pEQUIP[2] + "</p>");
//parses user info unsure if this could be used or would have to be copied
$(document).ready(function() {
$(document).keypress(function(key) {
if (key.which === 13 && $('#userinput').is(':focus')) {
var value = $('#userinput').val().toLowerCase();
$('#userinput').val("");
//playerInput(value); Is usually here, would lead to
//a switch which parses commands typed by the user.
//Unsure if it can be used for this problem as pausing
//the code I think would stop the switch?
}
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<body>
<div id="gametext"></div>
<input id="userinput">
</body>
It appears as though you're thinking of functions incorrectly.
Functions are:
A series of steps that may return data when they're invoked. You
invoke a function by passing arguments to the function name, even if
the arguments are nothing () - a.e. alert(string) or myFunction()
Not comparable to anything but themselves. In your code you have prompt == "1" this isn't going to work. prompt is a function name and it isn't invoked so you are literally comparing the function itself to the string "1".
Able to return data when invoked. That data can be compared.
Note: Also, very importantly, prompt is the name of a default function(like alert or console) and you shouldn't overwrite it. It isn't considered a reserved keyword by the language but altering it will cause havok if any other library you're using, or any other programmer doesn't know it's been overwritten, and tries to invoke it.
prompt("this is a normal prompt");
Furthermore you have the document setup to check the value of the text box itself on keypress. You should probably change this to an event listener on the text box, but there isn't any reason to continuously loop a function beyond this while waiting for the box to match some predefined input.
The Flow is this:
type in the box
hit enter
check value
if value is 1 or 2 or 3 or any other acceptable answer do something
If that's all you need currently then you do not need to work so hard for the functionality when a single event listener could do the trick:
$("#input_box").on("keypress", function(e) {
if(e.keyCode === 13) {
let value = $("#input_box").val();
if(value === "1" || value === "2" || value === "3") {
//do whatever
}
}
});
$("#input_box").on("keypress", function(e) {
if(e.keyCode === 13) {
let value = $("#input_box").val();
if(value === "1" || value === "2" || value === "3") {
console.log("accepted");
}
$("#input_box").val("");
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" id="input_box">

transfer date into input field from one asp form into another using session state

I need to transfer date from one asp form to another based on some checks.
In the source page I do the check and send as following:
if (txtFinalized.Text == "" && rblPhysicalrecords.SelectedValue=="1" && ddlResponsibility.SelectedIndex == 5)
{
//String s = Request.QueryString["finlalisationDate"] = txtFinalized.Text;
Session["finlalisationDate"] = txtFinalized.Text;
}
Then I try to read the value in the target form but so far I can't get the resut inserted into the input field as I need.
txtFinalised.Text = (string)(Session["finlalisationDate"]);
Do I need to write a method in javascript to fetch the result and insert it to the field and if yes how do I do that?
Your condition block has a flaw, it says txtFinalized must be empty to set a value to your session variable.
For learning and and understand session you could write your code like this...
//remove txtFinalized from condition
if (rblPhysicalrecords.SelectedValue=="1" && ddlResponsibility.SelectedIndex == 5)
{
//check if textFinalized NOT is null or empty
if (!String.IsNullOrEmpty)
{
Session["finlalisationDate"] = txtFinalized.Text;
}
//if textFinalized is empty set session to a value just to see some text
else
{
Session["finlalisationDate"] = "n/a";
}
}
Now when you load your second form you will always see something in your textFinalized textbox and from what you see you know if the user made some input in the first form.
You can modify your condition block like below
if (!String.IsNullOrEmpty(txtFinalized.Text) && rblPhysicalrecords.SelectedValue=="1" && ddlResponsibility.SelectedIndex == 5)
{
//String s = Request.QueryString["finlalisationDate"] = txtFinalized.Text;
Session["finlalisationDate"] = txtFinalized.Text;
}

checking values before submitting form

Before I submit a form I want to check the values in the input.
Here I'm checking if a value is NOt equal to .5 or 1. or not a empty string.
form.onsubmit = function(e) {
var ftimes = document.getElementsByClassName("add_timebox");
var fflag = 0;
for(i=0;i< ftimes.length;i++) {
var value1 = ftimes[i].value;
console.log(value1);
if ( value1 !==.5 ||value1 !== 1 || (!IsStringEmpty(value1)) ){
fflag = 1;
console.log('inside');
}
}
if(fflag==1) {
alert('enter again' );
return false;
}
I have made many changes to the IF statement to try to get it correct.
But it is still going in the loop even when I know if shouldn't.
For example when i submit the form and i have one input value equal .22
then it should only give me 1 'inside' but in keeps repeating:
inside
.22
(empty string)
inside
....
You do not show how you are implementing your IsStringEmpty method, but if you are using something like this, then any number is also a non-empty string, so your if statement will always run.
function IsStringEmpty(str) {
return (!str || 0 === str.length);
}
So you need to change your ORs with ANDs, or it will never check the number conditions.
You can check if the value is not an empty string and is different from 0.5 and 1. Then your condition should be like this.
if (!IsStringEmpty(value1) && value1 !== 0.5 && value1 !== 1)
But, you are getting the value from a form, so it will be a string. Therefore, you are comparing strings and you need this.
if (!IsStringEmpty(value1) && value1 !== ".5" && value1 !== "1")
Although you will probably want to compare floats, in which case you need this.
if (!IsStringEmpty(value1) && parseFloat(value1) !== .5 && parseFloat(value1) !== 1))
So basically, when you enter 1, .5 or and empty string in all of the form fields, you skip the inside block. But if you have any other value in any of the fields, then the flag will be set to 1. If that is not what you meant, please update your question to be more specific.
Please check Plunker here.
Hope this helps.
you have to add a break; statment in your if condition once the if condition is satisfied.
if ( value1 !==.5 ||value1 !== 1 || (!IsStringEmpty(value1)) ){
fflag = 1;
console.log('inside');
break;
}

Checking if input value is not empty or default

I'm look for an elegant way to check if input value is not empty and not default.
For example let's say we have input with value Username, this is a default value, and once the user clicks on this input field Username would be deleted so user could enter what he wants. Just to make it clear this is how it would look when the page is loaded:
<input type="text" class="defaultValue" value="Username" />
Now by default this field would never be empty, unless user would do something to make it empty, so just to make sure i need to check for both things. The way i would do this is very simple:
if($(".defaultValue").val().length == 0 || $(".defaultValue").val() == "Username")
alert("Please enter your username");
So this works, but looks ugly as hell. And usually i need to deal with huge forms so my code gets really ugly and hard to manage because of this, any way to improve this?
Thanks.
Try:
if (this.value == '' || this.value == this.defaultValue) {
// value is empty or is default value
}
Try writing a helper function to do this check for you.
var isEmptyOrDefault = function(field, default) {
var value = $(field).val();
return (value.length === 0 || value === default);
};
So you can use it:
if (isEmptyOrDefault($('.defaultValue'), 'Username')) {
alert("Please enter your username");
}

Categories

Resources