Using a JavaScript "for each" loop instead of having several "if

Could you please provide guidance on where to proceed?

There are multiple input rows, with each row containing a field with the class row_changed

If the value in the field is greater than 0, ajax will send the entire row to PHP. Each row is wrapped in a <tr></tr> tag and given an id of <tr id='row'>

Currently, achieving this requires multiple if statements.

I am looking for a solution to pass the corresponding row (inside <tr id='row'>) to PHP if any of the fields with the class row_changed have a value greater than 0.

Here is some information. Is it applicable to this scenario?

<tr id='row1'>
  <td>
    <input type="text" name="row1[]" id="date_day1" class="row_changed1">
  </td>
    ...
  <td>
    <input type="text" name="row1[]" id="is_row_changed1" size="1">
    <script>
      $(".row_changed1").on("change", function () {
        document.getElementById('is_row_changed1').value = 1;
      });
    </script>
  </td>
<tr>

if ($("#is_row_changed1").val() > 0) {
  $.post("_autosave_array.php", $("#row1 :input").serialize(), function (data1) {
    $('#load1').html(data1);
    $('#is_row_changed1').val(0)
  });
  var str = $("#row1 :input").serialize();
  $("#load1_1").text(str);
}

if ($("#is_row_changed2").val() > 0) {
  $.post("_autosave_array.php", $("#row2 :input").serialize(), function (data2) {
    $('#load2').html(data2);
    $('#is_row_changed2').val(0)
  });
  var str = $("#row2 :input").serialize();
  $("#load2_1").text(str);
}

Answer №1

Here is a sample implementation:

