Reputation: 445
I know this is a very basic JS question and I apologize. I am very new to this. I must be making a mistake somewhere. Here is what I am working with:
HTML Form
<div class='nameinput'>Please enter your name:</div>
<input id='name1' placeholder='Name...' type='text'>
<input type='submit' value='Connect' class="submitForm">
</div>
Javascript Code
function store() {
name = $("input#name1").val();
}
function init() {
$('.submitForm').on('click', function(){
if (name === '') {
alert("Please Enter Name");
}
else
store();
$(".login_page").animate({
'opacity': '0' });
I am not sure what I am missing here. The name = $("input#name1").val();
works fine but I can't seem to get the if to work right. Could someone kindly explain my issue here?
Upvotes: 1
Views: 60
Reputation: 2033
I am still new and learning JavaScript in many ways, so don't worry.
First, you should always try to debug the problem as much as possible. One easy way to do that is simply putting in test console.log()
statements printing out relevant values so you 1) know what is firing and when, and 2) what values they are working with. That'll get you out of a lot of problems like this.
Second, your if statement (if (name === '') {
) I believe is the problem. You should look at this and ask yourself why isn't it working? Is your logical comparison written wrong? are you comparing the right things? What values are you comparing?
Your problem is: where is name
defined? You use it in store()
, but it pops up for the first time in init
in that if
statement. It's not defined prior to that.
So the first time it fires, that can't be true, and it goes to the else
clause and then store()
fires.
In this case, you've lost track of scope; where your variables are being defined.
The easiest solution is to add another statement to extract the value of the input you are trying to check and making sure it's not null/empty. For that matter, I don't think you need store()
at all, unless you had some specific purpose for it.
Upvotes: 1
Reputation: 23859
The variable name
is undefined
in the scope. You need to get it when the button is clicked. Change your code to something like this:
function init() {
$('.submitForm').on('click', function() {
var name = $("#name1").val();
if (name === '') {
alert("Please Enter Name");
}
// rest of the code
}
Also, you don't need the function store
if you're using it only to initialize the variable name
. Additionally, the selector input#name1
can be simplified to #name1
as all elements in the page should have unique IDs.
Upvotes: 2