Having trouble getting the jQuery and Javascript function to modify the content of a DIV?

When I click a button, the following code is supposed to be executed:

 <input type="submit" name="cancel" value="cancel" onclick="clear_form (); return false;" class="pure-button">

This function clears the text from the textarea and removes two buttons from the form:

 function clear_form () {
        $("#statement").val('');
        document.submitform.submit.value = "save";
        document.submitform.delete.remove();
        document.submitform.cancel.remove();
 }

However, when I click the button in Chrome, I receive an error message saying that clear_form is not defined. As a result, the clear_form function does not work as expected.

Uncaught ReferenceError: clear_form is not defined 

I'm wondering if anyone can help me figure out what I might have missed?

Answer №1

Is the function function clear_form() declared within another function? If so, then clear_form() is only locally available within the scope of that containing function. To attach click handlers in HTML attributes, the mentioned functions must be declared globally.

If you're unable to make clear_form() global, you can still use addEventListener() to add your local function from Javascript instead of using the attribute onclick in HTML. By the way, this is the recommended approach for handling this on websites in order to separate content and logic.

Answer №2

UPDATE

VIEW DEMO

Javascript Function

function clear_input(){

    $("#statement").val('');
    document.submitform.submit.value = "save";
    document.submitform.delete.remove();
    document.submitform.cancel.remove();

    }

document.getElementById('submit').addEventListener('click',function(){

    alert()

    clear_input();

},false);

HTML Element

<input type="submit" name="cancel" value="cancel" class="pure-button" id='submit'>

According to @cookiemonster, having extra space(s) after function names does not impact functionality.

For more details, visit this link

Answer №3

I'm not entirely sure how you plan on incorporating that code into your full application, but I have created a complete working sample page for you to try out.

Please insert the following code snippet within the head tag of your HTML:

<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
    <title></title>
    <script type="text/javascript">
        function clear_form() {
            //    $("#statement").val('');  or load the JQuery Library and us this line
            document.submitform.statement.value = "";  // Used this instead of JQuery
            document.submitform.submit.value = "save";
            document.submitform.delete.remove();
            document.submitform.cancel.remove();
        }
    </script>

</head>
<body>
    <form name="submitform" id="submitform">
        <textarea id="statement" cols="30" rows="3"></textarea> <br />
        <input type="button" name="delete" value="delete" /><br />
        <input type="button" name="submit" value="Submit" /><br />
        <input type="submit" name="cancel" value="cancel" onclick="clear_form (); return false;" class="pure-button">
    </form>
</body>
</html>

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

I am experiencing issues with Google Fonts not functioning properly when I insert the bootstrap CDN

I have encountered an issue while working on my landing page. I am using Google fonts for the design and trying to integrate Bootstrap as well. However, whenever I add the Bootstrap link, all the font styles stop working. I have checked the order of the CS ...

Fixed width select2 input group

Why does the input group select 2 element disrespect the parent element width by extending beyond what is necessary? Selecting a normal option appears to be fine. However, when I choose a longer option, it ends up looking like this. Is there a way to se ...

Issue retrieving image from API in React

Currently, I am honing my skills in React and aiming to create a straightforward application that searches for movies and displays brief information about them as search results. Successfully, I have managed to retrieve data from an API and store it in Rea ...

When using create-react-app with JEST to run tests, TypeScript errors are not displayed

When I write incorrect TypeScript code in my project set up with create-react-app, running tests using npm test does not show any errors in the terminal. Is this normal behavior? It would be helpful to see these errors to avoid writing incorrect TypeScript ...

Replace pipeline function during component testing

During my unit testing of a component that utilizes a custom pipe, I encountered the need to provide a fake implementation for the transform method in my test. While exploring options, I discovered that it's feasible to override components, modules, ...

Creating fresh CSS by extracting essential selectors from an existing CSS file using Javascript

Is there a method to develop a mini JavaScript function that can parse an HTML document, extract specific selectors from a lengthy CSS file that contains over 2000 lines, and create a new CSS file with only the necessary styles? ...

avoidable constructor in a react component

When it comes to specifying initial state in a class, I've noticed different approaches being used by people. class App extends React.Component { constructor() { super(); this.state = { user: [] } } render() { return <p>Hi</p> ...

Unable to use jQuery change function within Bootstrap 5 tabs

I have inserted an input form within the tabs of bootstrap 5 like so: <div class="container"> <div class="row justify-content-center my-5"> <div class="col-auto"> <ul class="nav bg-dark&qu ...

In the past, I've crafted buttons and other elements using Photoshop, and subsequently saved them for web use. However, I'm now contemplating whether it's more advantageous to employ CSS in

In the past, I have utilized Photoshop to create visually appealing buttons and footer bars for my websites. However, I'm now pondering if it's more beneficial to utilize CSS for button creation. I've noticed that manually coding them can re ...

Utilizing jQuery and Flot to create dynamic real-time graphs with stacked lines

I am experiencing an issue with the stack option on a line-based real-time graph that is fed by a JSON file. The legend displays correctly, but the lines on the graph disappear. There seems to be no stacking and the lines are nowhere to be found. Has anyo ...

Performing insert operations with multiple repositories in NestJS using TypeORM

I currently have multiple APIs in place that handle CRUD operations, such as: POST /table POST /chair Each API has its own repository instance within their respective Service file. The following is a snippet of the Table's service file: table.servic ...

What steps can I take to resolve this issue when encountering an error during npm install?

As a newcomer to programming, I am embarking on the creation of a Discord bot using node and discord.js. My current hurdle involves the installation of a library named canvas, which seems to be causing issues. After developing and testing my application o ...

Having trouble implementing a circular progress bar with a custom Tailwind CSS library, the desired effect is not being achieved

I am on a mission to create a circular progress indicator. Recently, I stumbled upon the daisyui library and its component called radial progress - The documentation mentions that: "Radial progress requires the use of the --value CSS variable." ...

Exploring the loading of stateful data in ReactJS and implementing optimizations

Exploring the world of ReactJS in conjunction with Django Rest Framework (DRF) def MyModel(model): ... status = ChoiceField(['new', 'in progress', 'completed'...]) In my application, I have dedicated sections for eac ...

Hosting images with an online service on jsfiddle: A guide

Exploring the world of HTML canvas and honing my skills in HTML and CSS through jsfiddle, I am eager to incorporate my own images. While sites like Google Drive provide free image hosting, I wonder if I can utilize them with drawImage(); Is there a way to ...

Updating Array Values in AngularJS based on Input Text Box Modifications

In my application, there is a text box that looks like this - <input type="text" class="form-control" id="inputID" name="ItemId" ng-model="inputItemId" ng-required="true" ng-blur="addValueToArray(inputItemId)"/> The user has the ability to add or r ...

Read and manipulate website content using PHP

I recently encountered a challenging situation as a newcomer. Despite searching on Google, I couldn't find any information about it. There is a website that allows users to search for doctors in their area or state. It's possible that the number ...

JavaScript generates an image and its corresponding answer at random

I am currently working with the following code: <!DOCTYPE html> <html> <head> <script language="JavaScript"> <!-- Hide from old browsers function pickimg(){ var imagenumber = 5 ; var randomnumber = Math.random() ; var rand1 = ...

The code `$(body).css({'background-image':'url'}) is not functioning properly

Is it safe to assume that the .css() method cannot be applied to the body tag? Since it seems to work fine when used on $("#div")... ...

Trigger an event in jQuery when the focus moves away from a set of controls

Within a div, I have three textboxes and am looking for a way to trigger an event when focus leaves one of these inputs without transitioning to another one of the three. If the user is editing any of the three controls, the event should not be triggered. ...