Best practice for verifying if a form is empty in Ember.js

My form includes HTML5 validation implemented in the following way:

<script type="text/x-handlebars" id="project">
    <div class="row">

        <div class="span6">
            <div class="well well-small">
                <p style="text-align: center">
                    You can create a new Project by filling this simple form.
                </p>

                <p style="text-align: center"> Project Name should be minimum 10 characters & There's no limit on
                    Project Description.
                </p>
            </div>
            <form class="form-horizontal">
                <div class="control-group">
                    <label class="control-label" for="projectname">Project Name: </label>

                    <div class="controls">
                        {{!view App.TextFieldEmpty}}
                        <input type="text" name="projectname" id="projectname" required title="Project Name is Required!" pattern="[A-z ]{10,}" placeholder="Enter Project Name"/>
                    </div>
                </div>
                <div class="control-group">
                    <label class="control-label" for="projectdesc">Project Description:</label>

                    <div class="controls">
                        <textarea rows="3" id="projectdesc" name="projectdesc" placeholder="Enter Project Desc"
                                  required="Description Required"></textarea>
                    </div>
                </div>
                <div class="control-group">
                    <div class="controls">
                        <button class="btn" {{action 'createNew'}}>Add Project</button>
                    </div>
                </div>
            </form>
        </div>
    </div>
</script>

In my App.js, I have attempted the following:

App.ProjectController = Ember.ArrayController.extend({
    actions : {
        createNew : function() {
            if (!("#project form.form-horizontal") === "") {
                App.Project.createNew();
            }
        }
    }
});

App.ProjectRoute = Ember.Route.extend({

});

App.Project.reopenClass({
    createNew : function() {

        dataString = {
            'projectname' : $("#projectname").val(),
            'projectdesc' : $("#projectdesc").val()
        };
        console.log('check');
        $.ajax({
            type : "POST",
            url : "http://ankur.local/users/createNewProject",
            data : dataString,
            dataType : "json",
            success : function(data) {
                console.log('success');
            }
        });
        return false;

    }
});

Despite my efforts to validate the form for empty fields before submitting with Ajax POST, the button does not react even when the form is not empty. Additionally, including the entire form would also target checkboxes. How can I prevent the user from submitting an empty form?

Answer №1

Instead of focusing on Ember, this question is more about JS/jQuery. Take a look at jQuery's val() function.

Make sure to validate your form inputs in the view where you can access the <input elements. Also, remember that

$("#project form.form-horizontal") === ""
is missing the jQuery selector $.

App.ProjectView = Ember.View.extend({
    actions : {
        createNew : function() {
            if (!(this.$("#projectname").val() === "")) {
                App.Project.createNew();
            }
        }
    }
});

If there are other issues in your code, creating a jsFiddle with your code will make it easier for us to assist you.

Answer №2

After some trial and error, I have found a solution to my own question and it appears to be effective.

Here is the approach that yielded results:

App.ProjectController = Ember.ArrayController.extend({
    actions : {
        createNew : function(event) {
            $(":text, :file, :checkbox, select, textarea").each(function() {
                if ($(this).val() === "") {
                    alert("Empty Fields!!");
                } else {
                    App.Project.createNew();
                                    event.preventDefault();
                }
            });

        }
    }
});

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

Unexpected syntax error occurs while retrieving data from web API using jQuery AJAX request

I'm attempting to retrieve a json object from the following URL: You may not understand much as it's in Greek, but the format is json. Below is the code snippet I'm using: function getDicts() { api_url = 'https://test3.diavgeia.gov ...

Why are the variables not reflecting the changes when an event is triggered?

I'm a beginner in programming and would really appreciate some guidance. Why are my variables not updating when I click the button?? Here is the HTML code snippet: <h1>NIM</h1> <p>Welcome to a simple edition of the game NIM</p& ...

Incorporating React-Native components into a Next.js application within an Nx monorepository: A Step-by-Step

I'm encountering an issue while attempting to integrate React Native components into an Nx monorepo setup. Initially, the Nextjs app compiles successfully: info - Fast Refresh enabled for 1 custom loader event - client and server compiled successful ...

How can the table attribute "name" be obtained and added as the file name for DataTables in the export feature?

