AngularJS set default value in dropdown - javascript

I am using below code.
HTML code
<form name="profInfoForm" ng-submit="saveInfo(profInfoForm)" novalidate>
<div class="wrapper">
<div class="container">
<section class="main-ctr">
<div class="error-msg" ng-show="showErrorMsg">
<div class="text">Please fix the validation error(s) below and try again.<br />{{serviceErrorMsg}}</div>
</div>
<div ng-include="'views/header.html'"></div>
<main class="sm-main">
<section class="fix-section">
<h1>Professional information</h1>
<div class="lg-form">
<div class="form-group">
<label class="text-label lg-label">Salutation</label>
<div class="select-wrap lg-select">
<select class="form-input select" name="salutation" required ng-init="profInfo.salutation = item[0]"
ng-options="item.name as item.name for item in salutations"
ng-model="profInfo.salutation">
</select>
<div class="error" ng-show="profInfoForm.$submitted || profInfoForm.salutation.$touched">
<span ng-show="profInfoForm.salutation.$error.required">Required Field</span>
</div>
</div>
</div>
</div>
</section>
<div class="clear"></div>
<div class="button-ctr">
<button class="button" ng-class="profInfoForm.$valid ? 'active' : 'disable'">Next</button>
</div>
</main>
</section>
</div>
</div>
<div id="loading" ng-if="showLoader">
<img src="images/loader.gif" id="loading-image">
</div>
</form>
My constant.js
.constant('APP_CONSTANTS', {
SALUTATIONS: [{ id: 0, name: 'Select' }, { id: 1, name: 'Mr.' }, { id: 2, name: 'Mrs.' }, { id: 3, name: 'Miss' }, { id: 4, name: 'Dr.' }, { id: 5, name: 'Ms'}]
})
Controller code is given below
.controller('professionalInfoCtrl', ['$rootScope', '$scope', '$state', 'globalService', 'APP_CONSTANTS', 'dataServices', function ($rootScope, $scope, $state, globalService, APP_CONSTANTS, dataServices) {
$scope.showLoader = false;
$scope.profInfo = userData;
$scope.salutations = APP_CONSTANTS.SALUTATIONS;
}])
I want to set default value of Salutation drop down list.
For this I am using ng-init but this is not working. I did not to find out the problem.

Please consider using ui-select of AngularUI:
<ui-select ng-model="$parent.company">
<!-- using $parent - https://github.com/angular-ui/ui-select/issues/18 -->
<ui-select-match>{{$select.selected.name}}</ui-select-match>
<ui-select-choices repeat="company in companies>{{company.name}}</ui-select-choices>
</ui-select>

I resolved my issue by using below code
<select class="form-input select" ng-model="profInfo.salutation" required
ng-options="item.name as item.name for item in salutations">
<option value="">Select salutation...</option>
</select>
<div class="error" ng-show="profInfoForm.$submitted || profInfoForm.salutation.$touched">
<span ng-show="profInfoForm.salutation.$error.required">Required Field</span>
</div>
As simple I am using
<option value="">Select salutation...</option>
Thanks everyone.

Related

Vuejs get index in multiple input forms

