angularjs nullable select if null then - javascript

I have in my html angularjs select with null posibility:
<span class="nullable">
<select ng-model="ViewLevel" ng-change="selChanged()"
ng-options="camptype.name for camptype in campTypes">
<option value="">-- choose campaign type --</option>
</select>
</span>
and in js controller method to check if user selected something from list or nullable option
$scope.selChanged = function() {
if ($scope.ViewLevel == null) {
$scope.getTypeData();
console.log("nullek");
} else {
$scope.getCampaignData();
console.log("nie nullek");
}
}
But it doesn't work. Always if clause is true, even if in firebug I can see that ViewLevel is not null. Why?
EDIT: screen from firebug
ViewLevel is an object with property but if clause was true:

rather than checking against null, using ! operator, it will check for both null/undefined
$scope.selChanged = function() {
if (!$scope.ViewLevel) {
$scope.getTypeData();
console.log("nullek");
} else {
$scope.getCampaignData();
console.log("nie nullek");
}
}
EDIT
as per angularjs recommendation: your ngModel must have a dot, and that would solve the problem for you.
//somewhere in your controller
$scope.selected = {}
and then in your html
<select ng-model="selected.ViewLevel" ng-change="selChanged()"
ng-options="camptype.name for camptype in campTypes">
<option value="">-- choose campaign type --</option>
</select>
and then again fix if in your function. check for $scope.selected.ViewLevel
$scope.selChanged = function() {
if (!$scope.selected.ViewLevel) {
$scope.getTypeData();
console.log("nullek");
} else {
$scope.getCampaignData();
console.log("nie nullek");
}
}

Related

Angular5 select model

I have a Angular5 <select> bound to array of customers. See below:
<select class="form-control" [ngModel]="record.customer_id" (ngModelChange)="setCustomer($event)" name="customer_id">
<option *ngFor="let x of customers" [ngValue]="x.id">{{x.name}}</option>
</select>
In setCustomer function I get an customer's id as 'event'.
Property record.customer_id is type of number, not object. Is there any way how to get a whole customer entity in setCustomer method and also preserve binding to record.customer_id ?
I found on Angular docu a way [compareWith] so I tried:
<select class="form-control" [compareWith]="compareCustomer" [ngModel]="record.customer_id" (ngModelChange)="setCustomer($event)" name="customer_id">
<option *ngFor="let x of customers" [ngValue]="x">{{x.name}}</option>
</select>
and
compareCustomer(c1: customer, c2: number) : boolean {
if (c1 == null || c1 == undefined) {
return false;
}
if (c1.id == c2) {
return true;
}
return false;
}
Does not work. When I select any option, setCustomer is executed, record.customer_id gets selected id. However, after select loses focus, selected option is reset to blank.
There is a workaround (iteration in customers array and manual match by id) that I want to avoid:
setCustomer(event) {
this.record.customer_id = Number.parseInt(event);
customers.forEach(c => {
if (c.id === this.record.customer_id) {
// some logic with selected customer
}
});
}
Any advice?
Thanks!
Instead of bind customer_id, bind the whole object:
<select class="form-control" [ngModel]="record" (ngModelChange)="setCustomer($event)" name="customer_id">
<option *ngFor="let x of customers" [ngValue]="x">{{x.name}}</option>
</select>

AngularJS - Disable select list option if expression is true

I've tried to disable a materializeCSS select list option is a particular expression is true, but this doesn't seem to be working using the method below:
<option data-ng-disabled="employeeIsMale" value="maternity">Maternity</option>
I've defined the truth value of this expression like below on load, which is obviously working, because the correct message is logged to the console:
$document.ready(function() {
if ($scope.employee.gender === 'Male') {
$scope.employeeIsMale == true;
console.log("Employee is Male");
} else {
$scope.employeeIsMale == false;
console.log("Employee is Female");
}
})
How can I use the expression like this to disable the select option?
Full HTML:
<select data-ng-change="showAbsenceInputs()" data-ng-model="absenceTypes" id="absenceTypeSelect" name="absenceTypeSelect" material-select watch class="validate" required>
<option value="" selected>Select an option</option>
<option data-ng-disabled="employeeIsMale" value="maternity">Maternity</option>
</select>
You should use assignment operator =.You are using comparison operator for assignment.
$scope.employeeIsMale = true;

JQuery show/hide gives weird results

