You should prevent default action of submit button which is to submit the form.
Use Event.preventDefault();
function validateform() {
var email = $('#txt_emailID').val();
if (email == null || email == "") {
alert("Email Should Be Complusory");
return false;
}
var atposition = email.indexOf("@");
var dotposition = email.lastIndexOf(".");
if (atposition < 1 || dotposition < atposition + 2 || dotposition + 2 >= email.length) {
alert("Please enter a valid e-mail address...!!!");
return false;
}
}
$(function() {
$(document).on("click", "#submit_mail", function(e) {
if (validateform() == false) {
e.preventDefault();
document.getElementById("txt_name").value = $('#txt_name').val();
document.getElementById("txt_subject").value = $('#txt_subject').val();
}
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<label for="fname">Name</label>
<input type="text" id="txt_name" name="txt_name" placeholder="Your Name.." />
<label for="lname">EmailID</label>
<input type="text" id="txt_emailID" name="email" placeholder="Your EmailID.." />
<label for="lname">Subject</label>
<input type="text" id="txt_subject" name="txt_subject" placeholder="Your Subject.." />
<input type="submit" id="submit_mail" value="Send" />
Run code snippetEdit code snippet Hide Results Copy to answer Expand
Answer from Rayon on Stack OverflowYou defined the name attribute on your input field and not the id.
So either change the attribute in the input field to this:
<input type="text" id="webAdress" />
Or adjust your JavaScript to this (MDN docu):
function myFunction() {
var webAdress = document.getElementsByName('webAdress')[0];
alert(webAdress);
}
getElementById is use id, but webAdress is name attribute.
javascript - How to set alert message while object is null - Stack Overflow
Uncaught TypeError: Cannot read property dismiss of null (alert.js)
javascript - Cannot alert after checking for null value - Stack Overflow
`Alert.getInstance` returns `null`
I don't know where the exact issue in your page is but I believe you've encountered the Joys of IE and the onbeforeunload event.
In Internet Explorer it treats all navigation link clicks as to be "leaving" the page and thus if you have an onbeforeunload event defined you will get the confirmation message (presuming your code, or the CodeIgnitor framework has attached a handler)
The problem is that a link like this:
<a href="javascript:doSomething();">Do something on this page without leaving</a>
will trigger IE to believe the user is leaving the page.
The way I got around this was to do the following (ugly but it worked).
In my small page (a popup window) on the 4-5 links that were "internal" to the page I added a CSS class: class="internal" then in my onbeforeunload event I would check to see if the source element that triggered the event had the class set... and if so "ignore" throwing up my "Are you sure you want to leave?" type warning...
However on a "main" page with litterally 100's and 100's of links this would be very ugly to try and implement. - Best of luck.
Answer from Scunliffe helped me fixing this issue in the following way -
Added the below line at end of all my JavaScript code.
window.onbeforeunload = function(){}
You can try this in the console section of IE Developer Tools if want to have a quick test.
Again I am not sure how this will impact things in your code. So do test all your code properly if anything is broken. The code that will break might be related to any listeners that are attached to page unload or onbeforeunload events. In my case there weren't any :)
Hope it helps.
So I'm usually more of a server side developer, but lately I've been working with more of the client code at work. I understand what undefined and null are in JavaScript, but I find myself always checking for both of them. In fact, when checking if a String property exists, I end up writing this:
if(value !== undefined && value !== null && value !== '')
I figure there is a better way than this, and it's probably because I'm not 100% clear of when to check for what. So if someone could help fill me in here on the rules of when to check for undefined vs null, that would be great.
TL;DR: Use value != null. It checks for both null and undefined in one step.
In my mind, there are different levels of checking whether something exists:
0) 'property' in object - Returns true if the property exists at all, even if it's undefined or null.
-
object.property !== undefined- Returns true if the property exists and is not undefined. Null values still pass. -
object.property != null- Return true if the property exists and is not undefined or null. Empty strings and 0's still pass. -
!!object.property- Returns true if the property exists and is "truthy", so even 0 and empty strings are considered false.
From my experience, level 2 is usually the sweet spot. Oftentimes, things like empty strings or 0 will be valid values, so level 3 is too strict. On the other hand, levels 0 and 1 are usually too loose (you don't want nulls or undefineds in your program). Notice that level 1 uses strict equality (!==), while level 2 uses loose equality (!=).
I would just say
if (value) {
// do stuff
}
because
'' || false
// false
null || false
// false
undefined || false
//false
Edit:
Based on this statement
I end up writing this: if(value !== undefined && value !== null && value !== '')
I initially assumed that what OP was really looking for was a better way to ask "is there a value?", but...
if someone could help fill me in here on the rules of when to check for undefined vs null, that would be great.
If you're looking to see if something is "truthy":
if (foo.bar) {
alert(foo.bar)
}
This won't alert if value is '', 0, false, null, or undefined
If you want to make sure something is a String so you can use string methods:
if (typeof foo.bar === 'string') {
alert(foo.bar.charAt(0))
}
This won't alert unless value is of type 'string'.
So.. "when to check for undefined vs null"? I would just say, whenever you know that you specifically need to check for them. If you know that you want to do something different when a value is null vs when a value is undefined, then you can check for the difference. But if you're just looking for "truthy" then you don't need to.
All values obtained from form elements are strings. Even if the element is empty, the value is still "", not null so checking for null isn't the right approach.
Instead test for the absence of any "truthy" value as seen below.
// variables object
const el = {
form: document.querySelector(".form"),
input: document.querySelector(".user-input"),
list: document.querySelector(".list"),
date: document.querySelector(".date"),
time: document.querySelector(".time")
};
//local storage key
const storage_key = "tasks-storage-key";
//Create ID
const createId = () => `${Math.floor(Math.random() * 10000)}-${new Date().getTime()}`;
//variable of empty array that gets new task
let taskList = [];
// function that renders task list
//function that creates new tasks with date and time
const creatTask = (task) => {
const id = createId();
const taskNew = el.input.value;
const taskDate = el.date.value;
const taskTime = el.time.value;
const tasks = document.createElement("div");
tasks.innerHTML = `
<div class="task-content">
<div class="list-of-task">
<div class="task" data-id="${id}">
<input type="checkbox" class="tick">
<div class="new-task-created">${taskNew}</div>
<label class="due-date">${taskDate}</label>
<label class="due-time">${taskTime}</label>
</div>
<div class="atcion-buttons">
<button class="edit" data-id="">Edit</button>
<button class="delete" data-id="">Delete</button>
</div>
</div>`;
taskList.push(tasks);
console.log(taskList);
el.list.appendChild(tasks);
return task
};
//event listner that listens for add button.
function addTask(taskNew, taskDate, taskTime) {
if (!taskNew) {
alert("Please add a new Task")
}
if (!taskDate) {
alert("Please add a new Task with a due date");
}
if (!taskTime) {
alert("Please add a new Task with a due time");
}
creatTask();
}
<div class="form">
<input class="user-input" type="text">
<input class="date" type="date">
<input class="time" type="time">
<button onclick="addTask()" class="add" id="add">+</button>
</div>
<div class="list"></div>
Run code snippetEdit code snippet Hide Results Copy to answer Expand
Thanks for the help.
I also found another way of doing it as well after doing further research.
// variables object
const el = {
form: document.querySelector(".form"),
input: document.querySelector(".user-input"),
list: document.querySelector(".list"),
date: document.querySelector(".date"),
time: document.querySelector(".time")
};
//local storage key
const storage_key = "tasks-storage-key";
//Create ID
const createId = () => `${Math.floor(Math.random() * 10000)}-${new Date().getTime()}`;
//variable of empty array that gets new task
let taskList = [];
// function that renders task list
//function that creates new tasks with date and time
const creatTask = (task) => {
const id = createId();
const taskNew = el.input.value;
const taskDate = el.date.value;
const taskTime = el.time.value;
if (taskNew.length == 0) {
alert("Please add a new Task");
}
if (taskDate.length == 0) {
alert("Please add a new Task with a due date");
}
if (taskTime.length == 0) {
alert("Please add a new Task with a due time");
}
const tasks = document.createElement("div");
tasks.innerHTML = `
<div class="task-content">
<div class="list-of-task">
<div class="task" data-id="${id}">
<input type="checkbox" class="tick">
<div class="new-task-created">${taskNew}</div>
<label class="due-date">${taskDate}</label>
<label class="due-time">${taskTime}</label>
</div>
<div class="atcion-buttons">
<button class="edit" data-id="">Edit</button>
<button class="delete" data-id="">Delete</button>
</div>
</div>`;
taskList.push(tasks);
console.log(taskList);
el.list.appendChild(tasks);
return task
};
//event listner that listens for add button.
function addTask() {
creatTask();
}
<div class="form">
<input class="user-input" type="text">
<input class="date" type="date">
<input class="time" type="time">
<button onclick="addTask()" class="add" id="add">+</button>
</div>
<div class="list"></div>
Run code snippetEdit code snippet Hide Results Copy to answer Expand