Store the values of the selected options in a JavaScript array

I have 2 select boxes where I can choose options from one box and transfer them to the other. Upon clicking save, the selected values should be stored in an array and passed to the home controller. Although I receive the correct data in an alert message, I encounter an error in the firebug console that I am struggling to resolve. Your assistance in this matter would be greatly appreciated. Below is the error along with the relevant code snippet.

for (var i = 0; i <= PairedSelectBox.options.length; i++) {
    selectedClientChips.push(PairedSelectBox.options[i].value);
    alert("selectedClientChips == " + selectedClientChips);
}

The error displayed in the console is:

TypeError: PairedSelectBox.options[i] is undefined
selectedClientChips.push(PairedSelectBox.options[i].value);

Here is the HTML code:

<table>
    <tr>
        <td>
            <label style="font-size: medium;">Client Chip details</label>
        </td>
    </tr>

    <tr>
        <td>
            <label>Search</label>
            <input type="text" id="searchId">
            <input type="button" value="Go" onclick="getClientChipDetails();"></td>
    </tr>
    <tr>
        <td>
            <label style="font-size: small;">Client-Chip data</label>
        </td>
        <td></td>
        <td>
            <label style="font-size: small">Selected Client-Chip data</label>
        </td>
    </tr>
    <tr>
        <td>
            <select id="MasterSelectBox" name="MasterSelectBox" size="10" multiple="multiple"></select>
        </td>
        <td>
            <button id="btnAdd">> </button>
            <br>
            <button id="btnRemove">< </button>
        </td>

        <td>
            <select id="PairedSelectBox" name="PairedSelectBox" size="10" multiple="multiple">
            </select>
        </td>
    </tr>

</table>

This is the corresponding script:

$(document).ready(function () {

    $('#MasterSelectBox').pairMaster();
    $('#btnAdd').click(function () {
        $('#MasterSelectBox').addSelected('#PairedSelectBox');
    });
    $('#btnRemove').click(function () {
        $('#PairedSelectBox').removeSelected('#MasterSelectBox');
    });
});

Answer №1

Give this a try. I made some changes to your code.

Your HTML Code:

<table>
    <tr><td>Master selection box</td><td>Paired selection box</td></tr>
    <tr>
        <td>
            <select id="MasterSelectBox" name="MasterSelectBox" size="10" multiple="multiple">
                <option value="volvo">Volvo</option>
                <option value="saab">Saab</option>
                <option value="mercedes">Mercedes</option>
                <option value="audi">Audi</option>
            </select>
        </td>
        <td>
            <button id="btnAdd"> > </button><br>
            <button id="btnRemove"> < </button>
        </td>
        <td>
            <select id="PairedSelectBox" name="PairedSelectBox" size="10" multiple="multiple"></select>
        </td>        
    </tr>
</table>
<button id="save">Save</button>
<p id="output"></p>  

Javascript Section:

$(document).ready( function(){ 
    $('#MasterSelectBox').pairMaster();
    $('#btnAdd').click(function(){
        $('#MasterSelectBox').addSelected('#PairedSelectBox');
    });
    $('#btnRemove').click(function(){
        $('#PairedSelectBox').removeSelected('#MasterSelectBox');
    });
    $( "#save" ).click( function( e ) {
        $( "#output" ).empty();
        $.each( $( "#PairedSelectBox" ).val(), function( i, v ) {
            $( "#output" ).append( $( "<span> " + v + " </span>" ) );
        } );
    } );
});

Reminder: Use rawgit.com links for libraries, not raw.githubusercontent.com, when adding scripts to your jsfiddle.

Answer №2

@madhu, I've made updates to your code on jsfiddle and added the following snippet...

$(document).ready( function(){
    var data=[];
    //$('#MasterSelectBox').pairMaster();
    $('#btnAdd').click(function(){
        $("#MasterSelectBox option:selected").each(function () {  
    var selText = $(this).val();  
   data.push(selText);
});      

      $.each(data, function(val, text) {
                    $('#PairedSelectBox').append( $('<option>').text(text).attr('value',text));
                    }); 

    });
    $('#save_btn').click(function(){
        alert("your data is"+JSON.stringify(data));
    });
});

Please review the changes on your jsfiddle link

Answer №3

After some troubleshooting, I realized that I forgot to declare the variable PairedSelectBox before using it in my code. var PairedSelectBox = document.getElementById("PairedSelectBox"); // alert("PairedSelectBox==="+ PairedSelectBox);

 for (var i = 0; i<PairedSelectBox.options.length; i++) {
     selectedClientChips.push(PairedSelectBox.options[i].value);
     //alert("selectedClientChips == " + selectedClientChips); 
     }
 alert("selectedClientChips==="+selectedClientChips);

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

The failover process for PayPal involves seamless transitions to backup systems in the

I am currently assisting a client with a unique architecture setup: Back End Running on Java Server Front End Powered by Proxy (Node JS + Express application) For security reasons, all requests made to the server must pass through the Proxy. We ar ...

