Converting date formats using AngularJS

After clicking the search button and the radio button, I am converting the date format. Everything works fine when I search by date, but I encounter a problem when I click the radio button.

HTML Code

<form action="{{URL::current()}}" ng-submit="submit(item)">
    <div class="form-group">
        <label class="control-label">@lang('app.date')</label>
        <div class="input-group ui-datepicker">
            <input type="text" class="form-control datepicker"
                   uib-datepicker-popup name="enddate"
                   ng-model="item.enddate" is-open="enddate_opened"
                   ng-click="enddate_opened = !enddate_opened"/>
        </div>
    </div>
    <div class="form-group">
        <button type="submit" class="btn btn-primary">
            <i class="fa fa-search"></i> @lang('search.search')
        </button>
    </div>
    <!-- //////////Radio button//////////////////////-->
    <div class="radio">
        <label>
            <input type="radio" name="log_date" value="log_date"
                   onchange="this.form.submit()">
            @lang('product.invoice_date')
        </label>
    </div>
</form>

AngularJs Code

$scope.submit = function (item) {
    angular.forEach(item, function (value, key) {
        var val = value instanceof Date ? moment(value).format('YYYY-MM-DD') : value;

        $('form [name=' + key + ']').val(val);
    });
};

The URL result after clicking the search button:

enddate=2017-01-10

The URL result after clicking the radio button:

enddate=10%2F01%2F17

Both buttons are called from the same method, so why is the result different?

Answer №1

By invoking this.form.submit(), you will only trigger the form's action. The ng-submit function is specific to AngularJS and cannot be activated through regular JavaScript. However, there is a "submit button," so make sure to assign an ID to it:

<button type="submit" id="submit-button" class="btn btn-primary">
    <i class="fa fa-search"></i> @lang('search.search')
</button>

Then, call it from the radio button like this:

<input type="radio" name="log_date" value="log_date"
       onchange="document.getElementById('submit-button').click()">

Answer №2

When accessing the "item.enddate" object, you may notice that you are receiving different values.
Upon clicking the search button, a Date (JavaScript object) is returned in the first scenario.
However, when selecting the radio button, a string is retrieved instead.

This snippet of code demonstrates how to handle this situation:

var val = value instanceof Date ? moment(value).format('YYYY-MM-DD') : value;

This code essentially checks if the value is a Date object and converts it to a string using Moment.js if necessary. Otherwise, it returns the original value.
It's important to note that the string format may vary depending on the context. By console logging the "value" variable, you can observe a Date object or a string like '10/01/17'.

To ensure consistency, log the value and use it to create a new Moment object with the appropriate format:

You can achieve this using the following code:

var val = value instanceof Date ? moment(value).format('YYYY-MM-DD') : moment(value, 'DD/MM/YY').format('YYYY-MM-DD');

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

Guide to retrieving all selected options from a multi-select box using jQuery

I have a lengthy form that is constantly changing and includes multiple Select Options such as <select class="common_dt_select" id="select_15" data-col-index="15"> <option value="">All CC Status</option> <option value="0">De ...

Error message: Vue warning - The prop "disabled" must be a boolean type, but a function was provided instead

I have this code snippet that I am currently using <v-list-item> <v-btn @click="onDownloadFile(document)" :disabled=getFileExtention >Download as pdf</v-btn > < ...

The datepicker is functioning correctly, however, the displayed value does not reflect the updated date

The version of angularjs being used is 1.5.11. Within my .NET MVC project, the bs-datepicker element from angularjs is incorporated. Featured below is the datepicker component accompanied by a pair of images functioning as buttons within my application: & ...

What makes using $(selector).post() and $.get() in jQuery AJAX so valuable?

While browsing w3school, I came across a discrepancy in the definition of AJAX post and get. Post: $(selector).post(URL,data,function(data,status,xhr),dataType) Get $.get(URL,data,function(data,status,xhr),dataType) Why is there a post method with sel ...

Troubleshooting Ng-Switch String Length Issue in AngularJS

