Default option in select - html

I have this very simple select element:
<label>Items per page</label>
<select class="form-control input-sm w25" ng-model="itemsPerPage">
<option value="5">5</option>
<option value="10">10</option>
<option value="25">25</option>
<option value="50">50</option>
</select>
with controller:
$scope.itemsPerPage = 5; // default value
But the default value is a blank option and the default value attempt doesn't do anything.
How do I make the value 5 the default?

Angular is probably converting that value to a string, so do:
$scope.itemsPerPage = "5";

The blank option appears because ng-model can't find an option that matches the value of the bound property (option values are converted to string and the bound property is number).
If you don't want to change the type of your itemsPerPage property and make it a string, you can keep a number and define, in your $scope, an object with a getter and setter that will take care of the type conversion.
angular.module('dummyApp', [])
.controller('DummyController', function($scope) {
var itemsPerPage = 5; // still a number
Object.defineProperty($scope, "itemsPerPage", {
get: function() {
return itemsPerPage + "";
},
set: function(newValue) {
itemsPerPage = parseInt(newValue);
}
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.7.2/angular.js"></script>
<div ng-app="dummyApp" ng-controller="DummyController">
<label>Items per page</label>
<select class="form-control input-sm w25" ng-model="itemsPerPage">
<option value="5">5</option>
<option value="10">10</option>
<option value="25">25</option>
<option value="50">50</option>
</select>
</div>

<option value="5" selected>5</option>
This should work^^

Related

JQuery match different id with the last same number

I have example HTML code like this:
<select id="label_1">
<option></option>
</select>
<select id="item_1">
<option></option>
</select>
<select id="label_2">
<option></option>
</select>
<select id="item_2">
<option></option>
</select>
How do I write jQuery code to match the label and item id with the same number?
if($("#label_" + [/[0-9]+$/]) == $("#item_" + [/[0-9]+$/])) {
//do something
}
You can find all the label elements first and then iterate them to find the matching item elements
$("select[id^='label_']").each((_, label) => {
const idSuffix = label.id.split("_").pop();
const item = $(`#item_${idSuffix}`);
// now you have both `label` and `item`
});
The vanilla JS version isn't much different
document.querySelectorAll("select[id^='label_']").forEach((label) => {
const idSuffix = label.id.split("_").pop();
const item = document.getElementById(`item_${idSuffix}`);
// now you have both `label` and `item`
});
If you want to do one time : return false
$.each($("select[id^= 'label_']"), function(){
let num = this.id.replace('label_', '')
let equal = $(this).value === $("#item_" + num).value
if(equal) {
// do something
// if you want to run one times ( return false)
return false
}
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<select id="label_1">
<option value="1" selected>1</option>
</select>
<select id="item_1">
<option value="1" selected>1</option>
</select>
<select id="label_2">
<option value="2" selected>2</option>
</select>
<select id="item_2">
<option value="2" selected>2</option>
</select>

how to change second drop-down based on first option selection and third drop-down based on second option selection

Please can someone help me - I want the second drop-down to change based on a selection from the first option and also the third drop-down to change based on a second selected option. Here is my html:
<select name="selectLevel" id="selectLevel" >
<option value="">-- select a level --</option>
<option value="jhs">Junior High School</option>
<option value="shs">Senior High School</option>
<option value="tertiary 3">Tertiary</option>
</select>
<select name="selectSubject" id="selectSubject">
<option value=""> -- select a subject -- </option>
<option data-value="jhs" value="english">English Language</option>
<option data-value="shs" value="maths">Mathematics</option>
<option data-value="tertiary" value="IT">Business Math</option>
</select>
<select name="selectTopic" id="selectTopic" >
<option value=""> -- select a topic -- </option>
<option data-value="jhs">Spelling</option>
<option data-value="shs">Matrix</option>
<option data-value="tertiary">Calculus</option>
</select>
And here is my script:
$(document).ready(function(){
$('#jhs').change(function(){
if($(this).data('options') == undefined){
$(this).data('options', $('#selectSubject option').clone());
}
var id = $(this).val();
var options = $(this).data('options').filter('[data-value=' + id + ']');
$('#selectSubject').html(options).show();
});
$('#selectSubject').change(function(){
if($(this).data('options') == undefined){
$(this).data('options', $('#selectTopic option').clone());
}
var id = $(this).val();
var options = $(this).data('options').filter('[data-value=' + id + ']');
$('#selectTopic').html(options).show();
});
});
Thank You very much!
I change a little bit to make it easier.
When we change the first select, it will check the second select's option and change its value.
After that, it will trigger the second select's change event and so on.
$(document).ready(function() {
// Save all selects' id in an array
// to determine which select's option and value would be changed
// after you select an option in another select.
var selectors = ['selectLevel', 'selectSubject', 'selectTopic']
$('select').on('change', function() {
var index = selectors.indexOf(this.id)
var value = this.value
// check if is the last one or not
if (index < selectors.length - 1) {
var next = $('#' + selectors[index + 1])
// Show all the options in next select
$(next).find('option').show()
if (value != "") {
// if this select's value is not empty
// hide some of the options
$(next).find('option[data-value!=' + value + ']').hide()
}
// set next select's value to be the first option's value
// and trigger change()
$(next).val($(next).find("option:first").val()).change()
}
})
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select name="selectLevel" id="selectLevel">
<option value="">-- select a level --</option>
<option value="jhs">Junior High School</option>
<option value="shs">Senior High School</option>
<option value="tertiary">Tertiary</option>
</select>
<select name="selectSubject" id="selectSubject">
<option value=""> -- select a subject -- </option>
<option data-value="jhs" value="english">English Language</option>
<option data-value="shs" value="calculus">Calculus</option>
<option data-value="tertiary" value="IT">Info Tech</option>
</select>
<select name="selectTopic" id="selectTopic">
<option value=""> -- select a topic -- </option>
<option data-value="calculus">Calculus</option>
<option data-value="calculus">Matrix</option>
<option data-value="english">Basic English</option>
<option data-value="english">Basic English 2</option>
<option data-value="IT">Info Tech Studies</option>
<option data-value="IT">Info Tech Studies 2</option>
</select>
i got it u would add script CDN code in your code
https://www.w3schools.com/jquery/jquery_get_started.asp
just above your script code
Like this :
<select name="selectLevel" id="selectLevel" >
<option value="">-- select a level --</option>
<option value="jhs">Junior High School</option>
<option value="shs">Senior High School</option>
<option value="tertiary 3">Tertiary</option>
<select name="selectSubject" id="selectSubject">
<option value=""> -- select a subject -- </option>
<option data-value="jhs" value="english">English Language</option>
<option data-value="shs" value="maths">Mathematics</option>
<option data-value="tertiary" value="IT">Business Math</option>
<select name="selectTopic" id="selectTopic" >
<option value=""> -- select a topic -- </option>
<option data-value="jhs">Spelling</option>
<option data-value="shs">Matrix</option>
<option data-value="tertiary">Calculus</option>
</select>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function(){
$('#selectLevel').change(function(){
if($(this).data('options') == undefined){
$(this).data('options', $('#selectSubject option').clone());
}
var id = $(this).val();
var options = $(this).data('options').filter('[data-value=' + id + ']');
$('#selectSubject').html(options).show();
});
$('#selectSubject').change(function(){
if($(this).data('options') == undefined){
$(this).data('options', $('#selectTopic option').clone());
}
var id = $(this).val();
var options = $(this).data('options').filter('[data-value=' + id + ']');
$('#selectTopic').html(options).show();
});
});
You can do this by Ajax request.

How to validate lodash filter?

I have three dropdowns:-
<form name="myForm" data-ng-submit="save(myForm.$valid)"novalidate="novalidate">
<label>1st</label>
<select ng-model="a.value[0]">
<option value="One">One</option>
<option value="Two">Two</option>
<option value="Three">Three</option>
</select>
<label>2nd</label>
<select ng-model="a.value[1]">
<option value="One">One</option>
<option value="Two">Two</option>
<option value="Three">Three</option>
</select>
<label>3rd</label>
<select ng-model="a.value[2]">
<option value="One">One</option>
<option value="Two">Two</option>
<option value="Three">Three</option>
</select>
<button type="submit" class="btn btn-warning"><i class="fa fa-save"></i>
Save</button>
</form>
Controller code:-
$scope.a.value = [];
$scope.func = function () {
if (_.uniq($scope.a.value).length !== $scope.a.value.length) {
scope.notify("error", "Please set unique values");
}
};
What I want is that it should not saved if the values in the dropdowns are not unique. What validations should I apply and where?
What you have made looks like an initiative way to identify duplicate values using lodash. Theoretically your implementation should work. Did you try ?
Ideally you should check for the duplicates values when the user tries to select the value for better user experience. One way of doing that is you can remove the values selected in the 1st dropdown in the subsequent dropdowns and so on.
in your js add:-
$scope.allModels = {
firstDD: 'One',
secondDD: 'Two',
thirdDD: 'Three'
}
and then in your html to all Dropdowns use
<select ng-model="$scope.allModels.firstDD">
<select ng-model="$scope.allModels.secondDD">
<select ng-model="$scope.allModels.thirdDD">
eventiually in save function look for them
$scope.save = function(){
if($scope.allModels.firstDD != $scope.allModels.secondDD != $scope.allModels.thirdDD){
//do the thing you want or post it to server
}
}

How to use lodash filter?

I have three dropdowns:-
<form name="myForm" data-ng-submit="save(myForm.$valid)"novalidate="novalidate">
<label>1st</label>
<select ng-model="a.value[0]">
<option value="One">One</option>
<option value="Two">Two</option>
<option value="Three">Three</option>
</select>
<label>2nd</label>
<select ng-model="a.value[1]">
<option value="One">One</option>
<option value="Two">Two</option>
<option value="Three">Three</option>
</select>
<label>3rd</label>
<select ng-model="a.value[2]">
<option value="One">One</option>
<option value="Two">Two</option>
<option value="Three">Three</option>
</select>
<button type="submit" class="btn btn-warning"><i class="fa fa-save"></i>
Save</button>
</form>
What I want is user select unique value in each dropdown, if not get notified.
$scope.a.value = [];
scope.func = function () {
if (_.uniq(scope.a.value).length !== scope.a.value.length) {
scope.notify("error", "Please set unique values");
}
};
I used the above code but didn't get it right? Please tell me what I am doing wrong? or give me a possible solution.
Also what I want is that it is not saved if the values are not unique. What validation should I apply and where?
Use ng-change="uniqCheck()" in each select directive:
<select ng-model="a.value[0]" ng-change="uniqCheck()">
<option value="One">One</option>
<option value="Two">Two</option>
<option value="Three">Three</option>
</select>
Use in the controller:
$scope.uniqCheck = function(){
$log.log('this is $scope.a', $scope.a);
if (_.uniq($scope.a.value).length !== $scope.a.value.length) {
// $scope.notify("error", "Please set unique values");
$window.alert("error - Please set unique values")
}
}
this should work as #Selva.K comment
Your code should work fine - _.uniq returns an array with duplicate values removed - so if you compare the length of the result of _.uniq with the result of the unmodified array you can determine if the values are all unique.
The step you're missing is that you are not calling your validation - as pointed out by Anandapriyan S.D.
You need to make sure that every time you change your select you call the function that checks the uniqueness.
<div ng-controller="Ctrl">
<label>1st</label>
<select ng-model="a.value[0]" ng-change="uniqCheck()">
<option value="One">One</option>
<option value="Two">Two</option>
<option value="Three">Three</option>
</select>
<label>2nd</label>
<select ng-model="a.value[1]" ng-change="uniqCheck()">
<option value="One">One</option>
<option value="Two">Two</option>
<option value="Three">Three</option>
</select>
<label>3rd</label>
<select ng-model="a.value[2]" ng-change="uniqCheck()">
<option value="One">One</option>
<option value="Two">Two</option>
<option value="Three">Three</option>
</select>
</div>
function Ctrl($scope) {
// not sure why you are nesting values onto a, unless a has more important information
// you could just use $scope.a = []; and then use $scope.a[0] ...
$scope.a = {};
$scope.a.value = [];
$scope.notify = function(error, message) {
alert(error + ': ' + message);
}
$scope.uniqCheck = function() {
if (_.uniq($scope.a.value).length !== $scope.a.value.length) {
$scope.notify("error", "Please set unique values");
}
};
}
https://plnkr.co/edit/UARPwYWQGjJux9FrQwFc?p=preview

Disabling one option in HTML listbox

I have 3 listboxes which displays same options. I want to disable the option in other two listboxes which is selected in a listbox. I want to let my User go any listbox first. Any help is appreciated.
If you have the following HTML:
<select id="select1">
<option value="">Choose</option>
<option value="1">One</option>
<option value="2">Two</option>
<option value="3">Three</option>
<option value="4">Four</option>
</select>
<select id="select2">
<option value="">Choose</option>
<option value="1">One</option>
<option value="2">Two</option>
<option value="3">Three</option>
<option value="4">Four</option>
</select>
<select id="select3">
<option value="">Choose</option>
<option value="1">One</option>
<option value="2">Two</option>
<option value="3">Three</option>
<option value="4">Four</option>
</select>
You can do this (with the help of jquery):
var previousValues = []
$selects = $('#select1, #select2, #select3');
$selects
.mousedown(function(e) {
// save the previous value for re-enabling it when you change
var val = $(this).val();
if (val) {
previousValues[this.id] = val;
}
})
.change(function(e) {
// get the other select elements
var $theOtherSelects = $selects.not('#' + this.id),
prevVal = previousValues[this.id],
val = $(this).val();
// re-enable the previously disabled option
if (prevVal) {
$theOtherSelects
.find('option[value=' + prevVal + ']')
.prop('disabled', false);
}
// if a value is selected, disble in the other selects
if (val) {
$theOtherSelects
.find('option[value=' + val + ']')
.prop('disabled', true);
}
})
.mousedown()
.change();
Here's jsfiddle for you to play with.
Note: I've used jQuery because it is much easier, will work cross-browser, and you did not specify you didn't want to use it explicitly.
You could set some unique property on each option (the value might be enough, otherwise class is a good choice) and use jQuery to select and delete one option from the other two when it is selected in one of the selects.
EDIT: Here's an example that does something along the lines of what you want. You'd have to modify it a bit yourself. Didier's answer may be closer to what you want, though.
http://jsfiddle.net/baByZ/39/