difficulty encountered when attempting to input multiple values into a single text field

There are four boxes containing values. When clicking on a box, the value should appear in a text field separated by commas if multiple boxes are selected.

<li><a href="javascript:void(0)" onclick="check_stalls('A-14')" id="A-14">A-14</a></li>
    <li><a href="javascript:void(0)" onclick="check_stalls('A-13') id="A-13">A-13</a></li>
    <li><a href="javascript:void(0)" onclick="check_stalls('A-12') id="A-12">A-12</a></li>
    <li><a href="javascript:void(0)" onclick="check_stalls('A-11') id="A-11">A-11</a></li>

<input type="text" name="selected_stals" id="selected_stals" />

function check_stalls(stalno)
{
    alert(stalno);

    document.getElementById(stalno).style.backgroundColor = "#FF0";

    var textbox = document.getElementsByName("selected_stals")[0];
var checkboxes = stalno;

alert(checkboxes);
for (var i = 0; i < checkboxes.length i++) {
    var checkbox = checkboxes[i];
    checkbox.onclick = (function(chk){
        return function() {
            var value = "";
            for (var j = 0; j < checkboxes.length; j++) {
                if (checkboxes[j].checked) {
                    if (value === "") {
                        value += checkboxes[j].value;
                    } else {
                        value += "," + checkboxes[j].value;
                    }
                }
            }
            textbox.value = value;
        }
    })(textbox);
}  


}

I attempted to implement this using checkboxes but encountered some issues...

Answer №1

Code Example

<ul><li><a href="#"  id="A-14">A-14</a></li>
    <li ><a href="#" id="A-13">A-13</a></li>
    <li ><a href="#" id="A-12">A-12</a></li>
    <li ><a href="#" id="A-11">A-11</a></li></ul>

<input type="text" name="selected_stals" id="selected_stals" />

JavaScript Function

$(function(){
    $('a').click(function(){
        var val = $(this).text();
        var text = $('#selected_stals').val();
        var newText = val;
        if(text != ""){
            newText += "," + text;
        }
        $('#selected_stals').val(newText);
    });
})

Visit this link for live example.

Enjoy exploring the code!

Answer №2

Since you've tagged your post with "jquery", I'm assuming you're using jQuery. If I understand correctly, here's how I would approach the solution:

<ul id="boxes">
   <li><a href="#" id="A-14">A-14</a></li>
   <li><a href="#" id="A-13">A-13</a></li>
   <li><a href="#" id="A-12">A-12</a></li>
   <li><a href="#" id="A-11">A-11</a></li>
</ul>

<input type="text" name="selected_stals" id="selected_stals" />

You can include this script along with your other scripts:

$("#boxes a").on("click", function(e){
    if($("#selected_stals").val() == ""){
        $("#selected_stals").val($(this).html());
    }else{
        $("#selected_stals").val($("#selected_stals").val()
            + ", " + $(this).html());
    }
});

Check out this working JSFiddle for reference.

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

What is the best way to utilize an AngularJS directive to send a POST request with all parameters from a form?

I have created a custom AngularJS form with Stripe integration using a directive. You can view the Fiddle for this project here: https://jsfiddle.net/u5h1uece/. HTML: <body ng-app="angularjs-starter"> <script src="https://js.stripe.com/v3/"> ...

The attempt to initiate the MongoDB server was unsuccessful. dbexit reported an error with code 48 within the MongoDB system

After updating MongoDB, I encountered an error. I attempted to restart the MongoDB service, but the error persists. ...

Submitting option values in AngularJS: A step-by-step guide

Why does AngularJS ng-options use label for value instead of just the value itself? Here is my current code: <select ng-model="gameDay" ng-options="gameDay for gameDay in gameDayOptions"> This currently displays: <select ng-model="gameDay" ng- ...

Achieving accurate JSON output from Elasticsearch's autosuggest feature can be

Running my node.js server involves sending queries to an elasticsearch instance. I have a JSON example of the query's output: { "took": 2, "timed_out": false, "_shards": { "total": 5, "successful": 5, "failed": 0 ...

Encountering issues with Visual Studio Code following the integration of the MongoDB API Mongoose into my code

