angularJS - connect multiple droplist and comboboxes - javascript

I have a form with 2 dropdown-lists and 1 combobox.
Dropdown-list 1 has the 'groups', the second one contains the elements
The combobox contains a collection of data of combined groups and elements.
Example:
<select ng-model="currentCombo" ng-model="currentItem.group"
ng-options="item.label for item in data.subdata.groups"></select>
<select ng-model="currentCombo" ng-model="currentItem.Elements"
ng-options="item.label for item in data.subdata.elements"></select>
<button ng-click="updateCombination()">Update combination</button>
<select multiple ng-model="selectedItem"
ng-options="(item.group.label + ' : ' + item.elements.label) for item in data.combinations"></select>
Now, when I click the button, I add the new combination or, if it exists already, change the current one.
What I'm trying to achieve now is that, when you select an element in the combobox, it autoselects those 2 elements in the 2 separate dropdownlists.
Keep in mind that not all combinations exists: it is possible that a group has no elements yet.
In JS I run this code to add/update a combination:
$scope.updateCombination = function()
{
var isUpdate = false;
for (item in $scope.data['combinations'])
{
if ($scope.data['combinations'][item]['group']['id'] == $scope.currentCombo.group['id'])
{
$scope.data['combinations'][item]['element'] = $scope.currentCombo['element'];
isUpdate = true;
break;
}
}
if (!isUpdate)
$scope.data['combinations'].push($scope.currentCombo);
$scope.currentCombo = "";
}

Related

How to use the value of an input to render specific content on the same page without a page refresh or a form submit in Laravel 8

