I'm trying to create a Welcome page for new and former users using cookies in jquery. However, when I submit the form using new data for each user it doesn't say "Welcome New User". It always welcome the user as if he's already a submit a form on the site.
<h1 class="center">
<span id="wel"></span>
</h1>
<form id="form" autocomplete="on">
<br>
<input type="text" name="firstname" id="firstname" placeholder="Enter the first name" pattern="[A-Za-z\-]+" maxlength="25">
<br>Last Name:
<br>
<input type="text" name="lastname" id="lastname" placeholder="Enter the last name" pattern="[A-Za-z\-]+" maxlength="25">
<input type="submit" id="submit" value="Place Order!" />
</form>
var customername = []; // outside the function
var fname = $("#firstname").val();
var lname = $("#lastname").val();
customername = $.cookie('fullname', fname + " " + lname, {expires: 365});
if(customername == null) {
$("#wel").html("Welcome New Customer");
} else {
$("#wel").html("Welcome " + $.cookie("fullname"));
}
The problem is that the cookie will always get created, passing through empty values, because you are creating the cookie directly before checking that it exists:
customername = $.cookie('fullname', fname + " " + lname, {expires: 365});
if(customername == null) {}
In the above code, customername
will never havea value of null
. To get around this, what you need to do is define the customername
variable outside of the function, but not assign anything to it (not even a 'null'):
var customername;
if(customername == null) {
$("#wel").html("Welcome New Customer");
} else {
$("#wel").html("Welcome " + $.cookie("fullname"));
}
Then wrap the cookie creation inside of the form submission:
$("form").submit(function(){
var fname = $("#firstname").val();
var lname = $("#lastname").val();
customername = $.cookie('fullname', fname + " " + lname, {expires: 365});
});
This way, when the user visits the site, the cookie won't automatically get created; it will only get created on form submission.
Hope this helps! :)