Remove selected option from select list - select

I've made a select menu with html/css and js.
All works well but now I try to remove the selected option from the dropdown list if selected and nothing works for me.
All things I found on the web used jquery and I must use vanilla js.
How could I do that ? Have you an advice ?
Here's my code:
<div class="custom-select">
<label id="selected-category-container" for="sorted-menu" class="sorted_title">Trier par :</label>
<select id="select_category">
<option value="1">Popularité</option>
<option value="2">Date</option>
<option value="3">Titre</option>
</select>
</div>
function removeOptions () {
const listOptions = listItems.options
const listLength = listItems.options.length
console.log(listOptions[1].selected)
let i = 0
for (i = listLength - 1; i >= 0; i--) {
if (listOptions[i].selected) {
listItems.remove(i)
}
}
}

Related

Can the values in local storage be used to verify age?

I am looking for some help with my verification code. I am looking for a simple method to verify two ages. There is a "from age" and a "to age". I need to make sure that the user selects the ages properly. The "from age" should be younger than the "to_age. I made a script and it kind of works. The problem is it does not work consistently. I need it to check, when you select the "from_age" dropdown as well as the "to_age" dropdown. This one seems to only work with one of the dropdowns and one time through. It does not work when the page loads and it sometimes doesn't work at all. I tried two options but neither worked. I tried to use localstorage values since another script I have loads the keys and values on change very well. Or I need to try to fix this version which uses the values in the options dropdown. I am not sure which would work better, but I am thinking the localstorage values are the better choice.
I have tried to use the values associated with the keys in localstorage but I failed on getting it to work. The method using the values in the select/options works but works poorly. Please excuse me if I made any mistakes condensing the code for this question. Thanks
jQuery
$(function() {
$('.agefrom_selection').change(function () {
var quantity_1 = parseInt($('.agefrom_selection').val());
var quantity_2 = parseInt($('.ageto_selection').val());
if ( quantity_1 > quantity_2 ) {
$('.age_warning').addClass('show_age_warning')
}
else {
$('.age_warning').removeClass('show_age_warning')
}
});
});
CSS
.age_warning {
display: none;
}
.age_warning.show_age_warning {
display: block;
position: relative;
float: right;
font-size: 12px;
color: #ff0000;
}
html
<form id="ageselection" method="post" autocomplete="off">
<fieldset>
<ul class="age_preference_text_box fl">
<li><label class="from_to_age_text">from </label>
<select class="age_text agefrom_selection">
<option value="18" selected>18</option>
<option value="19">19</option>
<option value="20">20</option>
<option value="21">21</option>
<option value="22">22</option>
</select>
</li>
<li><label class="from_to_age_text">from </label>
<p class="age_warning"> "to" age must be equal <br>or higher than "from" age</p>
<select class="age_text ageto_selection">
<option value="18" selected>18</option>
<option value="19">19</option>
<option value="20">20</option>
<option value="21">21</option>
<option value="22">22</option>
</select>
</li>
</ul>
</fieldset>
</form>
I expected the warning to show on every instance(or disappear). If you change the from_age dropdown, when you change the to_age dropdown, when you modify either dropdown, if you refresh the page, and if you manipulate any dropdown after a page refresh. My code is poorly written and does not work as expected.
I figured it out. The function was only written on one of the dropdown selectors. It needed to be written for both dropdown selectors. The answer will be something like:
$(function() {
$('.agefrom_selection').change(function () {
var quantity_1 = parseInt($('.agefrom_selection').val());
var quantity_2 = parseInt($('.ageto_selection').val());
if ( quantity_1 > quantity_2 ) {
$('.age_warning').addClass('show_age_warning')
}
else {
$('.age_warning').removeClass('show_age_warning')
}
});
$('.ageto_selection').change(function () {
var quantity_1 = parseInt($('.agefrom_selection').val());
var quantity_2 = parseInt($('.ageto_selection').val());
if ( quantity_1 > quantity_2 ) {
$('.age_warning').addClass('show_age_warning')
}
else {
$('.age_warning').removeClass('show_age_warning')
}
});
If anybody else can come up with something better, I am very willing to listen. Thanks

Angular cast select value to int

I have a form with different selects like :
<select [(ngModel)]="selected.isConnected" (ngModelChange)="formChanged()" name="etat" id="etat" class="form-control">
<option value="0">Not connected</option>
<option value="1">Connected</option>
</select>
My backend expect to receive an int in the "isConnected" attribute. Unfortunately as soon as I change the value of the select the attribute is cast to a string :
{
isConnected : "0", // 0 expected
}
For standard <input> I could use type="number" but for a <select> I'm clueless.
Is there a way to force angular 2 to cast the data to int ?
Use [ngValue] instead of "value":
<select [(ngModel)]="selected.isConnected" id="etat">
<option [ngValue]="0">Not connected</option>
<option [ngValue]="1">Connected</option>
</select>
If you want cast it within formChanged() method (Which you haven't provided yet).
You should use + symbol as shown below,
formChanged(): void {
selected.isConnected = +selected.isConnected;
...
}
No, sadly you're forced to parse it on your own in the formChanged() method, since you always get a string back from the select.
You could try it with something like this:
formChanged(): void {
selected.isConnected = parseInt(selected.isConnected);
// ...
}
You can send a Number variable to select and assign the value for that select element. Then if you want to capture the value when it changes, you can add (change) event to select and retrieve the value as shown below.
import { Component } from '#angular/core';
#Component({
selector: 'my-app',
template: `<select value="{{isConnected}}" (change)="printConnected($event.target.value)" name="etat" id="etat" class="form-control">
<option value="0">Not connected</option>
<option value="1">Connected</option>
</select>
<div *ngIf="changed">You've selected {{isConnected}}<div>`
})
export class AppComponent {
isConnected : number = 1;
changed : boolean = false;
printConnected(value){
this.isConnected = value;
this.changed=true;
}
}
You can view an example at http://plnkr.co/edit/xO2mrTdpTGufkgXqdhYD?p=preview
I am using reactive bindings and do not want to use [(ngModel)]. Instead I created a piped observable that uses JSON.parse(value) (because +value doesn't handle "null"):
*.component.html:
<div class="col-lg-4 form-group">
<label>Group Type</label>
<select class="form-control" (change)="groupType$.next($event.target.value)">
<option [value]="null"></option>
<option *ngFor="let groupType of filterData.groupTypes" [value]="groupType.id">{{groupType.label}}</option>
</select>
</div>
<div class="col-lg-4 form-group" *ngIf="filteredGroups$ | async as groupOptions">
<label>Group</label>
<select class="form-control" (change)="group$.next($event.target.value)">
<option [value]="null"></option>
<option *ngFor="let group of groupOptions" [value]="group.id">{{group.label}}</option>
</select>
</div>
<div class="col-lg-4 form-group">
<label>Status</label>
<select class="form-control" (change)="status$.next($event.target.value)">
<option [value]="null"></option>
<option *ngFor="let status of filterData.statuses" [value]="status.id">{{status.label}}</option>
</select>
</div>
*.component.ts:
group$ = new BehaviorSubject<string>(null);
groupId$ = this.group$.pipe(
map((groupId: string) => JSON.parse(groupId) as number)
);
groupType$ = new BehaviorSubject<string>(null);
groupTypeId$ = this.groupType$.pipe(
map((typeId: string) => JSON.parse(typeId) as number)
);
status$ = new BehaviorSubject<string>(null);
statusId$ = this.status$.pipe(
map((statusId: string) => JSON.parse(statusId) as number)
);
[ngValue] is intended for objects. It generates an artificial option value even for numeric constants. For those who might be concerned about tests or readability, you can expand two way binding microsyntax
<select [ngModel]="selected.isConnected"
(ngModelChange)="selected.isConnected=$event && +$event" id="etat">
<option value="0">Not connected</option>
<option value="1">Connected</option>
</select>

Value of <select><option> coming back as string

Is there any way to have the value of an <option> to be set to an actual integer? I have the following html code:
<select id="proteinperc" onchange="setMacrosProtein()">
<option value="0" selected>0%</option>
<option value="5">5%</option>
<option value="10">10%</option>
<option value="15">15%</option>
<option value="20">20%</option>
<option value="25">25%</option>
<option value="30">30%</option>
<option value="35">35%</option>
<option value="40">40%(Rec.)</option>
<option value="45">45%</option>
<option value="50">50%</option>
<option value="55">55%</option>
<option value="60">60%</option>
<option value="65">65%</option>
<option value="70">70%</option>
<option value="75">75%</option>
<option value="80">80%</option>
<option value="85">85%</option>
<option value="90">90%</option>
<option value="95">95%</option>
<option value="100">100%</option>
</select>
Then I have the script below that is trying to access these option values and perform calculations using them. The problem is that when I do any calculations with them, all I get is string concatenation or strange values.
function setMacrosProtein() {
myProtein = document.getElementById("proteinperc").value;
var removeValue = 101 - (myProtein + myFats + myCarbs);
alert(removeValue); // Alert here just for testing the first calculation.
var x = document.getElementById("fatperc").options.length;
for (i = 0; i < x; i++) {
// Check fatperc
if (document.getElementById("fatperc").options[i].value + myFats >= removeValue) {
document.getElementById("fatperc").options[i].disabled = true;
} else if (document.getElementById("fatperc").options[i].value + myFats < removeValue) {
document.getElementById("fatperc").options[i].disabled = false;
}
// Check carbperc
if (document.getElementById("carbperc").options[i].value + myCarbs >= removeValue) {
document.getElementById("carbperc").options[i].disabled = true;
} else if (document.getElementById("carbperc").options[i].value + myCarbs < removeValue) {
document.getElementById("carbperc").options[i].disabled = false;
}
}
//setCals();
}
If there is no way to return an integer from an option value, I do have a workaround in mind but with a small issue. I could set up a new array with mirroring values to the options list, ie: array[0] would be equal to option[0] and I could check against the array in my if statements.
However, how would I set a variable to the currently selected option this way? How do I reference the current selected option's position in the option array to get the mirrored position in my newly created array? To clarify, if the selected option is currently option[4], how do I reference its position to then pull array[4]'s value?
You could use parseInt() to get the int value from it like this:
myProtein = parseInt(document.getElementById("proteinperc").value);
In javascript file try to use parseInt(...).
Use the unary operator +. Easier than parseInt(). Simply put a plus in front of what you'd like to convert to a number.
Example:
<select id="movie">
<option value="10">Casablanca ($10)</option>
<option value="12">Rear Window ($12)</option>
<option value="8">Vertigo ($8)</option>
<option value="9">Rosemary's Baby ($9)</option>
</select>
const movieSelect = document.getElementById('movie');
const ticketPrice = +movieSelect.value;

CodeIgniter: Multi-select input isn't able to select multiple values

Ironically, form_multiselect() I created didn't work for me. Actually it was created but I couldn't select multiple options. I followed the instructions on the user guide but still not functioning like a multi-select although it looks like one. Any silly mistakes I've made?
This is what the code looks like in web browser's inspect element feature:
<select name="meal_type[]" id="meal_type_id" onfocus="calculateTotal();" onblur="calculateTotal();" onchange="calculateTotal();" multiple="multiple">
<option value="Breakfast_1000">Breakfast</option>
<option value="Dinner_2500">Dinner</option>
<option value="Lunch_2000">Lunch</option>
</select>
This is what I coded in View:
<div class="control-group">
<label for="meal_type" class="control-label">
<i class="icon-glass"></i> Meal Type:
</label>
<div class="controls">
<?php
$js = 'id="meal_type_id" onFocus="calculateTotal();" onBlur="calculateTotal();" onChange="calculateTotal();"';
echo form_multiselect('meal_type[]', $mt_name, set_value('meal_type'), $js);
?>
<?php echo form_error('meal_type'); ?>
</div>
JAVASCRIPT
function calculateTotal() {
var room_type_id = document.getElementById('room_type_id').value;
var room_type_cost = room_type_id.split("_");
var meal_type_id = document.getElementById('meal_type_id').value;
var meal_type_cost = meal_type_id.split("_");
var ext_beds_id = document.getElementById('ext_beds_id').value;
var ext_beds_cost = ext_beds_id.split("_");
var reservation_duration = document.getElementById('reservation_duration').value;
var total_payable = ( parseInt(room_type_cost[1]) + parseInt(meal_type_cost[1]) + parseInt(ext_beds_cost[1]) ) * parseInt(reservation_duration);
document.getElementById('total_amount').value = total_payable;
}

Pass data-attribute from DOM to function in AngularJS controller

I'm using AngularJs to change visibility of certain DOM elements. The visibility depends on what value was selected in a dropdownlist. More specifically, on a data-attribute of the selected option tag. I cannot populate the dropdown via AngularJs, because it's an existing ASP.NET control.
I thought about using ng-change and call a method on my controller but I'd have to pass an argument. This argument is in the DOM and not in my controller. Obviously, I'd like to keep it this way, and not access the DOM in my controller.
I've made a jsFiddle, but this is my code:
HTML
<body ng-app>
<div ng-controller="VehicleDetailsCtrl">
<select ng-model="selectedValue" ng-change="update()">
<option value="1" data-carType="Car">Car 1</option>
<option value="2" data-carType="Car">Car 2</option>
<option value="3" data-carType="Truck">Truck</option>
</select>
<div ng-hide="isTruck">
Hide if a truck was selected.
</div>
</div>
</body>
Javascript
function VehicleDetailsCtrl($scope) {
$scope.isTruck = false;
$scope.selectedValue = null;
$scope.update = function() {
$scope.isTruck = !$scope.isTruck;
// hide div here?
// but then I'd need to know the selected option,
// but I don't want to reference the DOM here.
};
}
Am I approaching this in the wrong way?
Keep in mind that I cannot let AngularJs populate the select because ASP.NET already does that for me (and I can't change that at the moment).
Also, I need both the selectedValue (for post-back and saving it to the database) and the data-carType (for changing the DOM). I don't know at runtime what the id (or value) of the Truck option is.
Use a directive to create an object of vehicle types and watch the model value of the select to update your isTruck variable:
HTML:
<select ng-model="selectedValue" check-is-truck>
JS:
var app = angular.module('myApp', []);
app.directive('checkIsTruck', function(){
return function(scope, element, attrs){
scope.vehicleTypes = {};
scope.selectedType = false;
angular.forEach(element.find('option'), function(item, idx) {
scope.vehicleTypes[item.value] = item.dataset.cartype;
});
scope.$watch('selectedValue', function() {
scope.selectedType=scope.vehicleTypes[scope.selectedValue];
scope.isTruck = scope.selectedType == 'Truck'
})
};
})
function VehicleDetailsCtrl($scope) {
$scope.isTruck = false;
$scope.selectedValue = null;
}
DEMO: http://jsfiddle.net/7ttr6/2/
You don't need ng-change to update the value because ng-model takes care of that. And in ng-hide you need to simply compare the selectedValue with the value of 'Truck' option (int 3):
<select ng-model="selectedValue">
<option value="1" data-carType="Car">Car 1</option>
<option value="2" data-carType="Car">Car 2</option>
<option value="3" data-carType="Truck">Truck</option>
</select>
<div ng-hide="selectedValue==3">
Hide if a truck was selected.
</div>
Fiddle