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 Overflow
Discussions

javascript - How to set alert message while object is null - Stack Overflow
There is a following loop, traversing through images: When I type some items like sky, day, or a, or b it works but I want that when I type akjfhhsh or 23eewrr or something that is not in object th... More on stackoverflow.com
🌐 stackoverflow.com
javascript - Cannot alert after checking for null value - Stack Overflow
I am new to Javascript. I would like to redirect the user to page B when they load page A but there isnt any local storage ( page A needs to load info from local storage ) The code below checks if... More on stackoverflow.com
🌐 stackoverflow.com
Uncaught TypeError: Cannot read property dismiss of null (alert.js)
I keep getting random events where the error is: Uncaught TypeError: Cannot read property 'dismiss' of null The error is coming from the Alert default module on Line 113, in alert.js: hide_... More on github.com
🌐 github.com
12
March 31, 2018
`Alert.getInstance` returns `null`
I was under the impression that when including the classes for alerts on an element, an Alert was instantiated for handling JavaScript interactions. This does not seem to be the case. When using Al... More on github.com
🌐 github.com
5
April 15, 2021
🌐
JavaScript.info
javascript.info › tutorial › the javascript language › javascript fundamentals › logical operators
What's the result of OR?
JavaScript Fundamentals · Logical operators · back to the lesson · importance: 5 · What is the code below going to output? alert( null || 2 || undefined ); solution · The answer is 2, that’s the first truthy value. alert( null || 2 || ...
🌐
Null-js
null-js.com › components › alert
Null JS | Alert
<!-- Start null Alert--> <section class="null-alert-section"> <div class="null-alert-container null-position-relative null-border-radius null-alert-warning"><!--Add alert type here--> <div class="null-alert null-display-flex null-align-items-center"> <span class="null-alert-icon-container"> <!--Add icon here--> </span><!--End null-alert-icon-container--> <div class="null-alert-message-container"> <span class="null-alert-message">Null Alert Warning</span> </div><!--End null-alert-message-container--> <span class="null-alert-exit-icon null-cursor-pointer null-font-size-20">&times;</span> </div><!--null-alert--> </div><!--End null-alert-container--> </section><!--End null-alert-section--> <!-- End null Alert-->
🌐
Tutorial Republic
tutorialrepublic.com › faq › how-to-determine-if-variable-is-undefined-or-null-in-javascript.php
How to Determine If Variable is Undefined or NULL in JavaScript
<script> var firstName; var lastName = null; // Try to get non existing DOM element var comment = document.getElementById('comment'); console.log(firstName); // Print: undefined console.log(lastName); // Print: null console.log(comment); // Print: null console.log(typeof firstName); // Print: undefined console.log(typeof lastName); // Print: object console.log(typeof comment); // Print: object console.log(null == undefined) // Print: true console.log(null === undefined) // Print: false /* Since null == undefined is true, the following statements will catch both null and undefined */ if(firstNa
🌐
Stack Overflow
stackoverflow.com › questions › 66196653 › how-to-set-alert-message-while-object-is-null › 66196803
javascript - How to set alert message while object is null - Stack Overflow
images.forEach(image => { if (image !== null) { console.log(image); let div = document.createElement('div'); div.className = 'col-lg-3 col-md-4 col-xs-6 img-item mb-2'; div.innerHTML = ` <img class="img-fluid img-thumbnail" onclick=selectItem(event,"${image.webformatURL}") src="${image.webformatURL}" alt="${image.tags}">`; gallery.appendChild(div) } else { alert('Items not found'); } }) javascript ·
Find elsewhere
🌐
ESLint
eslint.org › docs › latest › rules › no-alert
no-alert - ESLint - Pluggable JavaScript Linter
/*eslint no-alert: "error"*/ customAlert("Something happened!"); customConfirm("Are you sure?"); customPrompt("Who are you?"); function foo() { const alert = myCustomLib.customAlert; alert(); }
🌐
MDN Web Docs
developer.mozilla.org › en-US › docs › Web › JavaScript › Reference › Operators › null
null - JavaScript - MDN Web Docs
Unlike undefined, JSON.stringify() can represent null faithfully. JavaScript is unique to have two nullish values: null and undefined. Semantically, their difference is very minor: undefined represents the absence of a value, while null represents the absence of an object.
🌐
Stack Overflow
stackoverflow.com › questions › 33979659 › cannot-alert-after-checking-for-null-value
javascript - Cannot alert after checking for null value - Stack Overflow
If there isnt any local storage and the person clicked page A,the desired outcome should be first alert something then redirects, but the following code only redirect instantly. Can anyone shows me the correct way of getting the desirable outcome? I can only use javascript but cannot use jquery. Thanks a lot! function loadpage(){ //runs when the browser first loaded var mov = JSON.parse(localStorage.getItem('one')); if (mov == null || mov == "") { alert('Please choose object') window.location = "object.html" }else{ getdetail(); gentable(); retrivedata(); document.getElementById("proceed").disabled = true; } }
🌐
JavaScript.info
javascript.info › tutorial › the javascript language › javascript fundamentals
Interaction: alert, prompt, confirm
It returns the text or, if Cancel button or Esc is clicked, null. confirm · shows a message and waits for the user to press “OK” or “Cancel”. It returns true for OK and false for Cancel/Esc.
🌐
Built In
builtin.com › software-engineering-perspectives › javascript-null-check
How to Check for Null in JavaScript | Built In
Summary: JavaScript offers several ways to check for null, including strict (===) and loose (==) equality, Object.is() and boolean coercion. Developers often use typeof and optional chaining (?.) to safely identify null, undefined or undeclared ...
🌐
TutorialsTeacher
tutorialsteacher.com › javascript › javascript-null-and-undefined
Difference between null and undefined in JavaScript
So now, <code>str</code> will be ... · Thus, undefined variables are the result of some code problems. You must explicitly assign a null to a variable....
Top answer
1 of 2
4

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.

2 of 2
0

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.

🌐
GitHub
github.com › MichMich › MagicMirror › issues › 1240
Uncaught TypeError: Cannot read property dismiss of null (alert.js) · Issue #1240 · MagicMirrorOrg/MagicMirror
March 31, 2018 - Uncaught TypeError: Cannot read property 'dismiss' of null · The error is coming from the Alert default module on Line 113, in alert.js: hide_alert: function(sender) { //Dismiss alert and remove from this.alerts this.alerts[sender.name].dismiss(); // <<========= LINE 113 !
Author: MagicMirrorOrg
🌐
GitHub
github.com › twbs › bootstrap › issues › 33651
`Alert.getInstance` returns `null` · Issue #33651 · twbs/bootstrap
April 15, 2021 - I was under the impression that when including the classes for alerts on an element, an Alert was instantiated for handling JavaScript interactions. This does not seem to be the case. When using Alert.getInstance(alertNode), null is returned. If ...
Author: twbs
Top answer
1 of 2
1

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

2 of 2
0

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

🌐
Reddit
reddit.com › r/javascript › basic js question: when to check for undefined, null, etc
r/javascript on Reddit: Basic JS question: when to check for undefined, null, etc
December 20, 2017 -

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.

Top answer
1 of 5
28

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.

  1. object.property !== undefined - Returns true if the property exists and is not undefined. Null values still pass.

  2. object.property != null - Return true if the property exists and is not undefined or null. Empty strings and 0's still pass.

  3. !!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 (!=).

2 of 5
16

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.

🌐
W3Schools
w3schools.com › howto › howto_js_validation_empty_input.asp
How To Add Validation For Empty Input Field with JavaScript
<form name="myForm" action="/a... value="Submit"> </form> If an input field (fname) is empty, this function alerts a message, and returns false, to prevent the form from being submitted:...