Im having some weird issues with javascript I can't really resolve.
I have three html input boxes with a small js file to show or hide the second and third one depending on what is picked in the first box. I'm using these functions:
$('#maintype').on('change', function() {
if (this.value == '1') {
$("#fries").show();
} else {
$("#fries").hide();
}
});
The problem im running to is that the second dropdown is not shown when I highlight "fries". The third input box is never shown. I've tried all sorts of solutions, but I just can't figure out why.
I put my code on github
Anyone that can give me some insight on where I am going wrong? Is there maybe another, simpler way to get this done?
You have two issues:
The problem im running to is that the second dropdown is not shown when I highlight "fries"
Your check for fries is wrong, you have:
if ( this.value == '1') {
$("#fries").show();
} else {
$("#fries").hide();
}
but the check should be for '6' since that is the value you assigned to it in your #maintype select.
The other issue:
The third input box is never shown.
You assigned the different IDs (eg. #fries, #icecream, etc.) to the <div> and not to the <select>.
You should also not have several elements with the same id or name (ie. #selectlist) in your case this will be solved when you fix the second issue.
There is no handler for <option value="6">fries</option> , i mean there is no if ( this.value == '6') type line in your javascript code. I added below lines in your js file and it worked.
$('#maintype').on('change', function() {
if ( this.value == '6')
//.....................^.......
{
$("#fries").show();
}
else
{
$("#fries").hide();
}
});
Demo : https://jsfiddle.net/gd548j0g/
In your #maintype select, fries has a value of '6'. But in your change handler, you are looking for a value of 1. In fact, there is no value in the select that has a value of 1. Hence, the fries select box is never shown. Either change your handler to look for the id of 6:
$('#maintype').on('change', function() {
if ( this.value == '6') {
$("#fries").show();
} else {
$("#fries").hide();
}
});
Or change your option value for fries to 1:
<select class="select" id="maintype" name="maintype">
<option value=""></option>
<option value="3">filler</option>
<option value="161">Icecreams</option>
<option value="1">fries</option>
<option value="7">Others</option>
<option value="162">burgers</option>
<option value="163">drinks</option>
</select>
Working example: https://jsfiddle.net/mspinks/vnofjobu/2/
<select class="select" id="maintype" name="maintype">
<option value=""></option>
<option value="3">filler</option>
<option value="161">Icecreams</option>
<option value="6">fries</option>
<option value="7">Others</option>
<option value="162">burgers</option>
<option value="163">drinks</option>
</select>
$('#maintype').on('change', function() {
if ( this.value == 6)
{
$("#fries").show();
}
else
{
$("#fries").hide();
}
be careful with the values that you assign to the options
your value of fries is 6, not 1
I have checked your code in Git, you can achieve your output with below code in your showhide.js file.
$(document).ready(function(){
$('#maintype').on('change', function() {
$('input[type="text"]').hide(); //Hides all input with type Text, better if we do this using class
var id = '#' + this.value;
$(id).show(); //Show input with id which you have returned with this.value
});
});

Check how many selects have had an options selected using jQuery

I got a bunch of selects:
<select name="paraquien" class="selectpicker form-control paraquien" id="paraquien" onchange="mostrarPreguntas();">
<option value=""><?=__('¿Para quién es el plan?')?><span class="glyphicon glyphicon-triangle-bottom"></span></option>
<option value="1"><?=__('Para mi')?> <span class="glyphicon glyphicon-triangle-bottom"></span></option>
<option value="2"><?=__('Para regalar')?><span class="glyphicon glyphicon-triangle-bottom"></span></option>
</select>
and I would like to know if all of them have been selected, and in that case trigger an event. I've tried this far:
jQuery('.paraquien option:selected')
Getting this result array:
[
<option value=​"1">​Para mi ​</option>​,
<option value=​"1">​Hombre​</option>​,
<option value=​"3">​Estudiante​</option>​,
<option value>​Su situación sentimental​</option>​,
<option value>​¿Tiene hijos?​</option>
​]
You can see every option selected has a value attribute set, what I would like to know is how to get just the options which value has been already set, in the same selector mentioned before.
Any Idea?
You can use filter() to check for select elements where the value is still ''. Try this:
var $unchosenSelects = $('.paraquien').filter(function() {
return $(this).val() == '';
});
if ($unchosenSelects.length) {
// there was at least one select within nothing chosen...
}
Similarly you could use map() to get all the values in an array, then $.inArray to check for empty strings:
var chosenValues = $('.paraquien').map(function() {
return $(this).val();
});
if ($.inArray(chosenValues, '') != -1) {
// there was at least one select within nothing chosen...
}

jQuery validation on select box not working

I am using jQuery validation plugin for client side validation, but my validation does not work on my select box.
HTML
<select id="select" class="required">
<option value="-1">Choose</option>
<option value="child">test2</option>
</select>
JavaScript
$("#formid").validate({
select: {
required: function(element) {
if ($("#select").val() == '-1') {
return false;
} else {
return true;
}
}
}
});
How do I get this working?
A simple way to fix this problem is to give the non valid option the value of "". Then simply call validate on your form and it will not submit when "Choose" is selected.
HTML
<form id="formid">
<select name="select" class="required">
<option value="">Choose</option>
<option value="child">test2</option>
</select>
<input type="submit" />
</form>​
JavaScript
$("#formid").validate(); ​
Demo
Although this probably works with some of the aforementioned methods,if you're looking to use a custom validation function, you should use addMethod as documented here: http://docs.jquery.com/Plugins/Validation/Validator/addMethod
So you would first add the method through something like
$.validator.addMethod("requiredSelect", function(element) {
return ( $("#select").val() !='-1' );
}, "You must select an option.");
Then simply assign the validator with
$("#formid").validate({
rules: {
select: { requiredSelect : true }
}
});
For some reason no solution provided worked in my case, it boiled down to jQuery Validate calling the "optional" check on the value of the drop down, which that called the !required rule.
When the select box selected an empty value, the required showed "false" which inverted meant it was always optional when the required failed, so it never ran the required rule.
I overwrote the optional function with the below, which returned "False" on optional if it was a required item:
// Get Select to work
$.validator.prototype.optional = function (element) {
var val = this.elementValue(element);
// Custom logic to get Select to show validate when value is empty
if (element.nodeName.toLowerCase() === "select") {
if (element.hasAttribute("data-val-required") || element.hasAttribute("required")) {
return false;
}
}
return !$.validator.methods.required.call(this, val, element) && "dependency-mismatch";
};
instead of:
$("#select").val()
try:
$("#select :selected").val()
$("#select").val() returns all the option values instead of the selected one.
Here, my assumption is that you want to check if the user has chosen the option -1 when the control report-crime is validated.
by default
<option value="">Choose</option>
works with
required: true
There is missing name attribute in your select element.
In my case that was the issue since the jQuery Validatation Plugin looks for the name not id while validating.

Categories

Resources