As I delve into the world of web development, I have been exploring databases with MongoDB Atlas and mongoose. Interestingly, my debugging process has hit a bump when using the node.js(legacy) debugger in VS code after importing mongoose with const mongoos ...

Create a dynamic list selector for WebOS using AJAX to populate options from a JSON response

Having trouble developing an application that retrieves MySQL database responses using Ajax post and updates a list selector with the data. The list is currently displaying empty results, can anyone provide some assistance please... JavaScript code: Seco ...

Tips for obtaining the state of a local variable in a Vue method:

How do I access the state of a local variable within a method in Vue? I am looking to set a specific value for the dialog in order to open the popUp. After loading the data, my goal is to open the popUp by using this porting method. import { mapState, m ...

Error encountered when attempting to insert data into a PostgreSQL database using Node.js and Sequelize

I'm currently using the node sequelize library to handle data insertion in a postgress database. Below is the user model defined in the Users.ts file: export class User extends Sequelize.Model { public id!: number; public name: string; public ...

What is the best way to implement multiple filters on the data of a Vue component?

I am facing a challenge in implementing multiple filters in a component. For instance, users should be able to choose a category and have the results filtered accordingly. Moreover, with a search filter already in place, I am looking for a way to combine i ...

Looking to target an element using a cssSelector. What is the best way to achieve this?

Below are the CSS Selector codes I am using: driver.findElement(By.cssSelector("button[class='btn-link'][data-sugg-technik='append_numbers']")).click(); driver.findElement(By.cssSelector("button[class='btn-link'][data-sugg- ...

How to deactivate the <a> tag with Ant Design UI Library

Is there a method in the antd UI library to disable a link? The disabled attribute is not supported by the a tag according to MDN. This code snippet works in React but the link remains clickable when using Next.js. <Tooltip title={tooltip}> <a ...

submit the data to the database

How can I successfully pass the value from the Ajax code to the database in this program aimed at displaying user details? There seems to be an error in the code for passing the value. What steps should I take to rectify this issue? function showUser() ...

The variable is constantly reverting back to its initial value

Here is the code snippet: function send() { var nop = 6; var send_this = { nop: nop }; $.ajax({ type: "GET", data: send_this, url: "example.com", success: function(r) { ...

Tips for preventing the ng-click event of a table row from being triggered when you specifically want to activate the ng-click event of a checkbox

So, I've got this situation where when clicking on a Table Row, it opens a modal thanks to ng-click. <tr ng-repeat="cpPortfolioItem in cpPortfolioTitles" ng-click="viewIndividualDetailsByTitle(cpPortfolioItem)"> But now, there&apos ...

Error Encountered While Submitting Email Form

I'm having trouble with my email submission form on my website. I've checked the code and it seems fine, but for some reason, the submissions are not going through successfully. Even when bypassing the JavaScript and directly using the PHP script ...

Retrieve the desired element from an array when a button is clicked

When I click on the button, I need to update an object in an array. However, I am facing difficulties selecting the object that was clicked. For better readability, here is the link to my GitHub repository: https://github.com/Azciop/BernamontSteven_P7_V2 ...

Tips on implementing session control using Ajax and PHP

When trying to login using JavaScript in a web-service created with Cake PHP, everything works fine with a common request (non-ajax). However, when utilizing the code below for the countUpdates after logging in, a 403 forbidden error is encountered. The AJ ...

Recursive React components. String iteration enhancement

In my React app, I am trying to create a string hierarchy from an object. The object structure is like this: { name: 'name1', parent:{ name: 'name2', parent:{ name: 'name3', parent: null }}} My plan is to use a state variable ...

Unable to resubmit form via ajax more than once

Greetings to all, I seem to be encountering some issues with a supposedly simple form submission using ajax. Upon the initial submission of the form by the user, everything proceeds smoothly: The content within the div changes as expected and the PHP proc ...

Calculating JS functions before images are loaded

Following up on a previous question, I am utilizing JavaScript code from another article to position a "content" div relative to a fixed div in my project. However, the issue arises when the positioning of the "content" div is calculated only after all the ...