I have an array of strings like:
questions: [
"Question 1?",
"Question 2?",
"Question 3?",
"Question 4?",
],
Then I have form fields in my data() like:
legitForm: {
name: '', // this will be equal to question string
answer: '',
description: '',
duration: '',
},
Now, the problem I'm facing is when I fill inputs for any of questions
above the same field for other questions gets same value.
Here is my template code:
<div v-for="(question, index) in questions" :key="index">
<form #submit.prevent="legitStore(question)" method="post">
<div class="row">
<div class="col-md-12">
<p>
<strong>{{question}}</strong>
</p>
</div>
<div class="col-md-6">
<label for="answer">Answer</label>
<select class="mb-1 field" v-model="legitForm.answer" name="answer" id="answer">
<option value="1">Yes</option>
<option value="0">No</option>
</select>
</div>
<div class="col-md-6">
<label for="duration">Duration</label>
<input class="field" v-model="legitForm.duration" type="text">
</div>
<div class="col-md-12">
<label for="description">Description</label>
<textarea style="height: 190px;" type="text" cols="5" rows="10" id="address" class="mb-1 field" v-model="legitForm.description"></textarea>
</div>
</div>
<button type="submit" class="saveButtonExperience float-right btn btn--custom">
<span class="text">Save</span>
</button>
</form>
</div>
And this is my post method that sends data to backend:
legitStore(question) {
this.legitForm.name = question; // set "name" in `legitForm` to value of `question` string
axios.post('/api/auth/userLegitsStore', this.legitForm, {
headers: {
Authorization: localStorage.getItem('access_token')
}
})
.then(res => {
// reset my data after success
this.legitForm = {
name: '',
answer: '',
description: '',
duration: '',
};
})
.catch(error => {
var errors = error.response.data;
let errorsHtml = '<ol>';
$.each(errors.errors,function (k,v) {
errorsHtml += '<li>'+ v + '</li>';
});
errorsHtml += '</ol>';
console.log(errorsHtml);
})
},
Here is issue screenshot:
Note: I've tried to
change legitForm to array like legitForm: [], and legitForm: [{....}]
add index to my inputs v-model
but I've got errors so i wasn't sure what I'm doing wrong, that's why
I'm asking here.
If you think of your questions as questions and answers, you can do something like this:
questions: [
{
question: 'Question 1',
answer: null,
description: null,
duration: null,
},
{
question: 'Question 2',
answer: null,
description: null,
duration: null,
},
]
Then when looping through your form, it would be more like this:
<div v-for="(question, index) in questions" :key="index">
<form #submit.prevent="legitStore(question)" method="post">
...
<select class="mb-1 field" v-model="question.answer" name="answer" id="answer">
<option value="1">Yes</option>
<option value="0">No</option>
</select>
...
</form>
</div>
And in the storing function you could send the data in the question instead of this.legitForm
Like you said you tried here:
change legitForm to array like legitForm: [], and legitForm: [{....}]
add index to my inputs v-model
You are supposed to be doing that.
I would change legitForm to:
//create legitForms equal to the length of questions
const legitForms = [];
for (i in questions) legitForms.push(
{
name: '', // this will be equal to question string
answer: '',
description: '',
duration: '',
}
);
and in template:
<div v-for="(question, index) in questions" :key="index">
<form #submit.prevent="legitStore(question)" method="post">
<div class="row">
<div class="col-md-12">
<p>
<strong>{{question}}</strong>
</p>
</div>
<div class="col-md-6">
<label for="answer">Answer</label>
<select class="mb-1 field" v-model="legitForms[index].answer" name="answer" id="answer">
<option value="1">Yes</option>
<option value="0">No</option>
</select>
</div>
<div class="col-md-6">
<label for="duration">Duration</label>
<input class="field" v-model="legitForms[index].duration" type="text">
</div>
<div class="col-md-12">
<label for="description">Description</label>
<textarea style="height: 190px;" type="text" cols="5" rows="10" id="address" class="mb-1 field" v-model="legitForms[index].description"></textarea>
</div>
</div>
<button type="submit" class="saveButtonExperience float-right btn btn--custom">
<span class="text">Save</span>
</button>
</form>
</div>
<div v-for="(question, index) in questions" :key="index">
In your template you iterate through questions and within this tag render object legitForm it all questions will refer to the same 1 object that's why all question have the same data.
You should have had create an array of question contains it own question's content like
<template>
<div v-for="(question, index) in questions" :key="index">
<form #submit.prevent="legitStore(question)" method="post">
...
<div class="col-md-12">
<p>
<strong>{{question.id}}</strong>
</p>
</div>
...
<select class="mb-1 field" v-model="question.answer" name="answer" id="answer">
<option value="1">Yes</option>
<option value="0">No</option>
</select>
...
</form>
</div>
</template>
<script>
class QuestionForm {
// pass default value if you want
name = ''
answer = ''
description = ''
duration = ''
id = ''
constructor(form) {
Object.assign(this, form)
}
}
function initQuestions(num) {
// can generate a Set object cause question are unique
return Array.from({ length: num }, (v, i) => i).map(_j => new QuestionForm())
}
export default {
data() {
return {
questions: initQuestions(5), // pass number of question you want to generate
}
}
}
</script>

How to add text field dynamically with angular2

