dropdown selected on page load angular - javascript

Here is a dropdown :
<div class="col-md-6">
<div class="form-group">
<label class="control-label">Role</label>
<select ng-model="User_Role" class="dropdown form-control" ng-options="t.RoleName for t in rollist track by t.ID">
<option value="" >-- Choose Role --</option>
</select>
</div>
</div>
the dropdown bind here:
$scope.rolelist = function () {
var role = UserService.getroleInfo();
role.then(function (d) {
//debugger;
$scope.rollist = d.data;
}, function (err) {
//debugger;
alert("Some Error Occured ");
});
}
how do selected the dropdown dynamic value in angularjs??
here is the dynamic dropdown <option label="Admin" value="1" >Admin</option>
can any one tell me how do i selected when page load using angular

Try this on your success call back :)
$scope.rollist = d.data;
$scope.User_Role=$scope.rollist[0]; // or $scope.User_Role=$scope.rollist[0].RoleName

here I used direct return in service instead of that you can use your http request in service
var app = angular.module('testApp',[]);
app.service('UserService',function(){
this.getroleInfo=function(){
return [{ID:1,RoleName:"Admin"},{ID:2,RoleName:"User"}];
};
});
app.controller('testCtrl',['$scope','UserService',function($scope,UserService){
/*+role.then(function (d) {
//debugger;
$scope.rollist = d.data;
}, function (err) {
//debugger;
alert("Some Error Occured ");
});*/
//place this below code in inside of your role.then(function(){})
$scope.rollist= UserService.getroleInfo();
$scope.User_Role={ID:2,RoleName:"User"};//here place your dynamic data
}]);
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div ng-app="testApp" ng-controller="testCtrl">
<div class="col-md-6">
<div class="form-group">
<label class="control-label">Role</label>
<select ng-model="User_Role" class="dropdown form-control" ng-options="t.RoleName for t in rollist track by t.ID">
<option value="" >-- Choose Role --</option>
</select>
</div>
</div>
</div>

You could use ng-init in the div and call a function that sets the ng-model value. for example: ng-init="assignValue()", and in the controller:
$scope.assignValue = function(){
$scope.User_Role = $scope.rollist[0]
}

Related

Cannot create property 'subjects' on number '1' using AngularJs

I want to select multiple subjects across one course but can't do so
I have two dropdown lists one for course selection and one for subjects selection. For multiple selection of the subjects I use the angular-chosen plugin, I can select multiple subjects only in the case when the Course is not selected from the dropdown list. But when I select the Course from the dropdown list then I can't select even one subject from the dropdown list
Following is my AddCourseController.js and related HTML
(function() {
var myApp = angular.module("myApp");
var AddCourseController = function($scope, CourseService, TeacherService) {
var onCourses = function(courses) {
$scope.courses = courses;
}
var onError = function(response) {
$scope.error = true;
$scope.errors = response.data;
};
CourseService.courses().then(onCourses, onError);
TeacherService.getSubjects().then(function(data) {
$scope.subjects = data
});
};
myApp.controller("AddCourseController", AddCourseController);
}());
<div class="form-group">
<label>Select Course</label>
<select ng-model="course" class="form-control"
ng-options="course.IdCourse as course.Name for course in courses track by course.IdCourse">
</select>
</div>
<div class="form-group" ng-class="{ 'has-error' :
addCourseForm.subjects.$invalid && !addCourseForm.subjects.$pristine }">
<label class="pull-left">Select Subjects</label>
<a class="pull-right btn btn-primary btn-xs" data-toggle="modal" data- target="#add-subject">Add Subject</a>
<select chosen multiple class="form-control"
ng-model="course.subjects"
ng-options="subject.IdSubject as subject.Name for subject in subjects">
</select>
<p ng-show="addCourseForm.subjects.$invalid &&
!addCourseForm.subjects.$pristine" class="help-block">Subject is required.
</p>
</div>
Change the course selector to return the entire course object to the ng-model:
<div class="form-group">
<label>Select Course</label>
<select ng-model="course" class="form-control"
ng-options="course ̶.̶I̶d̶C̶o̶u̶r̶s̶e̶ as course.Name for course in courses track by course.IdCourse">
</select>
</div>

How to populate a modal box SELECT form control before it is shown using the shown.sb.modal event

