Warning displayed on form input still allows submission

How can I prevent users from inserting certain words in a form on my website? Even though my code detects these words and displays a popup message, the form still submits the data once the user acknowledges the message. The strange behavior has me puzzled. Below is the code snippet:

HTML Form

<form name="form1" action="#" method="post" required>
    <label>Line 1:&nbsp; </label>
    <input type="text" name="firstline" required onClick="select_area()"><br/>
    <label>Line 2:&nbsp; </label>
    <input type="text" name="secondline" required onClick="select_area2()"><br/>
    <label>Line 3:&nbsp; </label>
    <input type="text" name="thirdline" required onClick="select_area3()"><br/>
    <input type="submit" name="submit_btn" id="submit" value="Submit" onClick="validate_text();">
    <input type="reset" id="reset" value="Reset">
</form>

JavaScript File

var swear_words_arr=new Array("word1","word2","word3");

var swear_alert_arr=new Array;
var swear_alert_count=0;
function reset_alert_count()
{
    swear_alert_count=0;
}
function validate_text()
{
    reset_alert_count();
    var compare_text=document.form1.firstline.value;
    for(var i=0; i<swear_words_arr.length; i++) {
        for(var j=0; j<(compare_text.length); j++) {
            if(swear_words_arr[i]==compare_text.substring(j,(j+swear_words_arr[i].length)).toLowerCase())
            {
                swear_alert_arr[swear_alert_count]=compare_text.substring(j,(j+swear_words_arr[i].length));
                swear_alert_count++;
            }
        }
    }
    
    var compare_text=document.form1.secondline.value;
    for(var i=0; i<swear_words_arr.length; i++) {
        for(var j=0; j<(compare_text.length); j++) {
            if(swear_words_arr[i]==compare_text.substring(j,(j+swear_words_arr[i].length)).toLowerCase())
            {
                swear_alert_arr[swear_alert_count]=compare_text.substring(j,(j+swear_words_arr[i].length));
                swear_alert_count++;
            }
        }
    }   
    
    var compare_text=document.form1.thirdline.value;
    for(var i=0; i<swear_words_arr.length; i++) {
        for(var j=0; j<(compare_text.length); j++) {
            if(swear_words_arr[i]==compare_text.substring(j,(j+swear_words_arr[i].length)).toLowerCase())
            {
                swear_alert_arr[swear_alert_count]=compare_text.substring(j,(j+swear_words_arr[i].length));
                swear_alert_count++;
            }
        }
    }
    
    var alert_text="";
    for(var k=1; k<=swear_alert_count; k++){
        alert_text+="\n" + "(" + k + ")  " + swear_alert_arr[k-1];
    }
    if(swear_alert_count>0) {
        alert("The message will not be sent!!!\nThe following illegal words were found:\n_______________________________\n" + alert_text + "\n_______________________________");
        document.form1.text.select();
    } else {
        document.form1.submit();
    }
}

function select_area()
{
    document.form1.firstline.select();
}
    
function select_area2()
{
    document.form1.secondline.select();
}
    
function select_area3()
{
    document.form1.thirdline.select();
}
    
window.onload=reset_alert_count;

Answer №1

Your function does not interfere with the form's action.

It doesn't include statements like 'return false' or 'preventdefault'.

Using onClick is possible, but it's recommended to use onsubmit for better keyboard submission functionality.

var swear_words_arr = new Array("word1", "word2", "word3");

var swear_alert_arr = new Array;
var swear_alert_count = 0;

function reset_alert_count() {
    swear_alert_count = 0;
}

function validate_text() {
    // Function code here
}

function select_area() {
    document.form1.firstline.select();
}

function select_area2() {
    document.form1.secondline.select();
}

function select_area3() {
    document.form1.thirdline.select();
}

window.onload = reset_alert_count;
<form name="form1" action="#" method="post" onsubmit="return validate_text();">
    <label>Line 1:&nbsp; </label>
    <input type="text" name="firstline" required onClick="select_area()"><br />
    <label>Line 2:&nbsp; </label>
    <input type="text" name="secondline" required onClick="select_area2()"><br />
    <label>Line 3:&nbsp; </label>
    <input type="text" name="thirdline" required onClick="select_area3()"><br />
    <input type="submit" name="submit_btn" id="submit" value="Submit">
    <input type="reset" id="reset" value="Reset">
</form>

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

How should one properly close off list items?

When I attempted to check the validity of my code on W3 validator, it highlighted errors referencing - No li element in scope but a li end tag seen. This pertains to a bootstrap dropdown menu that I came across in some examples provided by Bootstrap. Coul ...

What is a more effective way to showcase tab content than using an iframe?

