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

Inquiries about utilizing setTimeout with backbone.js and effectively managing timeouts

One of the questions I have is related to clearing timeouts using clearTimeout(content.idTimeout) for a specific idTiemout. But how can I clear all timeouts at once? Here is the model I am working with: var ContentModel = Backbone.Model.extend({ URL: "htt ...

Organize and display a list of contacts alphabetically by the first letter of their

I have a list of contacts that I need help with. Despite searching on Stack Overflow, I couldn't find the answer. Can someone please assist? Thank you. export const rows = [ { id: 1, name: 'Snow', email: 'Jon', co ...

Despite being present in the node_modules folder, the ag-grid-vue module appears to be missing

Currently, I am diligently following the Vue.js AgGrid getting started tutorial step by step: https://www.ag-grid.com/vuejs-grid/ However, upon adding the <script> section and saving my progress, an error promptly appears: ERROR Failed to compile ...

The use of DIV tags allows the element to be displayed in an inline

In my project, I decided to add three div tags. The first two are positioned next to each other with the third div tag placed below them. However, when I tried to insert a slideshow into the first div tag, all of the div tags ended up displaying as "block" ...

Incorporate the xml2js JavaScript library with Angular 2 for enhanced functionality

I've been attempting to utilize xml2js as an XML parser within my Angular 2 (RC 1 with TypeScript) web application. Unfortunately, I've encountered several errors without finding a solution that works. Here is the detailed process I followed: ...

The div smoothly descended from the top of the page to the center under the control of jQuery

I am trying to implement a feature where a div slides down from the top of the page to the center when a button is clicked. However, my current code seems to be causing the div to slide from the bottom instead of the top. Ideally, I want the div to slide ...

Gridsome's createPages and createManagedPages functions do not generate pages that are viewable by users

Within my gridsome.server.js, the code snippet I have is as follows: api.createManagedPages(async ({ createPage }) => { const { data } = await axios.get('https://members-api.parliament.uk/api/Location/Constituency/Search?skip=0&take ...

The attempt to follow or favorite the item at http://127.0.0.1:8000/follow/fav/8/1/ has resulted in a 403

I can't figure out why this error keeps happening. I have a favorite app, and it seems like the ajax functionality is breaking down. The error occurs when I click a button that should be working but isn't functioning properly at the moment. My su ...

JavaScript and AJAX are showing an error message that says: "ReferenceError: x is not

I am currently working on a jQuery function that retrieves the value from a PHP-generated checkbox and sends it through AJAX. The value being sent is always a single word consisting only of letters. Here is the script I have written: <script type="text ...

Getting pictures dynamically from the backend with unspecified file types

Greetings to my fellow Stackoverflow-Users, Lately, I was tasked with the requirement of loading images dynamically from the backend into my application. Up until now, it was always assumed that we would only be dealing with SVG images since there was no ...

The function given to requestAnimationFrame is not being triggered as expected

I have successfully implemented an infinite loop animation using setInterval. However, I want to enhance the performance by switching to requestAnimationFrame(). Unfortunately, the function supplied to requestAnimationFrame() is not being called for some r ...

Sort the results by total count in Mongoose Express Node.js after grouping by id

I have a unique collection of items: { "_id": { "$oid": "5f54b3333367b91bd09f4485" }, "items": [ { "_id": 20, "name": "Turkish Coffee", "price": ...

TypeScript combined with Vue 3: Uncaught ReferenceError - variable has not been declared

At the start of my <script>, I define a variable with type any. Later on, within the same script, I reference this variable in one of my methods. Strangely, although my IDE does not raise any complaints, a runtime error occurs in my console: Referenc ...

The enigmatic dance of Angular and its hidden passcodes

Recently, I've been diving into learning Angular 2 and I'm exploring ways to safeguard the data in my application. I'm curious about how one can prevent data from being accessed on the front end of the app. Could serving the angular app thr ...

Is there a distinction in invoking a service through reference or directly in Dependency Injection?

QUERY: Are there any discernible differences between the two instances of utilizing a factory service? Instance 1: angular.module('ramenBattleNetworkApp') .controller('MainCtrl', function ($scope, Helpers) { var testArray = [1 ...

The absence of the import no longer causes the build to fail

Recently, after an update to the yup dependency in my create react-app project, I noticed that it stopped launching errors for invalid imports. Previously, I would receive the error "module filename has no exported member X" when running react-scripts buil ...

What is the best method for retrieving the selected itemsPerPage in Vuetify's data-table in version 2.0

Recently, I've been struggling to retrieve the selected items-per-page on a Vuetify data-table due to some recent changes. I came across this helpful example: How to set initial 'rows per page' value in Vuetify DataTable component? Here is th ...

Service has not been properly declared

I encountered an issue with AngularJS where I am struggling to import a Service from one module to another. In the Data module, I have a Service named MenuDataService that I need to utilize in the MenuApp module. However, when attempting to do so, I receiv ...

The Jquery append function is limited to the initial ajax request, necessitating a page refresh in order to populate another div with the desired

When making an AJAX request to retrieve a JSON array, upon successful completion another AJAX request is triggered. The retrieved data is then populated into the div of a bootstrap modal using the jQuery append function. Everything functions as expected ...

How can animations be disabled in Angular/Javascript?

I have been assigned the task of developing an Angular component for my company's applications that will include a toggle to disable all animations within the app for accessibility purposes. It is important to note that I am unable to go into each in ...