Stop automatic form submissions from the enter key

My live chat messaging system is experiencing an issue where the page refreshes every time a user presses the enter button. I attempted to use prevent default code, but it did not work for me. I'm new to website programming, so if there are any problems in the code below, please let me know.

jQuery(document).ready(function() {
    jQuery('.btn-success').click(function() {
        var form_name  = jQuery(this).attr('title');
        var obj = jQuery(this);
        jQuery(".ajax_indi").show();
        switch (form_name) {
            case "npost":
            var message = jQuery("#message").val();
            break;
            default:
            alert("something went wrong!");
        }
        if((jQuery(message) == ''))
        {
           alert("Message Cannot be Empty");
           jQuery(".ajax_indi").hide();
           return false;
        } else {
        jQuery(this).attr("disabled", "disabled");
        jQuery(this).prop('value', 'Loading...');
        jQuery(this).css('cursor', 'default');
        }
        var str = jQuery("#"+form_name).serialize();
        jQuery.ajax({
            type: "POST",
            url: "chat.php",
            data: str,
            cache: false,
            success: function(html){
                jQuery('#chat1').append(html);
                obj.attr("disabled", false);
                obj.prop('value', 'Post');
                obj.css('cursor', 'pointer');
                jQuery(".ajax_indi").hide();
                document.getElementById(form_name).reset();
            }
        });
    }); 
});

Edited part

<form id="npost"  name="npost">
    <input class="form-control" placeholder="Type your message here..." 
    type="text" name="message">
    <input type="hidden" name="id" value="1">
    <span class="input-group-btn">
        <button type="button" class="btn btn-success" title="npost" >Send</button>

Answer №1

To avoid submitting the form, you can simply include return false in your code to halt the execution of the function.

Answer №2

To prevent form submission when hitting the enter key, you can use the preventDefault function. By default, pressing enter will submit the form. To avoid this behavior, add preventDefault to your code like so:

<script type="text/javascript" >
jQuery(document).ready(function(){

jQuery('.btn-success').click(function(e){         // make sure to include e parameter
 e.preventDefault();                              // add this line to prevent default action
var form_name  = jQuery(this).attr('title');
var obj = jQuery(this);
jQuery(".ajax_indi").show();
var message = '';
        switch (form_name)
        {

        case "npost":
                var message = jQuery("#message").val();
        break;
        default:
        alert("something went wrong!");
        }

        if((jQuery(message) == ''))
        {
             alert("Message Cannot be Empty");
             jQuery(".ajax_indi").hide();
             return false;
        } else {
            jQuery(this).attr("disabled", "disabled");
            jQuery(this).prop('value', 'Loading...');
            jQuery(this).css('cursor', 'default');
        }

        var str = jQuery("#"+form_name).serialize();

        jQuery.ajax({
            type: "POST",
            url: "chat.php",
            data: str,
            cache: false,
            success: function(html){
                jQuery('#chat1').append(html);
                obj.attr("disabled", false);
                obj.prop('value', 'Post');
                obj.css('cursor', 'pointer');
                jQuery(".ajax_indi").hide();
                document.getElementById(form_name).reset();
            }
        });
           });

       });
   </script>

Answer №3

When dealing with the default action of the Enter key, it's important to take preventative measures. The following code demonstrates how to prevent the default action of the Enter key:

$('#npost').on('keyup keypress', function(e) {
   if (e.which == 13) { 
       e.preventDefault();
       return false;
   }
});

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

Is it considered secure to encase a function within jQuery's removeClass()?

I'm currently developing a unique slider that includes a dynamic video element. With each slide transition, a new video is added to the DOM while the previous one is removed. To achieve this effect, I am utilizing CSS transitions along with a specific ...

The React component is experiencing a delay in its updates

I've been experiencing delayed updates when using React.useEffect(). Can anyone shed some light on why this might be happening? function Process(props) { const [results, setResults] = React.useState({ number: "", f: {} }); let ...

Invoke a function from a page that has been reloaded using Ajax

