using DDL - change 'Select' to 'Null' when viewing drop down - html

Using MVC I am displaying a list 'DeliveryRunList' through a drop down.
'Select' being the option the user sees, if the user clicks the drop down and selects 'select' as their choice, it will store the value as NULL, this is fine.
However is there anyway to change 'Select' to 'No Value' when the drop down is clicked so it will store as empty, but yet still appear as 'select' before the drop down is clicked.
<div class="editor-label">#Html.DropDownList("DeliveryRunId", Model.DeliveryRunList, "Select")</div>

You can use jQuery to achieve this easily:
$(function () {
$('#DeliveryRunId').focus(function () {
$('#DeliveryRunId option:first-child').text('No Value');
});
});

I ran into a similar problem recently, but instead of going for JQuery as Mike said (which is also a nice way of doing the task), i manually added it to the selectlist of the DropdownListFor Html helper from the controller and put it in the Viewbag and send it to it.
List<SelectListItem> DropDownValues= new List<SelectListItem>();
DropDownValues.Add(new SelectListItem() { Text = "-Select-", Value = "No Value" });
DropDownValues.Add(new SelectListItem() { Text = "Text 1", Value = "1.ToString()" });
DropDownValues.Add(new SelectListItem() { Text = "Text 2", Value = "2.ToString()" });
ViewBag.DropDownValueList= new SelectList(DropDownValues, "Value", "Text");
And in your View,
#Html.DropDownListFor(model => model.DropDownName, (SelectList)ViewBag.DropDownValueList)
I didn't check this code, but i remember doing like this and it should work.. Let me know if it does..

Related

Button in Kendo Grid, on click update field

In my Kendo Grid I have a column that I'd like to contain a button.
On clicking this button, I'd like to populate one of fields in the grid (called TradesmanId) with an ID that is available to a javacript function (it is the ID of a logged in user).
This ID should sit in the field until the save changes event on the grid is called.
I had thought about defining the column like this, but I wonder if a command column would work better?
.Columns(trdcol =>
{
trdcol.Bound(f => f.TradeHrs).Title("Man Hours").Width(45);
trdcol.Bound(f => f.TradeDate).Title("Time Date").Width(77).ClientTemplate("#= kendo.toString(TradeDate, 'hh:mm dd/MM/yyyy') #");
trdcol.Bound(p => p.TradesmanId).ClientTemplate("<button id='button' class='k-button'><span class='k-icon k-i-check-outline'></span> #= TradesmanId#</button>").Title("Signature").Width(85);
})
What you did is fine. You can just add a class to your button and then add a click handler that'll do the following:
$(document).on("click", "buttton.my-class", function(e) {
var grid = $("#grid").data("kendoGrid");
var dataItem = grid.dataSource.getByUid($(this).closest("tr").data("uid"));
dataItem.TradesmanId = getLoggedInUserId(); //your javascript function returning the user id
grid.refresh();
})

How do I add new elements to a dropdown menu using ajax?

I would like to know how to add new elements to a dropdown menu without refreshing the html page. For example, if I have the drop down menu below:
<select>
<option>existing item 1<option>
<option>existing item 2<option>
<option>existing item 3<option>
<option>add new item<option>
</select>
Any time the user selects "add new item", a text box would pop-up asking the user for input. Then whatever string the user types in the text box, I want that to be saved to the drop down menu without refreshing the page. Of course, the "add new item" option will remain unchanged, so the user can repeat this process as many times as he/she wants.
Thanks for your help in advance.
you can do it using jquery..
$("select").append("<option>Another option</option>")
A non JQuery way is to use the standard JavaScript dom api like so:
This piece uses a prompt as a text popout input. If you want to make it pretty you will have to consider an UI framework.
JavaScript :
var select = document.getElementById('select');
var addNewOption = document.getElementById('addNew');
select.onclick= function(){
if (select.value === 'addNew'){
var text = prompt('New Value');
if (text){
var label = text;
var value = text;
var newOption = document.createElement('option');
newOption.innerHTML = label;
newOption.value = value;
select.insertBefore(newOption, addNewOption);
select.value = value;
}
}
};
Demo here:
http://jsbin.com/sufug/2/edit

