javascript a loop through an array to reassign element ID's

Formulating a form with input elements that are utilizing a jquery datepicker is the current task at hand. Take a look at a snippet of the HTML code for these inputs:

<td style="width:15%"><input type="text" name="datepicker" id="Tb3fromRow10"/></td>
<td style="width:15%"><input type="text" name="datepicker" id="Tb3toRow10"/></td>

An issue has arisen where the date format required is mm/dd/yyyy, while the database only accepts formats in yyyy-mm-dd. As a workaround, the plan is to display dates as mm/dd/yyyy on the form, but use an eventlistener onSubmit to convert all dates to yyyy-mm-dd before being recorded in the database. The approach involves creating an array using getElementsByName (since all elements have been named "datepicker"), changing their formats, and then reassigning their IDs. Progress has been made on the first two steps, with some difficulty encountered when attempting to reassign IDs:

var myArray = document.getElementsByName('datepicker[]');
    for(var i = 0; i < myArray.length; i++) {
    var sep = myArray.split('/');
    var newDate = sep[2]+'-'+sep[0]+'-'+sep[1];
}
**document.getElementsByName('datepicker[]').value = newDate;**  

It's evident that the last line is incorrect. Assistance is needed in correctly reassigning all date elements to their corresponding IDs.

Appreciate any guidance!

Answer №1

IDs are not being reassigned in this scenario, but the utilization of myArray is incorrect. In order to make the necessary changes, assuming the input field has a name of datepicker[] and not datepicker, as shown in the provided HTML code snippet:

var myArray = document.getElementsByName('datepicker[]'); // or ("datepicker") depending on their name
for(var i = 0; i < myArray.length; i++) {
  var sep = myArray[i].split('/');
  var newDate = sep[2]+'-'+sep[0]+'-'+sep[1];
  myArray[i].value = newDate;
} 

Alternatively, why not consider validating and reformatting the data on the server side before persisting it?

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

Creating individual product pages from an array of objects: A step-by-step guide

Is there a way in Next.js to create individual pages for each object in an array with unique URLs? Here is the input array: Input Array const products = [ { url: "item-1", id: 1, name: "Item 1", description: "lor ...

utilizing props to create a navigational link

How can I display a tsx component on a new tab and pass props into the new page? Essentially, I'm looking for the equivalent of this Flutter code: Navigator.push( context, MaterialPageRoute(builder: (context) => Page({title: example, desc: ...

Ruby on Rails and JSON: Increment a counter with a button press

How can I update a count on my view without refreshing the page when a button is clicked? application.js $(document).on('ajax:success', '.follow-btn-show', function(e){ let data = e.detail[0]; let $el = $(this); let method = this ...

What is the best way to fetch information from an API using Angular5 with Material2 components?

Here are the 'table.component.html' and 'table.component.ts' files where I am pulling data from an API to display in a table. Below is the object received from the API: [ {position: 1, name: 'Hydrogen', weight: 1.0079, sym ...

Unable to interact with the page while executing printing functionality in

component: <div class="container" id="customComponent1"> New Content </div> <div class="container" id="customComponent2"> different content </div> ...

The CSS transition will only activate when coupled with a `setTimeout` function

After using JavaScript to adjust the opacity of an element from 0 to 1, I expected it to instantly disappear and then slowly fade back in. However, nothing seems to happen as anticipated. Interestingly, if I insert a setTimeout function before applying th ...

Activate the Masterpage menu to emphasize its current state

I am currently utilizing the AdminLTE template on my website. One issue I have encountered is with the menu and its child menus. When redirecting to different pages using image buttons, the menu collapses back to its original state. While navigating throu ...

SignalR blocking axios requests (In a Waiting State)

I am currently developing a project that involves bidding on products in Auctions with real-time updates of the bid price. With potentially thousands or even millions of users worldwide participating in the bidding process. We have implemented SignalR for ...

What is the best way to filter out and combine one array from two arrays in lodash based on their unique properties?

Lodash v 4.17.15 Consider the scenario where two arrays are involved: var users = [{ id: 12, name: Adam },{ id: 14, name: Bob },{ id: 16, name: Charlie },{ id: 18, name: David } ] var jobs = [ ...

Deactivating a button if the input fields are blank using ReactJS

Hi there, I'm new to reactJS and recently encountered an issue with my code. Everything seems to be working fine except for the NEXT button not being disabled when text fields are empty. My expectation is that the NEXT button should only be enabled af ...

Troubleshooting issue with Gulp watch on Node v4.6.0

I'm currently facing a frustrating situation. I had a project up and running smoothly with a functioning gulpfile.js file, everything was perfect until I updated node to version 4.6.0. When I tried to report this issue on Gulp's git repository, t ...

Surprising 'T_ENCAPSED_AND_WHITESPACE' error caught me off guard

Error: An error was encountered while parsing the code: syntax error, unexpected character (T_ENCAPSED_AND_WHITESPACE), expected identifier (T_STRING) or variable (T_VARIABLE) or number (T_NUM_STRING) in C:\wamp\www\html\updatedtimel ...

Retrieve telephone number prefix from Cookies using React

Being able to retrieve the ISO code of a country is possible using this method: import Cookies from 'js-cookie'; const iso = Cookies.get('CK_ISO_CODE'); console.log(iso); // -> 'us' I am curious if there is a method to obt ...

Change the value of the checked property to modify the checked status

This is a miniCalculator project. In this mini calculator, I am trying to calculate the operation when the "calculate" button is pressed. However, in order for the calculations to run correctly in the operations.component.ts file, I need to toggle the val ...

What is the reason for the lack of arguments being passed to this Express middleware function?

I have been developing a middleware that requires the use of `bodyParser` to function, however I do not want to directly incorporate it as a dependency in my application. Instead, I aim to create a package that includes this requirement and exports a middl ...

Leveraging Webworkers in an Angular application for efficient data caching with service workers in the Angular-CLI

I am looking to run a function in the background using a worker, with data coming from an HTTP request. Currently, I have a mock calculation (e.data[0] * e.data[1] * xhrData.arr[3]) in place, but I plan to replace it with a function that returns the actual ...

What is the best way to eliminate the [lang tag] from a URL in Next.js?

I am looking to eliminate either the /en or the /it from the URL without explicitly adding it. i18next seems to be doing it automatically, and I am unsure how to disable this behavior. I simply want it to happen in the background. https://i.stack.imgur.co ...

Common reasons why you may encounter the error "Uncaught TypeError: $(...).DataTable is not a function"

I recently started working with DataTable.js, and when I tried to integrate it into my ASP.NET Core MVC 5.0 project, I encountered an error: Uncaught TypeError: $(...).DataTable is not a function After doing some research on Google, I discovered that this ...

Vue (Gridsome) App encountering 'Cannot POST /' error due to Netlify Forms blocking redirect functionality

Currently, I am in the process of developing my personal website using Gridsome. My goal is to incorporate a newsletter signup form through Netlify Forms without redirecting the user upon clicking 'Submit'. To achieve this, I utilize @submit.prev ...

Retrieve active route information from another component

We are utilizing a component (ka-cockpit-panel) that is not linked to any route and manually inserted into another component like so: .. ... <section class="ka-cockpit-panel cockpit-1 pull-left"> <ka-cockpit-panel></ka- ...