I currently have a webpage set up with three tabs and an iframe that displays the content of the tab clicked. The source code for each tab's content is stored in separate HTML and CSS files. However, I've noticed that when a tab is clicked, the ...

Contemplating the Sequence of DOM Execution

In the world of html/javascript, the order of execution is typically serial, meaning that the browser reads the code line by line and interprets it accordingly. This is a common practice in most programming languages. Some javascript programmers prefer to ...

Dealing with lag problems while feeding a massive dataset into the Autocomplete component of Material-UI

In my React project, I have integrated the Autocomplete component from Material-UI to enhance user experience. However, when attempting to pass a large dataset of 10,000 items to the Autocomplete component as a prop, there is a noticeable delay of approxim ...

Is there a text form in Angular that allows only numerical input?

Here's an input form in Angular that I'm working on: <input ng-model="sc.zip" class="form-control" maxlength="5" type="text" /> I want to keep the form as a simple empty textbox without limiting it to only numbers. However, I do want to r ...

Verify the changing text within a Span tag with the use of Selenium in Java

Can anyone assist me in creating a logic to verify a dynamic text? The text within the tag below is constantly changing (to 6 distinct words), and I need to validate if those 6 unique words match the expected text. Is there a method to do this verification ...

What is the correct way to invoke a function contained within an object that is stored in an array?

I've encountered a problem with my program. I'm attempting to invoke a function that is part of an object stored in an array, but I'm having difficulty calling the function correctly. //Initialize Array for Storing Projects let allProjects ...

Tips for transferring data to the next page with JavaScript AJAX

I am working on a webpage that includes an html select element <pre> $query = mysql_query("select * from results"); echo "<select id='date' onchange='showdata()' class='form-control'>"; while ($arr = mysql_fetch_a ...

Issue with displaying entire object using Jest and console.dir

I'm having trouble displaying an error in my Jest test because it's not showing all the levels as expected. import util from 'util' describe('Module', () => { it('should display all levels WITHOUT util', () =& ...

AngularJS: The `$locationChangeStart` event

I am attempting to check the next token in the next, but I am encountering an error: TypeError: next.localStorage is not a function APP.JS .run(function ($rootScope, $location,$log,User) { $rootScope.$on("$locationChangeStart", function (event,nex ...

Using AngularJS to automatically fill in HTML select fields

Encountering an issue with an HTML select element in AngularJS. The API response returns one of the values as an integer, however, setting the "value" attribute for autofill is proving to be a challenge. Below is a screenshot showcasing the data received ...

Function executed many times during click action

I have developed a web application that allows users to input any keyword or statement and receive twenty results from Wikipedia using the Wikipedia API. The AJAX functionality is working perfectly. The app should dynamically create a DIV to display each r ...

What is the default DTD used if it is not specified in the doctype declaration?

On my webpage, the doctype is specified as: <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> No DTD is explicitly set. I'm curious which DTD will be defaulted in IE? It seems that it doesn't function the same way as "http ...

CSS Element Overlapping Issue in Safari Browser

I am currently developing an audio player for my application that includes a pause/play button, next button, and back button. I have encountered a problem specifically on Safari where the back/pause buttons are overlapping each other. The play/pause button ...

"Effortless alignment: Centralizing CSS styling across the entire

I need help placing a loading spinner in the center of my screen, ensuring it works on both mobile and desktop devices. Here is my current CSS code: .spinner { width: 100px; height: 100px; position:absolute; top: 50%; left: 50%; margin: 100px ...

Ways to alter the div post user authentication

I'm in the process of developing a website with a single-page application setup. I'm utilizing Node.js for the backend and Angular for the frontend. The challenge I'm facing is displaying a specific div when a user is not logged in, and swit ...

What could be causing the AJAX GET request to only successfully retrieve data for the initial item in the foreach loop?

My challenge involves populating a 'transaction model' form with previously entered data when a user wishes to 'edit' the transaction. The transactions are passed into the View as an IEnumerable<Transaction>. Each transaction is d ...

how to include a file within another file using PHP

Is there a method in PHP to incorporate or run code from another file? Imagine we have 2 files: a.php which includes: <?php echo "i'm a.php"; ?> and b.php which includes: <?php echo "i'm b.php"; // some code here that will "include ...

Combining the power of Node.js and Node-MySQL with Express 4 and the versatile Mustache

Currently, I am delving into the world of Node.js and encountering a bit of a roadblock. My focus is on passing a query to Mustache. Index.js // Incorporate Express Framework var express = require('express'); // Integrate Mustache Template En ...

What could be causing my Vue code to behave differently than anticipated?

There are a pair of components within the div. When both components are rendered together, clicking the button switches properly. However, when only one component is rendered, the switch behaves abnormally. Below is the code snippet: Base.vue <templa ...