I'm currently developing a Store application and I have encountered an issue where I need to display two different strings based on the response received. If the response does not contain an item title, I want to display "No Item Title Found". Otherw ...

I encountered a data discrepancy while attempting to link up with a weather API

This is my debut app venture utilizing node.js and express for the first time. The concept behind this basic application involves connecting to an external API to retrieve temperature data, while also allowing users to input their zip code and feelings whi ...

Guide on displaying various messages without using pop-ups when different options are chosen. Using JavaScript

In order to display different messages on the page based on the selected combinations, I have already created a demo. You can check it out here: http://jsfiddle.net/uDJd8/ <html> <head> <meta content="text/html; charset=ISO-8859-1" http ...

The Bootstrap Navbar-fixed-bottom div is covering up the JS rendered content due to an

The content on my main page container is being obscured by the content within this DIV: <div class="navbar navbar-fixed-bottom"></div> Below is the CSS from the GitHub project (bootstrap sass) // Code to fix top/bottom navbars when screen re ...

When executing the app.delete function, the req.body is found to be empty

I've encountered an issue when trying to send JSON data in an $http Delete call, as the req.body returned is coming back as an empty JavaScript object. Below is my $http delete call where "scenario" is a json object: //Deletes the item from the data ...

Could you explain the functionality of the hide button in AngularJS?

Is there a way to conceal my navigation bar with the click of a button? I need two buttons - one to hide and another to show. When I click on the hide button, the navigation bar should disappear, and vice versa. ...

What is the best way to send an email with a randomly generated HTML output using a <button>?

I am currently working on a feature where a random HTML output is sent to me via email whenever a user clicks on a button on the website page. The user receives a code when they click the button, and I want that code to be emailed to my address automatical ...

Values are being subtracted correctly without displaying any negative results

I'm working with the following code snippet: const my_transactions = [{amount: -100,currency: 'EUR'},{amount: -200,currency: 'EUR'},{amount: -400,currency: 'EUR'}]; let total = 0; my_transactions.forEach(el => total ...

If the td element contains text, add a comma (,) and wrap the text in HTML tags. If there

Currently diving into some jQuery code and have come across a few uncertainties. Here is what I've managed to put together so far: var html = ''; data.entities.forEach(function (value, index, array) { html += index !== data.entities.len ...

Errors encountered while starting Angular due to issues in package.json configuration

Summary: Encountered an error while using 'Angular' for the first time, indicating tsc was not found in the package.json file. Details: As a beginner with Angular, I followed an example from a book and attempted to start it with np ...

Tips for detecting when the MDC Snackbar has been closed using JavaScript

I'm currently working with Material Design's Snackbar in combination with VueJS. My goal is to detect when the snackbar has finished closing. The Snackbar object does have a property called isOpen, which allows me to check if the snackbar is ope ...

an issue encountered while trying to print a webpage styled with CSS

Users are given the option to print the current page on the website by clicking on a menu element: <li> <a href="#" onClick="window.print()"> <i class="icon-print"></i> Print Page </a> </li> The page contai ...

Performing a file selection in Cypress without the presence of an input element in the DOM

Upon clicking the upload button, a file browser is triggered through the method provided below. To my knowledge, an element is not automatically added to the Document Object Model (DOM) unless explicitly appended to a DOM element. const inputEl = document. ...

Issue with autocomplete feature malfunctioning on both php and javascript

I'm currently working on a simple auto-complete script using Javascript and PHP, but I'm running into some issues. Any help would be greatly appreciated! Here's the HTML code I have: <!doctype html> <html lang="en"> <head> ...

Error: Angular Directive has an undefined scope

I have a specific issue with my directive, where I am trying to extract data from an xls file and pass it to a button through the scope. The problem arises when I am binding to the element change event in the link function and calling a function to parse ...

JSON data is returned as Object Object

Trying to work with a JSON object and need to stringify it for localStorage: $http.post('http://localhost:8000/refresh', { name: $scope.name, email: $scope.email, token: $rootScope.devToken, platform: ionic.Platform.platform() }).then( ...