RAZOR- How to get the first SELECTED OPTION - html

I am currently working on RAZOR project and I have this dynamic HTML SELECT OPTIONS.
var selected="selected";
<select name="Ctry" id="Ctry" required>
<option #if (item.p2kValue.ToString().IsEmpty() || item.p2kValue.ToString().Replace(" ", "") == "")
{ #selected; }></option>
#foreach (var ritem in Model.RItems)
{
<option value="#ritem.ReasonCode" #if (ritem.ReasonCode.Contains(item.p2kValue.Replace(" ", "")))
{ #selected; } > #ritem.ReasonDesc</option>
}
</select>
Everything works fine. When there is an existing data, it can set that as the default selected option. But what I am having a trouble with is when there is no data retrived, the default should be Blank which is the first option. But my code gets the last option. Maybe because there are also SELECTED attribute but it is conditional.I tried to put the Blank option to the last which apprently work but the REQUIRED attribute in SELECT does not work.
So to make the question simple, how can I set the Blank option (first option) as the default when there is no data retrieved while there are conditional SELECTED attributes in other options.
Please help. Thank you in advance

For dropdownlist in html5 you can add a attribute tag in select and the option (which denote to "No option selected") must have empty string as value.
This way you can force the user to select the option before proceed.

Related

PrimeNG p-orderList disable multiple selection of items

I am using PrimeNG's p-orderList. By default, the metaKeySelection attribute is true which implies that a metaKey(ctrl key) is needed to be pressed to select multiple items. I was rather looking for a way to completely disable selection of multiple items. I should be able to select ONLY ONE item in the ordered list.
There is no metaKey attribute available for p-orderList. Can anyone help me with this?
<p-orderList [value]="policyList" [listStyle]="{'min-height':'calc(100vh - 325px)'}" (onSelectionChange)="onSelectionChange($event)">
<ng-template let-policy pTemplate="policy">
<span>{{policy}}</span>
</ng-template>
</p-orderList>
PS: onSelectionChange($event) is triggered every time you select items from the ordered list. $event.value contains the array of the items.
There is no easy flag for it but it can be achieved through calling a function that basically replaces the entire selection array with just the original selected row.
You will need a variable to store the previous value for comparison.
onSelectionChange(event) {
if (event.value.length === 1) {
this.tempValue = event.value[0];
}
else {
event.value = [this.tempValue];
}
}
Can also be simplified by passing event.value to the function
(onSelectionChange)="onSelectionChange($event.value)">
What about the metaKeySelection input property? (as shown here)
<p-orderList [metaKeySelection]="false" [value]="policyList" [listStyle]="{'min-height':'calc(100vh - 325px)'}" (onSelectionChange)="onSelectionChange($event)">
<ng-template let-policy pTemplate="policy">
<span>{{policy}}</span>
</ng-template>
</p-orderList>

Selected Options doesnt display on the field but is sent correctly to backend

So i have a project in which i have to display some data from the table. Now i want to change the size of the data based on a field above the table that is actually a select input field and sends a value to the angular controller. Now this is working perfectly except for the fact that the field doesn't show the selected number of data being displayed on the field.
This is the empty field. but the data is inserted correctly. Also on debugging I found another option here on the field that is not in the html code. Here's my code for the html and the controller.
View:
<li class="manual-dropdown pull-right">
<select id="ddPageSize" ng-model="PaginationInfo.pageSizeSelected" ng-change="ChangePageSize()" aria-controls="DepartmentTable" class="form-control pull-right">
<option value="5">5</option>
<option value="10">10</option>
<option value="25">25</option>
<option value="50">50</option>
<option value="-1">All</option>
</select>
</li>
Controller:
$scope.PaginationInfo = {
maxSize: 5, // Limit number for pagination display number.
totalCount: 0, // Total number of items in all pages. initialize as a zero
pageIndex: 1, // Current page number. First page is 1.
pageSizeSelected: 5, // Maximum number of items per page.
}
GetData(searched);
function GetData(searched) {
//debugger
//var noOfPages = 1;
var SearchData = $scope.StatusSearch.Search;
if (SearchData == "") {
searched = false;
}
var Displaysize = $scope.PaginationInfo.pageSizeSelected;
var index = $scope.PaginationInfo.pageIndex;
if (searched == false) {
Get("/User/GetData?Size=" + Displaysize + "&index=" + index, false).then(function (d) {
//$("#").val()
//$scope.userAccount.CountryID = $("#ddCountryOptions").val();
// $scope.PaginationInfo.maxSize = d.info.maxSize;
$scope.PaginationInfo.totalCount = d.totalSize;
$scope.PaginationInfo.pageIndex = d.index;
$scope.PaginationInfo.pageSizeSelected = d.size;
//$scope.noOfPages = $scope.PaginationInfo.totalCount / $scope.PaginationInfo.pageSizeSelected;
$scope.accountlist = d.GetList;
$scope.$apply();
})
}
else {
// alert($scope.SearchData.Search);
Get("/User/SearchData?inputstring="+ SearchData, false).then(function (d) {
$scope.accountlist = d.GetList;
$scope.PaginationInfo.pageIndex = index;
$scope.PaginationInfo.pageSizeSelected = Displaysize;
$scope.PaginationInfo.totalCount = d.totalSize;
$scope.$apply();
});
}
}
explanation for the Controller: The data is loaded on page load so the GetData() function is called immediately. the default page size is set to 5 as shown and when i make a change to the field i recall the GetData() function with page size as a argument and the back end does the rest and returns a amount of data that i asked for. Also the reason there are 2 ajax calls in this function is to implement a search function. which check if the input field is empty or has a value and based on that output the data.
What i want to know is why is the page size field on my dropdown empty when i select a value.
Edit:
After a bit more research i found that the ng-Model is making a empty option with the value of the option i selected. Now the problem still remains i don't know how to display the value in the empty object. if i do select another option as selected, my ng-model value does not change. So i am still stuck with this. Also i have already give the ng-model an default value of 5 the same as my first dropdown option. so in case i tag any other option as selected, the ng-model option will remain 5 no matter how many times i change the dropdown value.
Alright i kind of solved my issue, though I am not sure if this is a good way to do it.
So what i did is simply bind the pageSizeSelected Value to the html select element by id.
$("#ddPageSize").val(d.size)
$scope.pageSizeSelected = $("#ddPageSize").val();
before $scope.$apply and it worked. Now when i select a value from the field it changes and displays the value i selected.

Display selected items in select box that is stored in database using angularjs laravel

I am trying to get a stored value from the database into a select box, but it is not displaying. The selected value shows in the console(inspect element) but it's just not displaying.
HTML
<td data-ng-class="{'has-error': employeeSchedule.employee.$invalid && employeeSchedule.employee.$dirty}">
<select class="form-control input-sm" name="employee" ng-model="schedule.employee" ng-init="schedule.employee='{{$schedules[0]->employee}}'" ng-options="employee.employeeName for employee in employeesName track by employee.usersId">
<option value="">Select Employee</option>
</select>
</td>
ANGULARJS
app.controller('UpdateWorkScheduleCtrl', [ '$scope', '$http', function ($scope, $http)
{
$http.get('/schedule/employees').success(function(employeedata) {
$scope.employeesName = employeedata;
});
}]);
CONTROLLER(LARAVEL)
public function getEmployees() {
$users = DB::select(DB::raw("SELECT `usersId`, CONCAT(`firstName`,' ',`middleName`,' ',`lastName`) AS employeeName
FROM `users`
WHERE `userStatus` != 'Administrator'
AND `userStatus` != 'Director'
AND `userStatus` != 'HR Specialist'"));
return Response::json($users);
} // end function getEmployees()
INSPECT ELEMENTS(CHROME)
It is clear from inspect elements that the data is there, but it is just not being displayed as the selected item in the select box. Can someone show me what I am doing wrong please.
Your ng-options expression does not match with what you need. You have track by employee.usersId in the syntax employee.employeeName for employee in employeesName track by employee.usersId, Which means that you would need to set ng-model to userId instead of name and also as an object not just as string, i.e your ng-model should ideally be schedule.employee = {usersId:'someid'} for default selection. Now coming to your case which pretty seems like you are trying to set ng-model as a string and you want it the name of the employee (Which probably is a poor choice since you already have an id) you should try the alternate syntax with select as label for value in array`:
ng-options="employee.employeeName as employee.employeeName for employee in employeesName "
Also remember when you use select as syntax you should remove track by, as they are not designed to work together.
Side Note:-
It is a bad idea to use ng-init for initializing ng-mode. And doc says:
The only appropriate use of ngInit is for aliasing special properties of ngRepeat, as seen in the demo below. Besides this case, you should use controllers rather than ngInit to initialize values on a scope.

populate select box on selecting another selectbox

I have two select boxes.Both of them should be populated from database.Second select box should be populated based on the selected option in the first select box.Database connectivity is success and i am able to populate the first select box.But i dont know how to populate second select box based on the first.code i used to populate first select box is,
<select class="weekcombo">
<%
List list= new DataManager().getlist();
for(int i = 0; i < list.size(); i++) {
out.write("<option value=\""+ list.get(i)+ "\">"+ list.get(i));
}
%>
I dont know whether to use servlet or something else for this.
For first select box you can populate values by default like you have mentioned in above code :
<select class="weekcombo" onchange="populateSecValues(this)">
<%
List list= new DataManager().getlist();
for(int i = 0; i < list.size(); i++) {
out.write("<option value=\""+ list.get(i)+ "\">"+ list.get(i));
}
%>
</select>
<select id="secBox" class="weekcombo">
</select>
Javascript :
In urlString you can pass the first select box value like I have passed in below code snippet
function populateSecValues(obj){
// use here ajax call .. which will populate second box data
var firstBoxValue = obj.value;
var urlString ="your_action_url?firstBoxValue="+firstBoxValue ;
$.ajax({
type: "POST",
url: urlString ,
success: function(result) {
console.info("result"+result);
$("#secBox").html(result);
}
});
}
From server populate the values in the form of
<option value ="secBoxValue">secBoxValue</option>
Sagar Dalvi has a good solution. The only way to populate the 2nd select box based on the item selected in the first is with Javascript. This is because, unless you use Javascript, the contents of the 2nd select box would need to be known at page load time - before the user has made any selections.
Using Javascript, the page is ably to dynamically load the options into the 2nd select box when the user makes the selection in the first, using an AJAX call.
The only way round this without using javascript would be to have the form span more than one page, so the second select box is on the next page.

How to parse <select><option> tag using HtmlAgilityPack

I am able to parse radio , checkbox etc.
but while parsing select nodes :
<select name="customeDropDown1" style="height :27px;width :121px;margin-top :75px;margin-left :401px;color:#000000;background-color:#FFFFFF;font-family:Roboto;font-style:;font-size:16px;position:absolute;">
<option>Option1
</option>
<option>Option1
</option>
<option selected="selected">Option1
</option>
</select>
I am able to get the select tag using
var dropdowns = doc.DocumentNode.SelectNodes("//select");
foreach (HtmlNode dropDown in dropdowns)
but not able to get the values in the option tag
I have tried
dropDown .InnerHtml
dropDown . InnerText
and
foreach (HtmlNode node in doc.DocumentNode.SelectNodes("//select//option"))
I have found that using Xpath it can be resolved, any code sample will be helpful.
I am using C# win form application.
For some weird reason, HtmlAgilityPack does not handles those tags correctly, so this managed to solve my problem.
// Iterating over nodes to build the dictionary
foreach (HtmlNode city in citiesNodes)
{
if (city.NextSibling != null)
{
string key = city.NextSibling.InnerText;
string value = city.Attributes["value"].Value;
citiesHash.AddCity (key,value);
}
}
Instead of reaching directly the node,i managed to get the values of each node by using the NextSimbling reference from the previous simbling.
You can also try this. For anyone else that needs to try something different (the answer did not work for me), I ended up just referencing the child nodes from the parent:
HtmlNode.ElementsFlags.Remove("option"); // need this before you do anything with HAP
var options = htmlDoc.DocumentNode.SelectNodes("//select[#id='myselect']/option")
for (var i = 0; i < options.Count; i++) {
var val = options[i].InnerHtml;
}
I was trying to do a foreach, iterating through the nodes, which was giving me null values. This works just fine for me.