Controlling HTML elements with a controller

This seems chaotic and I long for a more organized solution.

I have different HTML elements:

<input class="form-control" required="true" name="Spanish" type="text" value="blah blah" id="lang_1">

<input class="form-control" required="true" name="French" type="text" value="hey hey hey" id="lang_2">

To save them, I use this method:

 function saveTranslations() {
var htmlRows = $("[id^=lang]");
var rowCount = htmlRows.size();
for (i = 0; i < rowCount; i++) {
ARRAY_LANGUAGE_ID[i] = htmlRows[i].id;
ARRAY_DESCRIPTION[i] = htmlRows[i].value;
}
}

Next, I utilize AJAX:

$.ajax({
type: 'PATCH',
url: 'products/' + id,
data: {
languageIDs: ARRAY_LANGUAGE_ID,
descriptiond: ARRAY_DESCRIPTION
}
});

This approach doesn't feel quite right. Is there a better way to accomplish this task?

Mick

Here is a slightly improved version:

var translations = $("[id^=lang]").serializeArray()

Answer №1

$(function() {
  $('#save').on('click', function() {
    var htmlRows = $('input[id^="lang"]'),
        ARRAY_LANGUAGE_ID = [],
        ARRAY_DESCRIPTION = [];

    $.each(htmlRows, function() {
      ARRAY_LANGUAGE_ID.push($(this).attr('id'));
      ARRAY_DESCRIPTION.push($(this).val());
    });
    
    // Handling AJAX request
    console.log(ARRAY_LANGUAGE_ID,
               ARRAY_DESCRIPTION);

  })
});
<!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width">
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
    <title></title>
  </head>
  <body>
    lang_1: <input class="form-control" required="true" name="Spanish" type="text" value="blah blah" id="lang_1"><br>
    lang_2: <input class="form-control" required="true" name="French" type="text" value="hey hey hey" id="lang_2"><br><br>
    
    <button id="save">save</button>
  </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

Tips for triggering an event from a function instead of the window

Everything is functioning as expected, with the event listener successfully capturing the custom event when it is dispatched from the window and listened for as loading, all seems to be working well. const MyLib = mylib(); function mylib() { const re ...

Is there a way to inject C++ text into an input field on a webpage using QWebEngine?

I want to integrate a website with QWebEngine to manipulate input commands using Qt's event filters and more. The specific website I am working with requires a username/email and password, and I aim to manage the input of this text on my end. This inv ...

Learn the process of effortlessly transferring user information to a MongoDB database

Using socket.io, I am broadcasting geolocation data (lat, lng) and updating the marker icon on a map every time a user connects to the app. When a user from Japan connects, their position is shared with me and vice versa. The issue arises when I only want ...

Tips for incorporating theme colors in the "color" prop when employing MaterialUI components

Trying to utilize the colors from my Mui palette as values for the color property in this way: For example: <Tabs indicatorColor="primary.mainGradient" > <Tab /> </Tabs> However, this approach does not seem to wo ...

Node.js server encountering a cross-domain error

As a beginner exploring node.js, I am embarking on setting up my very first installation. In my server.js file, I am defining a new server with the following code: var app = require('http').createServer(handler), io = require('socket.io&a ...

What steps can be taken to display database results solely for the user currently logged in and created by them?

Currently, I'm in the midst of a project that involves extracting an HTML list from JSON data using JavaScript. The list is being displayed on the logged-in user's profile, showcasing job listings from the JSON data. While I've successfully ...

Somehow, my array only manages to traverse exactly half of its elements

Something odd is happening with my input tag in the HTML file where only half of my array elements are being processed. The input collects numbers/letters and assigns a line of code, like this: let result = Object.fromEntries( Object.entries(answers2).m ...

Once the form is submitted, Vue automatically resets all the data

export default { data() { return { usrName: null, pass1: null, pass2: null, regState: {stateCode:-1}, } }, methods: { register: function () { this.axios.post("/login/", { baseURL: 'http://127 ...

Having difficulty integrating framer-motion with react-router

I've been working on adding animations and smooth transitions to my app using Framer-motion, but I'm facing some challenges in getting it all to function properly. With react-router 6, my goal is to trigger exit animations on route sub-component ...

Refreshing a controller by clicking it from another controller in AngularJS

Here is some HTML code I have been working on. I have a function in moreThanOne.html which sets a variable show to true. This causes it to load one.html for the first time and call the init method of my controller. However, if I change the valu ...

Using Django ajax doesn't function properly when it's in a separate file

My Django site utilizes AJAX to handle requests. Initially, I had the JavaScript code embedded within the HTML document using <script>...</script>, which worked perfectly fine. However, when I decided to move the JavaScript to a separate file, ...

Sorting Columns in PrimeVue DataTable by Date and Time

I am using a PrimeVue DataTable () with the following structure: <DataTable :rows = "5" :value = "apiItems" > <Column v-for="data in columns" :field="data.field" :header="data.header&q ...

Updating a particular element within nested arrays: best practices

I have developed a data table containing student records using material UI. Each row represents a different student array with a fee verification button. My goal is to change the fee status when the button is clicked for a specific student, but currently t ...

refresh Laravel 5.1 webpage content seamlessly without page reloading

Is there a way to update page content in Laravel 5.1 every second without reloading the page for all users? Here is my current view: I'm trying to refresh data without reloading the page using a foreach loop, but I'm not sure how to accomplish ...

Utilizing AJAX to send RSS feeds to a Django view

I'm fairly new to using ajax. Here's the scenario I'm dealing with: I'm working on a side project that involves displaying news and scores for various sports. To achieve this, I'm utilizing rss feeds from different sources. In my D ...

What sets Angular 2 apart when it comes to utilizing [ngStyle] versus [style.attribute]?

When using Angular 2, what distinguishes the following 2 options for passing a variable value to a style? Are there advantages and disadvantages, or is it simply a matter of personal preference, or is one more adaptable/meant for specific purposes? Option ...

Facebook utilizes Ajax for refreshing the page and obtaining updates

How does the system for update notifications and chat work on Facebook? Ajax is used to send requests to the server, such as inserting records into a database. But how are these records pushed by the server to other users? Does the Facebook page constant ...

Can you define the "tab location" in an HTML document using React?

Consider this component I have: https://i.stack.imgur.com/rAeHZ.png React.createClass({ getInitialState: function() { return {pg: 0}; }, nextPage: function(){ this.setState({ pg: this.state.pg+1} ) }, rend ...

Locate the midpoint index of the initial sequence occurrence within an array

I am trying to determine the midpoint of the first sequence that appears when given multiple strings in a large array For example: var array = ["c6dafc", "c6dafc", "1d2129", "1d2129", "1d2129", "cfcfff", "cfcfff", "ffffff", "1d2129", "1d2129", "1d2129", ...

Whenever an AJAX post request is made to the Rails database, the response consists of a collection of unspecified entities

Within my rails application's view, I am attempting to initiate an ajax request with parameters of date_from and date_to. These parameters will then be used to trigger an action in my controller that will search for records within a specified date ran ...