function handlePost(rowId, serializeId, resultId, serializedResultId){
  if ($(rowId).val() > 0) {
    $.post("_autosave_array.php", $(serializeId + ":input").serialize(), function (data) {
      $(resultId).html(data);
      $(rowId).val(0)
    });
    var strData = $("#row2 :input").serialize();
    $(serializedResultId).text(strData);
}

var dataRows = [{rowId: "#is_row_changed1", serializeId: "#row1", resultId: "#load1", serializedResultId: "#load1_1"},
               {rowId: "#is_row_changed2", serializeId: "#row2 ", resultId: "#load2", serializedResultId: "#load2_1"}
              ];

for(var i = 0; i < dataRows.length; ++i){
   var currentData = dataRows[i];
   handlePost(currentData.rowId, currentData.serializeId, currentData.resultId, currentData.serializedResultId);
}

Answer №2

It appears that all of the input tags you have share the same name. You can target them all by their shared name and then implement your logic or condition inside.

Here is an example:

$("input[name='row1[]']").each(function(){
        if($(this).val()>0){
            $.post("_autosave_array.php", $("#row1 :input").serialize(), function (data1) {
            $('#load1').html(data1);
            $('#is_row_changed1').val(0)
        }
    });

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

Node.js retrieves a single row from a JSON array with two dimensions

I am working with a two-dimensional JSON array and I am able to retrieve data from the first dimension using data["dimension-1"], but I am struggling to access data from the second dimension using data["dimension-1"]["dimension-2"]. What is the correct m ...

What could be causing PHP to issue an undefined index notification for a POST variable even though Ajax is returning the correct information and the POST variable is present?

While I acknowledge that there are similar general questions out there, none of them address my specific circumstances or offer a solution. Within the same folder on the server, I have two files: "quiz_maker.php" and "master_data.php." I am sending a JSO ...

Is there a way to showcase Ajax data in an alert window and simultaneously integrate dynamically added data?

I am using a PHP script to fetch data in the following way: $.ajax({ url: './fetchData.php', type: "POST", data: { mail: mail }, dataType:'text', success: function(ans) { var data = JSON.parse(ans); $(' ...

Scale up each image with the use of Java script

I have a main container with three different sub-containers, each containing an image and text. I want to achieve the effect of zooming in on the image of the specific sub-container when hovering over it. Currently, when I hover over any sub-container, all ...

The "Overall Quantity" of items will vary as it goes through different numerical values, despite the fact that I employed --

I am currently working on an e-commerce website with a shopping cart feature. The cart displays the number of items added to it, which increases by one when 'Add to Cart' is clicked and decreases by one when 'Remove' is clicked. However ...

What methods can I utilize to prevent pop-up errors from appearing in my javascript code?

Recently, I've been working on utilizing an innovative IBM tool called Presto that efficiently transforms traditional green screens into browser-based pages. While the process is effective, it involves some quirky behaviors. One particular challenge I ...

Error: A colon was unexpectedly encountered while trying to access the JSON API on tickets.com

I've been attempting to retrieve data from the following URL: http://api.master18.tiket.com/search/autocomplete/hotel?q=mah&token=90d2fad44172390b11527557e6250e50&secretkey=83e2f0484edbd2ad6fc9888c1e30ea44&output=json To do this, I am ut ...

Is there a way to incorporate a progress bar into the Java file uploading example?

I'm currently developing a JSP/Servlet web application and I am looking to implement file upload functionality with a progress bar within a Servlet context. Below is an example of uploading a file using JSP and Servlet but without the progress bar fea ...

Looking to bookmark Java links or a similar task?

Apologies for the lackluster title, as I am not well-versed in programming language and struggle to articulate my specific request... Allow me to explain: I frequently need to visit a particular website to conduct research (details below). I attempted usi ...

Recurly.js: Enhancing PHP Integration with Advanced Digital Signatures

I've been working on setting up forms for a recurly implementation and using PHP to generate the signature. Despite following the documentation, searching for examples, and testing various combinations, I'm facing an issue where part of the PHP c ...

Customize the date format of the Datepicker in Angular by implementing a personalized pipe

I am dealing with a datepicker that defaults to the MM/dd/yyyy format, and I need it to adjust based on the user's browser language. For example, if the browser language is English India, then the format should be set to dd/MM/yyyy as shown below. Be ...

Struggling to find a solution for your operating system issue?

We are currently attempting to utilize the markdown-yaml-metadata-parser package for our project. You can find more information about the package here. Within the package, it imports 'os' using the following syntax: const os = require('os ...

Decoding JSON using JavaScript

I am dealing with a webservice that uses RestEasy to return a JSON object with a List element. When I try to parse the results in a JavaScript loop, everything works fine if there are two or more elements in the List. However, if there is only one element, ...

Is there a way to display points on each vertex of my geometry using React, three.js, and Three-React-fiber?

I'm trying to figure out how to utilize the pointsmaterial and points object within three-react-fiber. Currently, I have a custom geometry that I've imported from a .gltf file and I'm rendering it like this: <mesh castShadow recei ...

Django Ajax filter displaying issue on HTML page

I'm uncertain about the correctness of my Ajax implementation. When using Django's built-in tags, the objects I pass through Ajax are not appearing on my template HTML page. view_results.html <div> <input id="search" name="search" t ...

Incorporate various Vue.js components into the main parent component

I am currently utilizing Vue.js to create a user interface for my HTML5 game. I have a scenario where I want to define UI containers that essentially group other UI components and position them on the screen. Here's an example of what I'd like to ...

Modify hyperlink address according to chosen option

Looking to incorporate a select input in Laravel using the latest alpine.js build. Here's what I have in mind: {{ Form::select('dogs', $dogs) }} This utilizes LaravelCollective HTML for streamlined form creation. Once an option is chosen, ...

Converting an Angular JSON encoded array to PHP format

I need to send a JS array to the server in this format: "['id' => ['users'=>[] ]]" In my Angular code, I have an id: var id = '3534534543535'; How can I convert my id to the expected PHP format? ...

Error Message Missing from Google Cloud Function Response

In my Google Cloud function code, I have encountered an issue where the status changes to 400 when there is an error creating a new user. However, on the client side, I always receive an "Error: invalid-argument" message regardless of the actual error from ...

What are some methods to make sure that functions in AngularJS do not run at the same time

I am new to the world of JavaScript and I have encountered a problem with one of my functions. The function is designed to retrieve cached resources, but if the resource is not found in the cache, it makes a call to the back-end. The issue arises when thi ...