Generate Select dropdown menus and set their values dynamically

Within the angular app.js file, I am dynamically populating a form with multiple select boxes, each having a unique id. How can I retrieve the selected values from these select boxes within the controller?

A variable has been added:

$scope.sibling_type = {};

Javascript code for loading the select box:

$scope.linkSiblingFinish = function(sibling){
   var str_siblingtype = "<div class='col-sm-2' style='margin-bottom:15px'>" +
     "<select ng-model='sibling_type[" + sibling.id + "]' class='form-control' id='sibling_type_"+sibling.id+"'>" +
       "<option class='ng-binding ng-scope' value='1'>Sister->Brother</option>" +
       "<option class='ng-binding ng-scope' value='2'>Brother->Sister</option>" +
       "<option class='ng-binding ng-scope' value='3'>Sister->Sister</option>" +
       "<option class='ng-binding ng-scope' value='4'>Brother->Brother</option>" +
     "</select></div>";

    document.getElementById('div_siblings').innerHTML = str_siblingtype;
}

The above script will be executed on a button click, passing a different 'id' to the 'sibling' parameter every time it is called. Assuming it's called twice with the ids '23' and '24', two select boxes will be created: 'sibling_type_23' and 'sibling_type_24'.

For the submit button:

$scope.saveSibling = function(data){
    dataFactory.httpRequest('index.php/students/sibling/'+$scope.form.id,'POST',{},$scope.form).then(function(data) {
    });
}

How can I bind/assign the option values so that when the form is submitted, I can access the selected options from those select boxes within the Laravel controller?

Answer №1

Here's a unique method you can try:

  1. Start by setting up a new 'sibling_type' scope in your controller.

    $scope.sibling_type = {};
    
  2. Then, adjust the ng-model for all dynamic selects within linkSiblingFinish as follows:

    "<select ng-model='sibling_type[" + sibling.id + "]' 
             class='form-control' id='sibling_type_"+sibling.id+"'>" +
    
  3. Upon form submission, retrieve the chosen options from these select boxes like this:

    var sibling_type_23 = $scope.sibling_type['23'];
    var sibling_type_24 = $scope.sibling_type['24'];
    

See it in action here:

const app = angular.module('myApp', []);
app.controller('AppCtrl', function ($scope) {
  $scope.siblings = [{id: 23,name: 'Sibling 23'},{id: 24,name: 'Sibling 24'}];
  $scope.sibling_type = {};
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.7.5/angular.min.js"></script>
<div ng-app="myApp">
  <div ng-controller="AppCtrl">
    <table border="0" cellpadding="0" cellspacing="0" width="100%">
      <tr ng-repeat="sibling in siblings">
        <td>{{sibling.name}}:</td>
        <td><input type="text" ng-model="sibling_type[sibling.id]" placeholder='Type here..' /></td>
      </tr>
    </table>
    <pre>{{sibling_type | json }}</pre>
  </div>
</div>

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 jQuery ajax request hangs indefinitely without triggering success or error callbacks

I have a jQuery ajax request to the server that triggers a redirect to a second page upon completion. It usually works fine, but in cases where the server response is delayed (e.g. 10 minutes), the callback function may not be executed, leaving the request ...

What is the process for creating a symbolic link from a project's node_modules directory?

Recently, I've been learning how to build a Password Manager using React, Node.js, and MYSQL by following a tutorial. However, I encountered an issue where the file /EncryptionHandler was located outside of the src/ directory of my project. Even thoug ...

Guide to shuffling an array with a simple click of a button

To simplify, I have an array that I would like to randomize by clicking a button. Once randomized, I want to display the first result from the array with another button. The array is currently randomized when opened in Chrome, and checking the results in t ...

The delay in loading HTML content using FOSJsRoutingBundle and Ajax for a specific route parameter (ID)

I'm using FOSjSrouting in my symfony2.7 project. This is the code in my html.twig view: <table> <!--table header code ...etc... --> <tbody> {% for currentData in arrayData %} <tr> <td>{{ currentData. ...

Sending information from Vue to Express for processing

Is there a way to pass data from Vue to an express server? For example, in the scenario below, I am looking to send the data logged in my Vue function to the "id" variable on the server side. expressApp.post('/delete' , function (request, respons ...

JS if clause fails to return true as expected

Here is my setup: <div id="user_input">...</div> And a button: <input type="button" id="panel_button">...</button> Using a selector: function $(id) { return document.querySelector(id); } With an event handler: var button_ ...

When I trigger a click event, it doesn't return anything, however, the function works perfectly when I execute a load event

I am having trouble displaying a random word from an array on my webpage. Whenever I click the button, it shows undefined and the console.log of randIndex gives me NaN. I've been trying to solve this issue but I can't seem to figure out what&apo ...

Tips for accessing child elements of a select tag after dynamically loading option tags using ajax

Greetings! Here is the select tag I have in my HTML: <select class="form-control city-select"></select> Below is the script that loads options into the select tag using a POST method: $.post('../select-city.php',{id: id_pro ...

Bidirectional data binding in the Vue 3 composition API

Currently, I am in the process of transitioning from the options API to the composition API in Vue. Within the code block below, I am attempting to implement two-way binding. I am utilizing the ant-design-vue library for a slider input and trying to bind ...

Clear SELECT After Submission

I have a jQuery script and need a function to reset the SELECT input after it has been submitted. <script> $(document).ready(function() { //elements var progressbox = $("#progressbox"); var progressbar = $("#progressbar"); var statustxt = ...

Discovering the active controllers in current AngularJS implementation

Is there a method to obtain a current list of active controllers? I have an object within my factory and a controller named "myController". Thus, I want to set myFactory.object={} (empty this object) if the myController is no longer connected to the modu ...

Utilize the Feefo JSON data and convert it to a JavaScript array for rendering as an HTML

Currently diving into the world of Javascript and JSON, but feeling a bit overwhelmed by it all. Attempting to pull data from a JSON array, I've managed to reach this stage $(function(){ var $reviews = $('#reviews'); $.ajax({ ...

Cleaning up unwanted objects in THREE.js webGL

Our app utilizes THREE.js to showcase 3D body meshes. We have a special object named MeshViewer that manages the rendering process; within the initialize method, we establish this.renderer = new THREE.WebGLRenderer({ antialias: true, preserveDrawingBu ...

Removing the pound sign from the URL in location hash

function updateView(category) { console.log( window.location.hash ); if (location.hash !== ""){ //convert #3 to 3. //load video based on id //myArray[sanitizedHash]; } else { updateCategoryLabel(category); currentList = updateVi ...

Exploring the concept of promises in node.js for recursive functions

I'm attempting to use recursive calls in order to fetch data from redis, halting and returning when the members return null. My data is inserted as shown below: SADD parents.<name> <parent1> <parent2> SADD parents.<parent1> & ...

Using Jquery to duplicate a row from one table and insert it into another table

Recently, I've dived into the world of jQuery and JavaScript with the goal of creating a simple app. The main functionality I'm trying to implement is the ability to copy a row from one table to another and then delete the original row when a but ...

A warning message has been triggered: 'Script Alert Error - Object

I've been putting in hours on a SUP project that requires some tweaking and I keep running into the issue Script Alert Error: Object expected The code I've added is: $('#bottomOfStart_ScreenForm').before('<div style="display: ...

Tips for clearing a text box on an AngularJS page when clicking a link within the page

On my HTML page, I have a search box and various category links. When a user enters text in the search box, I want to display: p in Products | filter {searchedText} If a user clicks on a category link, I want to display: p in Products | filter {categor ...

What is the best way to determine the location of just one element?

I am currently working on a rating application where only the selected circle should remain green, not all of them. $('#rating-container').click(function () { var element = $('#target'); var container = $('#rating-containe ...

Transferring a PHP variable to a different PHP script through AJAX

I am facing an issue with displaying data stored in a MySQL table inside div elements. Each div with the class content-full is created based on the data in the database. However, when I click on any of these divs, the content associated with the last div i ...