Utilizing a singular JavaScript method across various form interfaces

I seem to be facing a bit of a challenge with a task I've been working on.

My goal is to have multiple forms (six in total) utilize a JavaScript method that I have created. These forms contain text input values which need to be checked, then passed to a PHP file where AJAX is used to update the page with either a confirmation or an error message.

For this illustration, I'll focus on just two forms. Here they are:

<div class="trade_info_1">
            <h2>Market #1</h2>
            <form action="" method="POST">
                <ul>
                    <li>
                        <label for="market_1">Market: </label><input type="text" name="market_1" id="market_1" />
                    </li>
                    <li>
                        <button type="button" name="button1" id="button1" onclick="check_update_selection()">Update Market!</button>
                    </li>
                </ul>
                <input type="hidden" name="market_number" id="market_number" value="1" />
                <div id="market_1_output">output</div>
            </form>
        </div>

        <div class="trade_info_2">
            <h2>Market #2</h2>
            <form action="" method="POST">
                <ul>
                    <li>
                        <label for="market_2">Market: </label><input type="text" name="market_2" id="market_2" />
                    </li>
                    <li>
                        <button type="button" name="button2" id="button2" onclick="check_update_selection()">Update Market!</button>
                    </li>
                </ul>
                <input type="hidden" name="market_number" id="market_number" value="2" />
                <div id="market_2_output">output</div>
            </form>
        </div>

The next step involves using AJAX to update the page. Below is the existing JavaScript method:

function check_update_selection() 
 {
if (window.XMLHttpRequest) 
{
    xhr = new XMLHttpRequest();
}
else if (window.ActiveXObject) 
{
    xhr = new ActiveXObject("Microsoft.XMLHTTP");
}

console.log('Market value: ' + document.getElementById('market_number').value);

if(document.getElementById('market_number').value == 1)
{
    var market = document.getElementById('market_1').value;;
    var market_number = 1;
    var html_element = 'market_1';
}
else if(document.getElementById('market_number').value == 2)
{
    var market = document.getElementById('market_1').value;
    var market_number = 2;
    var html_element = 'market_2';
}

xhr.open('POST', 'update_market.php');
xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded; charset=UTF-8');
var obj = {market: market};
xhr.send("data=" + JSON.stringify(obj));
xhr.onreadystatechange=function() 
{
    if (xhr.readyState==4) 
    {
        if(market_number == 1)
        {
            document.getElementById("market_1_output").innerHTML = xhr.responseText;
        }
        else if(market_number == 2)
        {
            document.getElementById("market_2_output").innerHTML = xhr.responseText;
        }
    }
}

I won't delve into the PHP code as all it does is echo the word "TEST".

The functionality works flawlessly for the first form. However, there seems to be an issue with the second form, as it updates the data from the first form instead. Upon inspecting with console.log(), I noticed that every time I submit the second form, it submits the fields from the first form.

Am I going about this correctly, or is there something important I may have overlooked?

Additionally, I'm currently learning JavaScript, so my expertise in the language isn't extensive. Feel free to point out any errors I may have made.

Thank you for taking the time to read this.

Answer №1

Avoid having two elements on the same page with identical IDs (like market_number):

<input type="hidden" name="market_number" id="market_number" value="2" />

An improved approach would be to pass a parameter to the main function check_update_selection and then invoke it with that parameter from each form:

function check_update_selection(number)

In your HTML, simply call it with the appropriate number:

onclick="check_update_selection(1)"
onclick="check_update_selection(2)"

Answer №2

It is not advisable to have multiple forms on a single page that point to the same action. Each element's ID should be distinctive and unique.

For novice developers, validating HTML using the W3C validator can provide valuable learning experiences in web development.

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

Prevent duplicating ReactJs when using Gulp: A guide

My current project involves using ReactJS as the view library for client-side rendering. Additionally, I am utilizing a lot of components from Material-UI in my application. One challenge that I have encountered is the need to use gulp for setting up brows ...

What are the steps for adding node packages to sublime text?

Is there a way to install node packages directly from Sublime Text instead of using the command line? If so, what is the process for doing this? I'm not referring to Package Control; I'm specifically interested in installing npm packages like th ...

Why does jQuery's each function struggle to retrieve the width of hidden elements?

Why is it difficult to obtain the width of hidden elements? Here is my code: .hidden { display: none; } <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.0/jquery.min.js"></script> <ul class="navbar-items"> <li> ...

The reason why Express is not directing to the static React build files is due to the absence of a specific URL slug

The Scenario Currently, I'm in the process of developing a React application that is being served statically through Express. To clarify, the React app is constructed using npm run build and the resulting static files are stored within the build/ ...

How to break down JSON into individual elements using JavaScript

{ "name": "Sophia", "age": "Unknown", "heroes": ["Batman", "Superman", "Wonder Woman"], "sidekicks": [ { "name": "Robin" }, { "name": "Flash Gordon" }, { "name": "Bucky Barnes" } ...

Using select tags in conjunction with JavaScript can add dynamic functionality to your website

I've been working on adding dropdown menus to my website and have been using code similar to this: <select> <option value="volvo">Volvo</option> <option value="saab">Saab</option> <option value="opel">Opel</opti ...

Fixed bar on top, revealed only when the scroll attempts to conceal it

I have placed a menu on the top section of my website, but not at the very top. I would like it to stick to the top of the page when the user scrolls down and disappears from view. However, if the title is still visible, I want the menu to remain below it ...

Conceal the cursor within a NodeJS blessed application

I am struggling to hide the cursor in my app. I have attempted various methods like: cursor: { color: "black", blink: false, artificial: true, }, I even tried using the following code inside the screen object, but it didn't work: v ...

Verify that all keys of an object are present as values in an array of objects

Imagine having two entities like the following: const obj1 = {key1: "", key2: "", key3: ""}; const array2 = [ { name: "key1", }] Is there a way to verify if array2 contains an object with the same name as ea ...

Techniques for verifying phone numbers from various countries

The number of digits in a mobile number differs from country to country. I have tried using regular expressions, however, for example, India allows 10 digits, but this does not validate UAE, where the number of digits can range from 7 to 9. ...

What is the process for including echo HTML field in the WooCommerce order view?

I have successfully added HTML input fields within functions.php. However, these echoed fields are not displaying in WooCommerce orders after placing an order. I am looking for a way to include the values and labels of these fields in the orders view wit ...

When utilizing jQuery, I implemented this code but it does not display anything. I am unsure of the error within the code

When using jQuery, I implemented the following code snippet but it doesn't display anything. What could be causing this issue? // $.ajax({ // URL:"https://dog.ceo/api/breeds/image/random", // method:"GET", // ...

using javascript to target a specific css selector attribute

I have a CSS file with the following code: .datagrid table tbody td { color: #00496B; border-left: 1px solid #E1EEF4; font-size: 16px ;font-weight: normal; } Is there a way to use JavaScript to dynamically change the font size? The code below worked ...

"Enhance Your Website with jQuery's Dynamic Multi-Animation

I'm facing an issue with my website where, upon clicking the contact link in the navigation bar, a contact box slides down and the navigation bar moves below it. However, when the contact link is clicked again to hide the contact box, the navigation b ...

Encountering a [$injector:modulerr] error while attempting to include modules in ZURB Foundation for Apps

I am currently working on a project that involves specific authentication which is functioning well in Ionic. My task now is to incorporate the same authentication system into the admin panel exclusively for web devices. I have already completed the instal ...

Utilize JavaScript to retrieve data from a JSON document

To extract information from a .json file in node.js, the require function is used. I'm currently developing an Artificial Neural Network that utilizes this code to fetch data from the data.json file. const fs = require('fs'); const json = ...

Is there a way for me to retrieve the information within this function? It seems like it may be a promise, but I am uncertain

I need help extracting the data from doc.data and sending it to another component based on the dropdown selection. It appears that the data is in promise format, and despite trying async/await, I am struggling to access it. Can anyone guide me on how to ...

Accessing the jQuery Ajax success variable

I have a PHP function that returns an array with an element error containing the value 'ERR': var updatePaymentType = function(plan_pt_id, pt_id){ var error = null; var data = new Object() data["function"] = "update"; ...

Include vue-videobg in Vuetify using CDN without the need for webpack

I am trying to integrate vue-videobg into vuetify using a CDN without any additional requirements like "magic_videobg_to_install.java.css.js.htm" <!DOCTYPE html> <html> <head> <link href="https://fonts.googleapis.com/css?family=R ...

Unable to access contextual values in NextJS

When attempting to retrieve values from the context API, I am encountering issues where I receive a default value (without the updates made during the context call) and an undefined value (which should receive a value in the context provider). sortListCont ...