Hi guys I'm using angular2 in my project and I'm trying to add an input text dymanically, and it works heres the code :
TS:
initArray() {
return this._fb.group({
title: ['', Validators.required]
})
}
addArray() {
const control = <FormArray>this.myForm.controls['myArray'];
//this.myGroupName.push(newName);
control.push(this.initArray());
}
HTML:
<div formArrayName="myArray">
<div *ngFor="let myGroup of myForm.controls.myArray.controls; let i=index">
<div [formGroupName]="i">
<span *ngIf="myForm.controls.myArray.controls.length > 1" (click)="removeDataKey(i)" class="glyphicon glyphicon-remove pull-right" style="z-index:33;cursor: pointer">
</span>
<!--[formGroupName]="myGroupName[i]"-->
<div [formGroupName]="myGroupName[i]">
<div class="inner-addon left-addon ">
<i class="glyphicon marker" style="border: 5px solid #FED141"></i>
<input type="text" style="width:50% !important" formControlName="title" class="form-control" placeholder="Exemple : Maarif, Grand Casablanca" name="Location" Googleplace (setAddress)="getAddressOnChange($event,LocationCtrl)">
<br/>
</div>
</div>
<!--[formGroupName]="myGroupName[i]"-->
</div>
<!--[formGroupName]="i" -->
</div>
</div>
<br/>
<a (click)="addArray()" style="cursor: pointer">+ add text Field</a>
it gives me an error when i add a new text field, any suggestions please??
ERROR Error: Cannot find control with path: 'myArray -> 1 ->
Do not manupulate DOM with AngularJS
In controller create array of inputs
$scope.inputs = [];
$scope.inputs.push({ id: 'input1', value: 'input1' });
$scope.inputs.push({ id: 'input2', value: 'input2' });
$scope.inputs.push({ id: 'input2', value: 'input2' });
<input ng-repeat="input in inputs" ng-model="input.value">
Example

Show div tag when selecting an option | Angular1

I want to show a div tag when selecting a specific option. I am developing this with Angular and Ionic 1. I've been searching around for a while now, but I can't find any answers that works for me, therefore I'm writing this. I want to display the second option (id number 2), but I can't get it to work.
Here's the HTML:
<div class="row row-white">
<div class="col col-white">
<label>
<select name="keys" ng-options="key.name for key in list" ng-change="myCtrl()" ng-model="testValue" class="select-input" style="margin-left:0px;">
<option ng-if="false"></option>
<option ng-value=""></option>
<option ng-value=""></option>
</select>
</label>
</div>
</div>
<div class="divider20"></div>
<div class="row row-white" ng-show="result"> <!-- Won't display!! -->
<div class="col col-white">
<input type="number">
</div>
</div>
And here's the JS:
$scope.list = [{
"id": 1,
"name": "Engångsnyckel"
}, {
"id": 2,
"name": "Fleragångsnyckel"
}]
$scope.myCtrl = function() {
if ($scope.testValue.id == "2") {
$scope.result = true
}
else {
$scope.result = false
}
}
// Sets the first index as placeholder
$scope.testValue = $scope.list[0]
Sorry if this is a dumb and obvious question, but I'm getting desperate.
I hope this will help. You can directly use the data binding property without depending on any functions for the static conditions.
function TodoCtrl($scope) {
$scope.list = [{
"id": 1,
"name": "The Id One"
}, {
"id": 2,
"name": "The Id Two"
}]
// Sets the first index as placeholder
$scope.testValue = $scope.list[0]
}
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app>
<h2>Todo</h2>
<div ng-controller="TodoCtrl">
<div class="row row-white">
<div class="col col-white">
<label>
<select name="keys" ng-options="key.name for key in list" ng-model="testValue" class="select-input" style="margin-left:0px;">
<option ng-if="false"></option>
<option ng-value=""></option>
<option ng-value=""></option>
</select>
</label>
</div>
</div>
<div class="divider20"></div>
<div class="row row-white" ng-show="testValue.id==2"> <!-- Won't display!! -->
<div class="col col-white">
<input type="number" placeholder="Enter the number here">
</div>
</div>
</div>
</div>
Your comparison should be with a number
$scope.myCtrl = function() {
if ($scope.testValue.id == 2) {
$scope.result = true
}
else {
$scope.result = false
}
}
It's nice to use track by too in your
<select name="keys" ng-options="key as key.name for key in list track by key.id" ng-change="myCtrl()" ng-model="testValue" class="select-input" style="margin-left:0px;">
</select>

AngularJS - Conditionally hide a span