I am trying to build a student catalog. I have a structure which consists in Classes -> Groups -> Students.
I already have the classes and groups in my database. Each group belongs to a class.
As an example, I go to my Class page and I create class 1. After this, I go to my group page and add a group "A" that has class 1 assigned to it. I can add multiple groups to each class.
Now I want to create a student on my student page. To do this, I want to add the student in a specific group. To be able to chose the group, the admin has to firstly select the class from a select dropdown. After the class gets selected, the next select will render only the groups assigned to the selected class.
My solution for this right now is to set the $_GET super global with the class id that was selected by the user in the first dropdown. I do this via javascript function with window.location.href url change. I set the logic of the group dropdown to look for the $_GET variable before it renders the options.
I don't think this is a clean and good approach as the page is always refreshed when the location is reset and the input values are always reset.
I just want to use whatever the user has selected from the classes dropdown to render the options in the group dropdown. Is there anything that Laravel 8 built in features can do for me regarding this issue?
As a sample of what I am doing right now:
<select name="classes" id="classes" onchange="getClassID()"> // getClassID just changes the location and adds the selected class id to the url as a query string
#php
foreach ($classes as $class) {
if(isset($_GET['classID'])){
if($_GET['classID']*1 === $class->id){
echo " <option value={$class->id} selected>{$class->classes_number}</option>";
} else {
echo " <option value={$class->id}>{$class->classes_number}</option>";
}
} else {
echo " <option value={$class->id}>{$class->classes_number}</option>";
}
}
#endphp
</select>
<script>
function getClassID(){ //this is called whenever the user changes any class in order to get his input and render the options from the below select
let option = document.getElementById("classes").value;
window.location.href='/students/create?classID=' + option;
}
</script>
<select name="group_id" id="group">
#php
// If the user has changed the initial classes select dropdown value, we will
// get all of the groups that have the class that was selected and display them
// as options in this select
if(isset($_GET['classID'])){
$classID = $_GET['classID']*1;
foreach ($groups as $group) {
if ($group->classes_id === $classID) {
echo "<option value={$group->id}>{$group->group_name}</option>";
}
}
}
else {//another code that handles the situation in which all classes are erased}
#endphp
</select>
Images with my form when the user selects different classes and the groups are rendered differently for each selected class:
Instead of reloading the page, you can get the options via api and create the second select on client-side.
var groupIdSelect = document.getElementById('group');
function getClassID(){ //this is called whenever the user changes any class in order to get his input and render the options from the below select
let classID = document.getElementById("classes").value;
fetch('api/students/create?classID=' + classID)
.then((res) => res.json())
.then((groups) => {
for (group of groups) {
if (group.classes_id === classID) {
var option = document.createElement('option');
option.value = group.id
option.textContent = group.group_name;
groupIdSelect.appendChild(option);
}
}
})
}

Jquery option select value matches with values in array

I have a select field with all countries listed. The option val is the country code so for the United States the option value is US.
I have a few products in a list which each have a unique country codes assigned to them in the html such as:
<div class="restricted-items" data-countries="["TR","UA","AE","GB","US"]"></div>
<div class="restricted-items" data-countries="["GB","US"]"></div>
etc
What I am trying to do is that when on change event the option value is US, it finds that value in the array show shows text. The trouble i am having is that the text will show for all classes with "restricted-items"
My code or attempt is:
$(document).on('change', '.fieldset.estimate.select[name="country_id"]', function() {
var blacklistCountries = JSON.parse(jQuery('.restricted-items').attr('data-countries'));
console.log($(this).val());
console.log(blacklistCountries);
if($.inArray($(this).find(':selected').val(), blacklistCountries) > -1){
$('.restricted-items').text('This item cannot be shipped to ' + $(this).find(':selected').attr('data-title'));
} else {
if ($('.restricted-items').text().length > 0) {
$('.restricted-items').empty();
}
}
});
Any help will be great thanks

Loop that will select all elements in a dropdownlist

I went in and created id tags for each dropdown. I tried creating a loop to select each manufacturer in the drop down without having to write 300+ lines of code since there are many options in some of the dropdowns. I tried and couldn't figure out a way. The second drop down for example is "source_manufacturer".
This is what i tried:
var expected = ['COMFORT-AIRE', 'Daewoo', 'GE'];
var els = element.all(by.id('source_manufacturer'));
for (var i = 0; i < expected.length; ++i) {
expect(els.get(i).getText()).toEqual(expected[i]);
}
Here is the html code:
<select id="source_manufacturer" ng-class="{'btn btn-default' : !$root.isMobile.iOS()}" class="form-control ng-valid btn btn-default ng-not-empty ng-touched ng-dirty ng-valid-parse" ng-model="manufacturer" ng-options="m.name for m in manufacturers">
`<option selected="selected" value="object:439" label="COMFORT-AIRE">COMFORT-AIRE</option>
....
<option value="object:443" label="Whirlpool">Whirlpool</option></select>`
This is the error message: Failed: Index out of bound. Trying to access element at index: 1, but there are only 1 elements that match locator By(css selector, *[id="source_manufacturer"]). I want to test if each one can be selected and that it actually changes.
The expected shows every element in the list instead of a single one.
This is how i would go about clicking each individual element in the list:
element(by.id('source_manufacturer')).click().
element(by.cssContainingText('option', 'GE')).click();
First of all, you should make sure you really have multiple select elements with source_manufacturer id. Then, you should be using each() instead of a regular for loop. And, I would use an elegant abstraction over the select-option structure suggested here:
var expected = ['COMFORT-AIRE', 'Daewoo', 'GE']
var selects = element.all(by.id('source_manufacturer'));
selects.each(function (select, index) {
var selectWrapper = SelectWrapper(select);
selectWrapper.selectByPartialText(expected[index]);
expect(selectWrapper.getSelectedOptions().first().getText()).toEqual(expected[index]);
});

get list of selected items from select box in javascript

i am using a multi select box in javascript as given here:
i want to get the list of selected items in the multi select text box (the left list)
what can i do to achieve that?
my select box is as follows:
<select id="userList" class="multiselect" multiple="multiple" name="users[]" style="width: 75px;">
//List
</select>
i guess users[] stores the selected users at a point in time. but i can't figure out how to retrieve that variable.
Doing this will work:
$('[name="user[]"]').val()
PS: You need to have jQuery included in your webpage.
from the demo at http://www.quasipartikel.at/multiselect/, doing $('[name="countries[]"]').val() will give sample output:
["ARM", "AUS", "AUT"]
Get a list of values with jQuery:
var values = $select.find('option:checked').map(function() {
return this.value || this.text;
});
// or $select.val() of course, like lemarc says
// => ['ABC', 'DEF']
var prefix = encodeURIComponent($select.attr('name')) + '=';
var httpQuery = values.length ? prefix + values.map(function() {
return encodeURIComponent(this);
}).join('&' + prefix);
// => users[]=ABC&users[]=DEF
I didn't test it.
This will return array of selected values
$('#userList').val();
DEMO
You can directly target $(".multiselect") Object, by doing this:
$("input[type='submit']").click(function(e){
e.preventDefault();
_selValue = $(".multiselect").val(); //You will have variable of selected values
for(var i=0;i<_selValue.length;i++){
alert(_selValue[i]);
//You can iterate it individually in loop
}
});

JavaScript / jQuery - taking input from 2 drop down identical menus

I have 2 drop down lists, which both hold the same list of teams, one to be used as the home team and one as the away team. At the moment the first drop down list works, when a team is selected from the list, it's id and name is output to the page. But when the other drop down is clicked, nothing happens. So for example the output takes the id and team name and outputs them to the textboxes.
Here is an example of each drop down list and the relevant code below, can anyone help me out?
HTML generated for home team list:
<select id="teamList" style="width: 160px;">
<option></option>
<option id="1362174068837" value="1362174068837" class="teamDropDown">Liverpool</option></select>
HTML generated for away team list:
<select id="teamList" style="width: 160px;">
<option></option>
<option id="1362174068837" value="1362174068837" class="teamDropDown">Liverpool</option>
</select>
JADE template used to generate the HTML (used for both lists):
div#teamDropDownDiv
-if(teamsList.length > 0){
select#teamList(style='width: 160px;')
option
-each team in teamsList
option.teamDropDown(id="#{team.key}",value="#{team.key}") #{team.name}
JavaScript for the page:
Team.initTeamsDD = function(){
$("#teamList").change(function(e){
e.preventDefault();
var teamId = $(this).val();
$.get('/show/team/'+teamId, function(response){
if(response.retStatus === 'success'){
var teamData = response.teamData;
$('#teamId').val(teamData.key);
$('#teamName').val(teamData.name);
} else if(response.retStatus === 'failure'){
}
});
});
The two <select> elements both have the same "id" value, which is "teamList". You should never have two elements with the same "id". Because of this, the on-change event handler is getting attached to only one of them. You should change them to "homeTeamList" and "awayTeamList", and then use:
Team.initTeamsDD = function(){
$("#homeTeamList, #awayTeamList").change(function(e){
...

Categories

Resources