I have a simple modal popup that edits an item retrieved from the back end. The for has several input and select controls. The input form controls work properly but the select controls are not pre-populated as intended.
The basic architecture of my functions as follows:
function BootboxEditItem(id) {
$.ajax({
// Load back end data
})
.done(function(data) {
var itemData = data;
$.ajax({
// Load form template for modal
url: '/modal/item/edit-item.html',
......
})
.success: function (data) ({
var box = bootbox.confirm({
// Set up bootbox buttons;
},
callback: function(result){
// Post edited data back to the server
}
)};
box.on("shown.bs.modal", function(e) {
// Populate the modal here using data from the backend.
// This is where the problem lies!
})
box.modal("show");
});
}
Below is the full JavaScript code:
function BootboxEditItem(id) {
var itemDao = '';
$.ajax({
type: "GET",
contentType: "application/json",
url: "/api/item/edit/" + id,
dataType: "json",
cache: false
})
.done(function (data) {
itemDao = data;
$.ajax({
type: "GET",
url: '/modal/item/item-edit-form.html',
success: function (data) {
console.log(itemDao);
var box = bootbox.confirm({
message: data,
title: "Edit Item: [" + itemDao.item.sysId + "]",
buttons: {
cancel: {
label: "Cancel",
className: "btn-danger btn-fixed-width-100"
},
confirm: {
label: "Save",
className: "btn-success btn-fixed-width-100"
}
},
callback: function (result) {
}
});
box.on("shown.bs.modal", function(e) {
console.log(e.currentTarget);
var selectItemLevel = document.getElementById('editItemLevel');
console.log(selectItemLevel);
$(selectItemLevel).empty();
$.each(itemDao.itemLevels, function (key, index) {
var opt = document.createElement('option');
opt.value = index;
opt.innerHTML = 'Level ' + index;
selectItemLevel.appendChild(opt);
});
$(e.currentTarget).find('select[name="editItemLevel"]').val(selectItemLevel);
$(e.currentTarget).find('input[name="editIdentifier"]').val(itemDao.item.identifier);
$(e.currentTarget).find('textarea[name="editItemValue"]').val(itemDao.item.itemValue);
});
box.modal('show');
}
});
});
}
Here is the code for the HTML file:
<form id="editItem" action="/api/items/save" method="post">
<input type="hidden" name="artifactId" id="artifactId" value="" />
<input type="hidden" name="editId" id="editId" value="" />
<input type="hidden" name="editSysId" id="editSysId" value="" />
<input type="hidden" name="editSortIndex" id="editSortIndex" value="" />
<div class="row">
<div class="col-sm-6">
<div class="form-group">
<label for="editItemLevel">Item level:</label>
<select class="form-control" id="editItemLevel" name="editItemLevel"></select>
</div>
</div>
<div class="col-sm-6">
<div class="form-group">
<label for="editItemClass">Item class:</label>
<select class="form-control" id="editItemClass" name="editItemClass" onchange="itemEditClassChange();"></select>
</div>
</div>
</div>
<div class="row" id="editRequirementRow">
<div class="col-sm-6">
<div class="form-group">
<label for="editItemType">Requirement type:</label>
<select class="form-control" id="editItemType" name="editItemType"></select>
</div>
</div>
<div class="col-sm-6">
<div class="form-group">
<label for="createIdentTemplate">Identifier prefix:</label>
<select class="form-control" id="editIdentTemplate" name="editIdentTemplate" onchange="itemEditIdentTemplateChange();"></select>
</div>
</div>
</div>
<div class="row">
<div class="col-sm-6">
<div class="form-group">
<label for="createMediaType">Media type:</label>
<select class="form-control" id="editMediaType" name="editMediaType"></select>
</div>
</div>
<div class="col-sm-6" id="editIdentField">
<div class="form-group">
<label for="editIdentifier">Identifier:</label>
<input type="text" class="form-control" id="editIdentifier" name="editIdentifier" />
</div>
</div>
</div>
<div class="form-group">
<label for="editItemValue">Item details:</label>
<textarea class="form-control" rows="5" cols="50" id="editItemValue" name="editItemValue"></textarea>
</div>
And here is the output intended for one of the SELECT controls as printed by console.log();
<select class="form-control" id="editItemLevel" name="editItemLevel">
<option value="1">Level 1</option>
<option value="2">Level 2</option>
<option value="3">Level 3</option>
<option value="4">Level 4</option>
<option value="5">Level 5</option>
<option value="6">Level 6</option>
<option value="7">Level 7</option>
<option value="8">Level 8</option>
<option value="9">Level 9</option>
<option value="10">Level 10</option>
It seems your each loop is not properly appending the <option></option>.If you have chrome developer tools and you know how to use it, put a breakpoint in this function and make sure the select options are being created and added to the DOM:
$.each(itemDao.itemLevels, function (key, index) {
var opt = document.createElement('option');
opt.value = index;
opt.innerHTML = 'Level ' + index;
selectItemLevel.appendChild(opt); //breakpoint here
});
Also, since you are already using jQuery, you could add them to the DOM like this:
$.each(itemDao.itemLevels, function (key, index) {
$(selectItemLevel).append('<option value="'+index+'">Level '+index+'</option>');
});
Thanks to #nilerafetr24, but the problem was not about appending properly. Rather it was about how to get hold of the SELECT control before being shown.
Certainly, the following doesn't work document.getElementById('editItemLevel'), but the following works $(e.currentTarget).find('select[name="editItemLevel"])'.
So, my final solution is to rewrite the loop thus; after combining with the solution suggested by #nilerafetr24 which seems more efficient:
$.each(itemDao.itemLevels, function (key, index) {
$(e.currentTarget).find('select[name="editItemLevel"]).append('<option=value="'+index'">Level '+index+'</option');
});

Using jQuery validate on select list

I have the following javascript:
var $step = $(".wizard-step:visible:last"); // get current step
var validator = $("#WizardForm").validate(); // obtain validator
var anyError = false;
$step.find("input").each(function ()
{
if (!validator.element(this)) { // validate every input element inside this step
anyError = true;
}
});
This is successfully validating all my input fields but upon trying to apply a similar method to the select type using code:
$step.find("select").each(function () {
if (!validator.element(this)) { // validate every input element inside this step
anyError = true;
}
});
My HTML is as follows:
<div class="wizard-step" id="step1" visibility="hidden" style="display: block;">
<div class="row">
<div class="col-md-6 column ui-sortable">
<div class="form-group">
<label class="control-label col-md-4" for="Tariff_Type">Tariff Type</label>
<div class="col-md-8">
<select style="width:100%;height:35px;border-radius:4px;padding-left:10px;" id="TariffType" name="TariffType" class="form-control input required">
<option value="">Please Select Tariff Type</option>
<option value="keypad account">Say Hello To Budget Extra Discount</option>
<option value="bill pay account">Standard 24H</option>
</select>
<span class="field-validation-valid text-danger" data-valmsg-for="TariffType" data-valmsg-replace="true"></span>
</div>
</div>
</div>
</div>
</div>
How can I ensure that a TariffType value is selected using this method?
Try the .valid() method instead...
if (! $(this).valid()) { ...

React - get value of selected element

I have a set of countries, and each country has a set of cities.
I want to print a dropdown where the user selects a country, and then for that selected country I want to display all cities in another dropdown.
However, how can I know which country was selected?
handleSelect: function(indexOfSelectedCountry){
},
render: function(){
var countryNames = this.props.countries.map(function(elem){
return <option>{elem.name}</option>
});
return(
<div>
<p>Select category</p>
<div class="dropdown">
<select class="form-control" onselect={this.handleSelect(What do I put here?)}>
{countryNames}
</select>
</div>
</div>
)
}
I want to do something like the above, but I don't know how to pass the result of the selection to a listening method.
You don't have to put anything in your parenthesis, this is how you retrieve the selected value (notice the onChange and event usage)
handleSelect: function(event) {
var optionValue = event.target.value
...
},
render: function(){
var countryNames = this.props.countries.map(function(elem){
return <option>{elem.name}</option>
});
return(
<div>
<p>Select category</p>
<div class="dropdown">
<select class="form-control" onChange={this.handleSelect}>
{countryNames}
</select>
</div>
</div>
)
See https://facebook.github.io/react/docs/forms.html
Try This:
<select class="form-control" onChange={ e => this.handleSelect(e.target.value)}>
{countryNames}
</select>
try like this:
handleSelect: function(event){
console.log(event.target.value);
},
render: function(){
var countryNames = this.props.countries.map(function(elem){
return <option>{elem.name}</option>
});
return(
<div>
<p>Select category</p>
<div class="dropdown">
<select class="form-control" onselect={this.handleSelect}>
{countryNames}
</select>
</div>
</div>
)
}

Load <select> AngularJs in form

I'm trying to load my states, where it should be with a state already informed. But I cannot carry it, how can I do this?
It works when it is an input that's okay.
but when I will show again in a form, he is not showing the state in my
In my database the data is like: Arizona
My html code:
<div class="form-group">
<label class="col-sm-4 col-md-4 control-label " for="state">State | {{even.state}}</label>
<div class="col-sm-4 col-md-8">
<span class="block input-icon ">
<select class="form-control" ng-model="even.state" ng-options="state.state for state in states" ng-change="change(even.state)">
<option value="">State</option>
</select>
</span>
</div>
Function to getState
var getState = function () {
dirAPI.getState().success(function (data,status) {
$scope.states = data[0];
})
};
Function to Load general data
var loadEvent = function () {
dirAPI.getEvent().success(function (data) {
$scope.event = data;
});
};
This is a example, when a I load the form, the Arizona did
enter image description here
Thanks

Categories

Resources