I want to hide the <span ng-show="currencyObject.to != 'undefined'">=</span> until the currencyObject.to is undefined which is supposed to be undefined until the user select an option from the select box.
I used ng-show="currencyObject.to != 'undefined'" to conditionally show-hide the span but it is not working. What I find is, when the page is freshly loaded, the = is visible.
<div class="row" ng-controller="QConvertController">
<div class="col-md-8 col-md-offset-2">
<div class="form-group">
<label for="amount">Amount</label>
<input type="number" step="any" class="form-control" id="amount" ng-model="currencyObject.amount">
</div>
</div>
<div class="col-md-8 col-md-offset-2">
<div class="form-group">
<label for="from">From</label>
<select class="form-control" id="from" ng-model="currencyObject.from" ng-change="getconvertedrate()">
<option ng-repeat="currencyCode in currencyCodes" value="{{currencyCode.value}}">{{currencyCode.display}}</option>
</select>
</div>
</div>
<div class="col-md-8 col-md-offset-2">
<div class="form-group">
<label for="to">To</label>
<select class="form-control" id="to" ng-model="currencyObject.to" ng-change="getconvertedrate()">
<option ng-repeat="currencyCode in currencyCodes" value="{{currencyCode.value}}">{{currencyCode.display}}</option>
</select>
</div>
</div>
<br>
<br>
<br>
<div class="col-md-8 col-md-offset-2">
<h1 class="display-4">{{currencyObject.amount}} {{currencyObject.from}} <span ng-show="currencyObject.to != 'undefined'">=</span> {{currencyObject.amount_converted}} {{currencyObject.to}}</h1>
</div>
</div>
QConvertController.js
var app = angular.module('qconvertctrlmodule', [])
.controller('QConvertController', function($scope, $http, $log) {
$scope.currencyObject = {};
$scope.currencyObject.from;
$scope.currencyObject.to;
$scope.currencyObject.amount;
$scope.currencyObject.amount_converted;
$scope.currencyObject.runCount = 0;
$scope.currencyCodes = [{value : 'INR', display : 'Indian Rupee'}, {value : 'USD', display : 'US Dollar'}, {value : 'GBP', display : 'British Pound'}];
$scope.getconvertedrate = function() {
$log.info("FROM : " + $scope.currencyObject.from);
$log.info("TO : " + $scope.currencyObject.to);
$http.get("http://api.decoded.cf/currency.php", {params : {from : $scope.currencyObject.from,
to : $scope.currencyObject.to, amount : $scope.currencyObject.amount}})
.then(function(response) {
$scope.currencyObject.amount_converted = response.data.amount_converted;
$log.info(response.data.amount_converted);
});
};
});
You don't need != 'undefined' to check the variable is defined or not
<span ng-show="currencyObject.to">=</span>
or
<span ng-hide="!currencyObject.to">=</span>
or
<span ng-if="currencyObject.to">=</span>
You can directly use as ng-show="currencyObject.to"
Also in Js correct usage of comparing with undefined is
if(typeof variable !== 'undefined'){ /*...*/ }

ng-disabled in Angular validation not working as expected

http://plnkr.co/edit/9Yq6aZHtKCuZMtPbjBIN?p=preview
I've tried and tried to get this to work but I've had no luck. I'm trying to disable the submit button using angularJS and the built in validation function. What I find is that when you first load the form, the submit button is active--not disabled!
I've tested and tried and I've found that my validation code accepts an empty string / null string in the Team Name, despite me requiring the input.
Does anyone know how to format this correctly? The ONLY way I've gotten it to work is to fudge the data with replacing an empty string with a single space...in production this is unacceptable...
Here is the index.html:
<body ng-controller="EnterController as enter">
<div class="panel panel-primary">
<div class="panel-body">
<form name="enterFormNew" ng-submit="enter.TeamNameNext()" autocomplete="off" novalidate>
<div class="row">
<div class="col-xs-8 col-md-6">
<div class="form-group">
<label for="teamname">Team Name</label>
<input name="TeamName" ng-required ng-minlength="2" ng-maxlength="40" ng-model="enter.Team.Name" type="text" id="teamname" class="form-control" />
<p ng-show="enterFormNew.TeamName.$touched && enterFormNew.TeamName.$invalid">This is not a valid team name.</p>
</div>
<div class="form-group">
<label for="division">Division</label>
<select name="selectDivision" ng-required ng-model="enter.Team.Division" id="division" class="form-control" ng-options="division.Name for division in enter.Divisions track by division.Id ">
<option value="">Select...</option>
</select>
<p ng-show="enterFormNew.selectDivision.$touched && enterFormNew.selectDivision.$invalid">A valid Division needs to be selected.</p>
</div>
</div>
</div>
<div class="row">
<div class="col-xs-2">
<button type="submit" class="btn btn-primary" ng-disabled="enterFormNew.$invalid">Next</button>
</div>
</div>
</form>
</div>
</div>
</body>
And here is the app.js:
angular.module('Enter', [])
.controller("EnterController", [
function() {
this.RegistrationPhase = 0;
this.Divisions = [{ Id: 1,Name: "Normal"}, {Id: 2,Name: "Not Normal"}];
this.Team = { Name: "", ResumeKey: null, Division: { Id: -1 }, Players: []};
this.TeamNameNext = function() {
//Code removed
alert("Made it to the submit function!")
};
}
]);
the attribute ng-required requires a value. Don't get confused with HTML5 attribute required that doesn't require a value.
ng-required="true"
Because "Team.Division" is not undefined in your controller code.
If you could use the code below, you will get what you extected.
this.Team = { Name: "", ResumeKey: null, Division: undefined, Players: []};
You can use null or "" instead of undefined.

Categories