dynamically get options of a dropdown menu in angular

The main problem is that I have a dropdown menu whose options should be updated dynamically.
The workflow is as follows:
I have an input element connected to an ng-model called toSubmit that when longer than 3 characters should fire an http.get call to fetch the list that should populate the dropdown menu.
So this list will change everytime the toSubmit variable changes. Let's call this list database (in the controller it is $scope.database.
What I am trying right now is a very simple solution that doesn't work most probably because the html DOM that contains the dropdown list is loaded at the very beginning and does not keep track of the changes in the options.
In my controller I have the following part which watches over toSubmit:
$scope.toSubmit = '';
$scope.$watch('toSubmit',function(query){
if (query.length >= 3){
getQueryDatabases.companyNameService({'field':'name','query':query,'numberOfHits':'10'},'CIK').prom.then(
function(dataObject){
$scope.database = dataObject;
// dataObject.forEach(function(item){
// $scope.databaseString.push(item.cik + ' ' + item.companyName);
});
});
}
});
And my html looks like the following:
<label for="nameCompany">Name:</label>
<input type="text" ng-model="toSubmit"></input>
<select ng-model="database" ng-options="line in database"></select>
Now my take was take by binding database with ng-Model I would get the result but I am most likely wrong. Can someone please help me?
I recommend you to use select2 that'll handle things like limiting input before server request and have great look and extendibility.
You need to add angular-ui-select2 to your project.
Here is code for you:
Html:
<input class='form-control' data-ng-model='position.company' data-ng-required data-placeholder='Company:' data-ui-select2='employerSelect2Options' id='company_name' type='hidden'>
JavaScript:
$scope.employerSelect2Options = {
minimumInputLength: 2,
query: function (query) {
var _query = query;
var companies = Restangular.all('companies').getList({query: query.term});
companies.then(function(data) {
var results = {results: []};
_.each(data, function(element, index, list) {
results.results.push({id: element.id, text: element.name});
})
if(!_.contains(_.map(data, function(element){ return element.name; }), _query.term)) {
results.results.push({id: _query.term , text: 'Create company "' + _query.term + '"'});
}
_query.callback(results);
})
}
};
My example also contains logic for add "create company" if zero results returned. In this case position.company will contain text of non found company name in id field and you can check it on server side and create one before assigning id.
This logic in
if(!_.contains
condition.

Disabling KendoUI drop down list options

How to disable an option of a kendoiu drop down list?
I couldn't find how to accomplish this in their documentation...
Try the following approach (here and here there are some demos): use a template for your items, which conditionally adds a class to the items to be disabled. The info about which items should be disabled comes from the underlying data objects.
HTML:
<script id="template" type="text/x-kendo-tmpl">
#
if (data.disabled != null) {#
<span class="tbd" > ${data.text} - is disabled </span>
# } else { #
<span>${data.text}</span > #
}#
</script>
<input id="color" value="1" />
jQuery and Kendo UI (note here the disabled extra property for the Orange item and the usage of the dataBound event):
var data = [{
text: "Black",
value: "1"
}, {
text: "Orange",
value: "2",
disabled: "disabled"
}, {
text: "Grey",
value: "3"
}];
$("#color").kendoDropDownList({
dataTextField: "text",
dataValueField: "value",
dataSource: data,
index: 0,
template: kendo.template($("#template").html()),
dataBound: function (e) {
$(".tbd").parent().click(false);
}
});
CSS for graying out:
.tbd{
color:#777777
}
While the accepted answer will prevent a click on the item, it still allows keyboard navigation (and feels pretty hackish).
Using the DataItems to identify which item should be disabled is indeed the way to go, but instead of removing the click handler, it is simpler to implement a Select handler that will stops the chain. This method is supported and documented by Kendo :
Fired when an item from the popup is selected by the user either with
mouse/tap or with keyboard navigation.
...
e.preventDefault Function
If invoked prevents the select action. The widget will retain the
previous selected item.
All that remains is to detect if we want to cancel the selection or not, which is trivial if your data item keeps a property that identifies whether it is available or not :
function Select(e) {
if (e.sender.dataItem(e.item).disabled) {
e.preventDefault();
}
}
Using a template to inject a specific class is not needed, but I would still recommend it if only to enable a proper styling.
Based on the question here, you could access the relevant item and change attributes like so:
var ds = $('#YourCombo').data().kendoComboBox.dataSource;
//someIndex is the index of the item in the dataSource
ds.data()[someIndex].set("enabled","False");
Kendo currently doesn't support such functionality but this is easiest hack I found to disable an option in Kendo Dropdown.
$("#" + id + "_listbox .k-item")[index].disabled = true;
where id -> ID of your dropdown
index -> position of the element in the dropdown you want to disable.
Hope it helps. Enjoy :)
You could try something like this:
var dropDown = $("#yourDropdown").data("kendoDropDownList");
dropDown.enable(false);
Try other way for specific index
var dropDown = $("#color").data("kendoDropDownList");
$("#color" + "_listbox .k-item")[index].disabled = true;
$("#color" + "_listbox .k-item").eq(index).addClass("tbd");
Fiddler for reference :- http://jsfiddle.net/xLs4n9dm/2/
If you want to disable the entire control and you are using the MVC fluent API, then you can use the .HtmlAttributes() method:
#Html.Kendo()
.DropDownList()
.HtmlAttributes(new { #disabled = "disabled" })
Try like this
$('#YourDropDown').attr('disabled', 'disabled');

Cannot set default text for #Html.TextAreaFor?

I am not able to set default text for #HTML.TextAreaFor
This is all I tried, but didn't work, it always shows empty text area
#Html.TextAreaFor(m => m.EmployeeDescription, new { #Text = ViewBag.Model.EmployeeDescription })
#Html.TextAreaFor(m => m.EmployeeDescription, new { #text = ViewBag.Model.EmployeeDescription })
#Html.TextAreaFor(m => m.EmployeeDescription, new { #Value = ViewBag.Model.EmployeeDescription })
#Html.TextAreaFor(m => m.EmployeeDescription, new { #value = ViewBag.Model.EmployeeDescription })
Exactly same thing is working for #Html.TextBoxFor with #Value but not with TextArea :(
Can anybody help...
You should be setting the text on the model before you pass it to the view. This is true for the TextBoxFor as well. You should not have to set the value using HTML attributes. Note that a textarea doesn't have text or value attributes, it's value, when initially rendered, is the HTML between the opening and closing tags.
Found the answer, I was doing a silly mistake
Now I replaced my Index method from this
public ActionResult Index(Guid empId)
{
ViewBag.Model = new EditEmployeePopulator(session, empId).GetModel();
return View();
}
To this
public ActionResult Index(Guid empId)
{
return View(new EditEmpoyeePopulator(session, empId).GetModel());
}
And it worked!
I was doing that in the wrong way earlier. I was assigning my model as a property of ViewBag and was accessing it through ViewBag only in my view and that was my mistake.
When I replaced my code it started working with this only
#Html.TextAreaFor(m => m.EmployeeDescription)
:) :)
Thanks for all the replies
Sorry this by natural of the TextArea element of the HTML itself because if you see the view source you will find the value or the text but for the HTML this not has affect on the TextArea, so to add a default value you need to put text inside the TextArea tag itself
so you can just initialize the object in the creating with your default value as the following:
Employee e = new Employee { Id = 1, EmployeeDescription = "Default Value" };