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

Having trouble utilizing Reactjs Pagination to navigate through the data

I'm currently working on implementing pagination for a list of 50 records, but I'm encountering an issue. Even though I have the code below, it only displays 10 records and I'm unaware of how to show the next set of 10 records until all 50 a ...

Troubleshooting issues with AngularJS's minDate functionality

I have been trying to set the minDate for the datepicker to today, following the example on the angularJS bootstrap site. However, it seems like something is not working correctly. There are no console errors showing up, but it appears that the minDate is ...

When scrolling on an IOS mobile device, the .on(click) event is triggered for fixed position elements

Whenever I click on an li element or menu, a function is triggered that moves the nav container to the left by the width of the window. However, on my iPhone, after I click to slide the container off the screen, the event gets triggered repeatedly every ti ...

How can you obtain values from a nested JSON object and combine them together?

I have a javascript object that is structured in the following format. My goal is to combine the Name and Status values for each block and then store them in an array. { "datatype": "local", "data": [ { "Name": "John", ...

Transferring MongoDB information to a Jade template in an ExpressJS application

Hey there, hoping you can assist me with a query issue I'm facing. To give you some context, I am querying a MongoDB collection and trying to pass the results back to a Jade view. app.helpers({ clients: function(){ users.find({uid:req.session.u ...

Unable to execute JS script to navigate back to prior page with webdriver

Here is my code snippet: JavascriptExecutor jse = (JavascriptExecutor)driver; jse.executeScript("window.history.go(-1);"); The code above isn't working. I've tried casting the webdriver instance but it doesn't work every time. I prefer not ...

Exploring nested optgroup functionality in React.js

Within my code, I am utilizing a nested optgroup: <select> <optgroup label="A"> <optgroup label="B"> <option>C</option> <option>D</option> <option>G</option> </optg ...

Looking for similar arrays from two sets of multidimensional arrays

Greetings! I have the following two multidimensional arrays: Array ( [user_attempts] => 0 [2] => Array ( [0] => 1 [1] => 4 ) [3] => Array ( [0] => 32 [1 ...

Issue encountered with mouse handling on SVG elements that overlap is not functioning as anticipated

I am working with multiple SVG path elements, each contained within a parent SVG element, structured like this: <svg class="connector" style="position:absolute;left:277.5px;top:65px" position="absolute" pointer-events:"none" version="1.1" xmlns="http:/ ...

Can PHP retrieve data when the form submit function is overridden with AJAX?

I have customized the .submit function of a form on this webpage. It is being loaded inside the #mainContent in an "index.php" and I want the Submit button to only replace this #mainContent. My goal is to retrieve data from this form and send it to a .php ...

Python's selenium struggles with iterating through elements

When attempting to iterate through a list of elements using the index of a class, the index doesn't increase with each attempt. If quotes are added around %s, it results in an invalid syntax error. lengeItem = len(driver.find_elements_by_xpath(&apos ...

What are the reasons for not accessing elements in a more "direct" way like elemId.innerHTML?

Recently, I came across a piece of JavaScript code that accesses HTML elements using the shorthand elementID.innerHTML. Surprisingly, it worked perfectly fine, but interestingly, most tutorials opt for the traditional method of using document.getElementByI ...

When I try to increase the date by 1 day using the MUI X Date picker, it does not update as expected

I have encountered an issue where adding 1 day to my date picker on button press results in it jumping to 01/01/1970. The same occurs when attempting to subtract 1 day from it. My goal is to achieve the following: Refer to this image of my Date picker: D ...

Trouble with the array returned by preg_split in PHP

I am currently in the process of developing a PHP script to validate usernames and passwords. I am taking it step by step, starting with a password file that contains only one line: user:0011 To parse the lines in this file, I am using preg_split and hav ...

JavaScript: Generating multiple variables using a for loop?

Is there a way to dynamically create n variables a_1, a_2, a_3 ... a_n, where the value of n is determined during runtime? Attempting to use the following code would not produce the desired outcome: var n = prompt("Enter number of variables?"); for (i= ...

The left border is failing to appear on the Td element

When attempting to add border styling to td elements, the left border is not displaying correctly. This issue seems to vary across different browsers. Here is the HTML code: <table class="table-bordered"> <thead> <tr> ...

Tips for integrating my Python random forest classifier in a web application built using HTML, Javascript, and Node.js

Greetings! I am currently in the process of creating a machine learning web application that requires the use of a random forest classifier. However, I am unsure of how to properly integrate the python code with it. Any guidance would be greatly apprecia ...

The error message "TypeError: Unable to access property of undefined when using web sockets"

Exploring Isomorphic framework for React and integrating Pusher for websockets communication. I'm encountering difficulty accessing the state within the componentDidMount() function. class TopbarNotification extends Component { state = { vis ...

The Gulpfile.js encountered an error while trying to load

My Visual Studio task runner is having trouble loading the gulp file. I am currently using VS2017 v15.9.4, but the project was developed some years ago. Failed to run "...\Gulpfile.js"... cmd.exe /c gulp --tasks-simple assert.js:350 throw err; ...

Extracting the value from a Text Editor in React Js: [Code snippet provided]

Currently, I am in the process of developing a basic app that generates a JSON form. So far, I have successfully incorporated sections for basic details and employment information. The basic details section consists of two input fields: First Name and Las ...