Having multiple tables on my page using JQuery DataTables, I find it to be a useful library. I am looking to modify the file name for exporting the data on these tables. I have several DataTables on this page This is how I initialize my tables: $(docume ...

Import the information into a td tag's data-label property

I have implemented a responsive table design that collapses for smaller screens and displays the table header before each cell. body { font-family: "Open Sans", sans-serif; line-height: 1.25; } table { border: 1px solid #ccc; border-collapse: co ...

Tips for successfully sending a nested function to an HTML button and dropdown menu

I'm working on two main functions - getChart() and fetchData(). The goal is to retrieve chart data and x/y axes information from a database. Within the getChart function, I'd like to incorporate a dropdown menu for displaying different types of c ...

Replacing an existing pie chart with a new one using JavaScript

I created pie charts using chartjs V2.6.0, and everything was working fine until I encountered an issue. Whenever I input new data into the same chart, it keeps displaying the previous data when hovering over. I attempted to fix this by using the $('# ...

Display popup when hovering over an li element, but only after one second of hovering over it

My goal is to display an inner div when hovering over an li element. I have implemented a fadeIn and fadeOut effect, but the issue is that if I quickly hover over all li elements, the fadeIn effect triggers for all of them. Ideally, the inner div should on ...

Jquery is not working as expected

I am having trouble implementing a jQuery function to show and hide select components. It doesn't seem to be working correctly. Can someone help me identify the issue? <html> <head> <meta charset='UTF-8' /> <script ...

Bootstrap's square-shaped columns

I would like to implement a grid of squares for navigation purposes. By squares, I mean that the colored areas should have equal width and height. Currently, I have achieved this using JavaScript, but I am interested in a CSS-only solution. My project is ...

Steps for building a Bootstrap grid of thumbnails

I need to display an unknown number of thumbs. Below is a sample of the HTML rendered: <div class="row-fluid"> <ul class="thumbnails"> <li class="span3"> <a href="#" class="thumbnail"> &l ...

personalized link when uploading images in Jodit Editor

I recently integrated the Jodit Editor (react) with the Insert Image option, allowing users to upload images that are saved in the default location set by the Editor. Now I am curious about how to use a custom URL to insert an image in the editor. Here i ...

What is the best method for sending variables to the `script.` block in Pug?

I am encountering an issue with the code in my index.pug file doctype html html head title= title body script(src=`${source}`) script. for (var event of events){ VClient.Event.subscribe(event, createDiv); } This is how ...

Steps to include a jQuery reference in a JavaScript file

I'm looking to create an external JavaScript file with validation functions and incorporate jQuery into it. Can anyone provide guidance on how to accomplish this? I attempted the code below, but unfortunately, it doesn't seem to be functioning c ...

Breaking down a javascript project

As the trend of splitting large JavaScript projects into separate files and then compiling them into a single distribution increases, I am eager to explore this workflow. While I have considered Node.js, npm, and Grunt for this purpose, I find the learning ...

Tips for displaying nested JSON arrays in HTML using Ember.js

I'm having trouble displaying the JSON data I get in app.js using HTML. Any suggestions? Here is the code for app.js (I am confident that $.post is returning valid JSON) App.CadeirasRoute = App.AuthenticatedRoute.extend({ model: function() { a ...

What is the best way to retrieve ViewBag data using jQuery?

Greetings, I am currently in the process of developing a web application using MVC5. Within this application, I have implemented a login form that consists of fields for both username and password: @using (Html.BeginForm("ClickAction", "Login", FormMethod ...

The Epub text box feature is malfunctioning

I have a quiz task in an epub format where users need to enter their answers in a text box after reading the question. However, I am facing an issue where the text box does not display the keyboard for typing the answer. Is there a solution using javascr ...

Error Uploading File to Cloudinary Platform

I am currently developing a REST API using Express.js. The main functionality of the API involves accepting a video file from the client and uploading it to Cloudinary. Interestingly, when I test the API by returning the file back to the client, everything ...

What could be causing document.getElementById to return null?

I've been troubleshooting my code and noticed that one of the methods in my JavaScript file is not functioning correctly. Does anyone have any insights into why this might be happening? index.html: <!DOCTYPE html> <html lang="en"> <he ...