After making an Ajax request to reload a page, I need to trigger a JavaScript function on the main page based on certain database conditions. This is necessary because I require some variables from the main page for the function. PHP code: if($reset_regi ...

What is the best way to incorporate a countdown timer on an ASP.NET webpage?

Looking to display a countdown timer in the top right corner of my ASP page that starts from 00:00:30 and counts down to 00:00:00 before resetting back to 00:00:30. Does anyone have any suggestions on how to achieve this? ...

Combining Jquery scripts for seamless integration

I am facing an issue while trying to execute two different jQuery scripts simultaneously - one named balancedgallery and the other museum. Individually, each script works perfectly fine. However, when running them together, the balancedgallery script seems ...

Can anyone help me figure out the best way to test for observable errors in Angular2?

I'm currently working on creating unit test cases for my Angular2 components. Up until now, the test cases have been running smoothly. However, I've run into some issues with my asynchronous calls. For example, I have a method for creating a n ...

What is the best way to efficiently transmit Objects through AJAX utilizing bodyParser in node.js express?

Currently attempting to execute: $.ajax({ type:"POST", url:"/psychos", data:JSON.stringify(this.psycho) }) Upon reaching the server, I encounter the following: app.post("/psychos", function(request, respon ...

Stop the event propagation when the back button is clicked

While utilizing ons-navigator, I am looking to customize the function of a particular element at a certain stage. Employing the onClick handler has allowed me to successfully trigger this function. However, upon exiting the onClick handler, the navigator ...

Tips for utilizing [(ngModel)] with an object that is empty, null, or undefined in Angular 4

When trying to assign [(ngModel)] inside my .html code to an empty (null or undefined) object, I encountered the error message _co.object is null. There are two scenarios: one where the object has a value and one where it does not. The ngModel works fine i ...

globalThis undefined following git hiccup

While working on a web app in React, I followed a certain guide to execute Python code successfully within the app. However, during a git operation, I accidentally added unnecessary files like node_modules and package lock files, which led me to delete ev ...

Is there a way to automatically hide a div based on a checkbox value when the page loads?

How can I hide a div in my view when a checkbox is not checked upon page load? <input type="checkbox" class="k-checkbox" id="chkInvoiceStatusActive" asp-for="InvoiceStatus" value="true" /> <input t ...

Issue with custom Javascript not executing in Internet Explorer versions 9 and 10

Initially, this script is found in the document's head section. <script> document.addEventListener("DOMContentLoaded", function () { var e, t = document.querySelectorAll("div.bounceInDown"); for (var n = 0, r = t.length; n & ...

Having issues with passing data to a Modal on eventClick using FullCalendar with ReactJS, receiving a "cannot read property of undefined" error. Any advice on how

My MERN stack application utilizes the FullCalendar plugin, even though I am aware that mixing jQuery with React is not ideal. Unfortunately, I am a novice developer and running behind schedule. The goal is to allow users to click on an event on the calen ...

Are items placed into an array passed by reference or by value?

When working with custom Objects in an Angular context, I define two objects "a" and "b" using an interface. These are created as class attributes along with an empty array of these objects. public a: CustomObj; public b: CustomObj; public array: ...

Is using an interval the best method to ensure that an Ajax call has finished successfully?

I have a scenario with two input text fields and a save button. <input type="text" id="myInput" /> <input type="text" id="searchResult"/> <button id="myButton>save</button> The myInput t ...

Listcell XUL with button options

How can I make buttons inside a listcell function in XUL? I am having trouble getting it to work. Here is the XUL code: <listitem id = "1"> <listcell label = "OK Computer"/> <listcell label = "Radiohead"/> <listcell label ...

Creating custom CSS for Styled Components in ReactJS

I'm struggling with CSS in React using styled components. Below is the code snippet I am working with: import React from 'react'; import { Navbar, Container, Row, Col } from 'reactstrap'; import styled from 'styled-components& ...

Using 'jquery.get' in combination with a servlet is

I need a servlet that can handle GET requests and return a specific string. A simple example of the code is shown below: public class QueryHandler extends HttpServlet { public void doGet(HttpServletRequest request, HttpServletResponse response) ...

Update app content without requiring users to download a new APK

Hey there, I'm new to all of this so I appreciate your patience. I'm working on a video based app and I'm wondering how I can add new videos/content to the app without having users download a new apk. I know I need to host the app on a data ...

Encountering 404 errors on dynamic routes following deployment in Next.JS

In my implementation of a Next JS app, I am fetching data from Sanity to generate dynamic routes as shown below: export const getStaticPaths = async () => { const res = await client.fetch(`*[_type in ["work"] ]`); const data = await re ...