Using three.js library from npm to import the THREE.Lut() functionality

After installing three packages from npm, I attempted to invoke: lut = new THREE.Lut( colorMap, numberOfColors ); However, I encountered the error message: "export 'Lut' (imported as 'THREE') was not found in 'three'. Altho ...

Error: ASP.Net MVC Controller Encountered NullReferenceException

A simple bowling game web app involves two text boxes and a submit button. The first text box is for the FirstRoll, and the second text box is for the SecondRoll. Users input two numbers and click the submit button to display a score. Problem: I am enco ...

Obtain the VW/VH coordinates from an onclick action in JavaScript

With this code snippet, you'll be able to retrieve the x and y coordinates of a click in pixels: document.getElementById("game").addEventListener("click", function(event) { console.log(event.clientX, event.clientY); }); However ...

Obtaining JSON data through Ajax following a MySQL query

In the process of setting up my bookshop, I decided to create a cashdesk script. This form includes an ajax dynamic search feature and is specifically designed for use on a local PC, rather than being published on the web. By scanning the EAN code, the fo ...

Generate an embedded iframe displaying a linked code snippet

I manage an online store and once a courier has been dispatched, I send out an email to customers with tracking information for their shipments. To streamline this process, I have implemented an input field (Code provided below). In this field, when a us ...

The most recent version of Autonumeric now permits the inclusion of a decimal point, even if the decimalPlaces parameter

I need to ensure that only whole numbers are allowed in the input textboxes, while also displaying a currency symbol and commas. I am using the most recent version of Autonumeric JS for this purpose. Even after setting the decimalPlaces property to 0, I a ...

Looking for assistance with submitting a form?

Looking for assistance with a JavaScript hack. Since this morning, I've been trying to figure out a simple hack that would enable me to submit a form multiple times. Take a look at this image. https://i.sstatic.net/GffW1.png It's a basic form ...

Is it possible to extract information from a string with regular expressions?

As I sift through a myriad of arbitrary "Header" data in node. Here's an example of what it looks like: _Aa:GA1.1.78037747.867108, 44907=5xyz; Webstorm-a36041d5=9fbb-48e9-b19e-e3f0a3282151; srce=coolernode; nsid=1234; cookie_data=T%3D1; _gat_PP= ...

What's the Deal with MeshLine and Line Thickness in Three.js in 2021?

I was looking to create a curved line in Three.js with a thickness greater than one. After some research, I found that using Three.MeshLine seemed to be the solution. However, I have come across several reports (and experienced it myself) stating that the ...

Creating a straight line on a plane in three.js

In my project, I am tasked with creating numerous flat arrow lines in a 2D plane using Three.js, similar to a navigation map like Google Maps. While I am aware of examples showing fat lines and the meshline package, these options do not meet the specific c ...

Retrieving values from a database using Bootstrap multiselect search option

I am currently utilizing bootstrap-multiselect in my project. I am attempting to retrieve database values through an ajax request in the search feature, but unfortunately, the values are not being appended. Here is my code: $('#example-getting-sta ...

How can I utilize jQuery to add tags in a box?

I have an idea for a feature similar to the Stack Overflow tag insert. My goal is to have a box where I can type in a tag, click 'Add', and see it appear above. Additionally, I want this action to update an array called 'SelectedTags'. ...

The transfer of JSON information from View to Controller yields no value

My goal is to create functionality where users can add and delete JQuery tabs with specific model data, and then save this data to a database. I'm attempting to use an ajax call to send JSON data to the controller, but I am encountering an issue where ...

Creating a notification for specific choices in a dropdown menu

I am working on a form that includes a select element with multiple options. Depending on the option selected, a different form will be displayed. My concern is if a user starts filling out one form and then decides to select another option, I want to add ...

Iterate over the cells within a column and save a particular value into an array

Hello, I'm currently training to become an IT Specialist and my mentor has assigned me a task involving creating a macro for Excel. (I have no prior experience with VBA) The objective is to search a specific column for the value 1 and save all instan ...

Calls to the function are piling up

There is a bootstrap modal that displays a confirmation message. If the 'accept' button is clicked, a function is called with an id. If the 'cancel' or 'close' button is clicked, the modal closes. The problem arises when the m ...

Having difficulty accessing a JSON imported object beyond the FOR loop

I am facing an issue when trying to reference my imported JSON data. The problem arises when I attempt to access the data outside of a FOR loop, resulting in the error message "Uncaught TypeError: Cannot read property 'Tname' of undefined" The f ...

Is there a more efficient method for subtracting a set number of months from a date without having to repeat code?

Trying to develop a function that takes the current date as input using: const currDate = new Date() The goal is to pass this value to a function that subtracts a specific number of months from the current date and returns the result in RFC 3399 fo ...

Tips for troubleshooting in Chrome when working with the webpack, ReactJS, and Babel combination

I've configured webpack-dev-server to act as my development server, bundling all of my source code into a single JavaScript file. While it's working well, I'm having trouble debugging my code in Chrome. I can view my JS source code in the Ch ...