I have got an enumeration in C# ie something like Category.cs.
In a dropdownlist we are binding values.
So if the user selects some specific value in dropdown it will hide one div.
So i want to get the enumeration value in javascript ie want to compare the enumeration value with one selected value in javascript.
Mahesh
Suppose you have such enum with numeric values:
public enum Colors
{
Yellow = 1,
Red,
Blue,
Green,
Purple
}
First of all, in the code behind (Page_Load event) register JavaScript code that will build client side structure that hold the same data:
string strJS = string.Format("var arrColors = {{{0}}}; ",
string.Join(", ", Enum.GetNames(typeof(Colors)).ToList().ConvertAll(key =>
{
return string.Format("{0}: {1}", key, (int)((Colors)Enum.Parse(typeof(Colors), key)));
}).ToArray()));
Page.ClientScript.RegisterClientScriptBlock(this.GetType(), "enum", strJS, true);
Now arrColors is JS variable with both keys and values of your enum.
To use it, have such code for example:
<script type="text/javascript">
function SelectionChanged(oDDL) {
var selectedValue = oDDL.value;
var enumValue = arrColors[selectedValue] || "N/A";
alert("enum value for '" + selectedValue + "' is: " + enumValue);
}
</script>
And the drop down should look like this:
<select onchange="SelectionChanged(this);">
<option>Select..</option>
<option value="Yellow">Yellow</option>
<option value="Green">Green</option>
</select>
System.Enum.GetNames(typeof(yourenumerationtype)) - returns an array of strings, which represents enumeration items' names
Related
I have a multiselect dropdown. All of its selected text and values should be displayed as each entry on other dropdown. I coded somewhat like this but its not working. All the selections of multiselect dropdown are appending on a single entry of the other dropdown. It is not displaying as separate entries.
#LstCashAccount is the multiselect dropdown and #ddlDefaultCash is the dropdown where entries selected in multiselect dropdown have to get affected
$('#LstCashAccount').change(function () {
$("#ddlDefaultCash").empty();
$("#ddlLoyaltyAcc").empty();
var CashAcc = "";
var CashAccId = $("#LstCashAccount").val();
CashAccIdSplit = CashAccId.splice(",")
CashAcc = $(this).find("option:selected").text();
CashAccSplit = CashAcc.split(".")
$("#ddlDefaultCash").append('<option class="InputDefCash" Id=' + CashAccIdSplit + '>' + CashAccSplit + '</option>');
});
So there are multiple issues here.
First, it's important to realize that the .append() function is what's actually creating your items. You only call this once, so expecting there to be multiple items is, frankly, a bit silly.
Second, you're using .splice() on a string, which isn't valid. I have a hunch you meant to do .split(), but without your HTML markup, it's a bit of a shot in the dark.
And finally, your CashAccSplit variable is (and, I assume, your CashAccIdSplit is supposed to be) an array. If you just concatenate this with a string, it will output the entire array.
If we clean this up, you might be looking for something more like the following...
$('#LstCashAccount').change(function () {
$("#ddlDefaultCash").empty();
$("#ddlLoyaltyAcc").empty();
var CashAcc = $(this).find("option:selected").text();
var CashAccId = $("#LstCashAccount").val();
var CashAccIdSplit = CashAccId.split(",")
var CashAccSplit = CashAcc.split(".")
//Use .each to iterate through the array, append each member as an item
$.each(CashAccIdSplit, function(index, item) {
$("#ddlDefaultCash").append('<option class="InputDefCash" Id=' + CashAccIdSplit[index] + '>' + CashAccSplit[index] + '</option>');
});
});
I have a set of list elements, that I create dynamically. Each of these list elements, contains an input text, whose value I want to pass to the controller.
HTML
<ul id="list"></ul>
<button id="add">Add</button>
<script>
var counter = 1;
$('#add').click(function () {
var text = '<input type="text" name="(what should I put here?)"></input>';
var li = '<li>' + text + '</li>';
$(li).appendTo('#list');
counter++;
return false;
});
</script>
View Model
public IEnumerable<string> list {get; set;}
...
How can I bind those values to my ViewModel implicitly? I have tried to use the counter variable to assign a name to each created element (like list[counter]), but on the controller side the list variable on my ViewModel still comes empty.
First I would base your counter on the amount of li's within your un-ordered list with:
$('#list > li').size()
Then in order to keep the model binder happy pre-fix your property with list:
'<input type="text" name="list[' + counter + ']"></input>'
The full code then becomes:
$('#add').click(function () {
var counter = $('#list > li').size();
var text = '<input type="text" name="list[' + counter + ']"></input>';
var li = '<li>' + text + '</li>';
$(li).appendTo('#list');
return false;
});
jsFiddle
Please note, you will have to change your view model property to an IList or List for indexing to work too:
public IList <string> list {get; set;}
Because your collection is for value type (string) only, then you can simply use
$('#add').click(function () {
var text = '<input type="text" name="list"></input>';
....
});
It is only necessary to include indexers when the property is a member of a complex object.
If you do include the indexer, it must start at zero and be consecutive (unless you also include a special hidden input for to identify the indexer). Your attempt at using list[counter] failed because the value of counter is initialized to 1 (it would have worked had you initialized it to var counter = 0;)
How can I set the Textbox's value equal to address bar?
for example :
localhost:28362/?f=Ava
when we click on a button the value of textbox must set to : Ava
?
Try this, Add Query String Jquery Js(querystring-0.9.0-min.js) in solution
$("#ButtonId").click(function(){
$("#textBoxID").val($.QueryString("f");)
});
Here is Javascript function to get query string value:
function getParameterByName(name) {
name = name.replace(/[\[]/, "\\\[").replace(/[\]]/, "\\\]");
var regex = new RegExp("[\\?&]" + name + "=([^&#]*)"),
results = regex.exec(location.search);
return results == null ? "" : decodeURIComponent(results[1].replace(/\+/g, " "));
}
Then you need to assign this value to a textbox. I would use jQuery:
$(function(){
$("#myTextBoxID").val(getParam("f"));
})
If you want a solution that uses MVC4 rather than JavaScript, define your controller method as:
public ActionResult Index(string f) {
return View(f);
}
In your view, you would then use one of:
#model string;
#Html.TextBoxFor(Model)
or
#model string
<input type='text' value='#Model' name='myValue' />
Obviously this is vastly oversimplified, but should give you a good starting point.
I have a nested ASP.NET ListView, the outer one presenting groups of questions, and the inner one presenting distinct questions within the group. Some of the questions are presented as drop down lists. I want to detect the selected value on change without doing a postback. I have seen lots of references that look like "$(#control).val()" but I need a bit more flexibility.
I am adding the JavaScript in the C# code and it looks like this:
js = string.Format("javaScript:setInputSelectOption('{0}'); return false;", hidSelector.Value);
ddlInputSelectOptions.Attributes.Add("onchange", js);
The resultant aspx file contains this generated code;
<div id='Management_q2'>
<input type="hidden" name="ctl00$body$lstExecutive$ctrl1$hidSelector" id="ctl00_body_lstExecutive_ctrl1_hidSelector" value="Management" />
<select name="ctl00$body$lstExecutive$ctrl1$ddlInputSelectOptions"
id="ctl00_body_lstExecutive_ctrl1_ddlInputSelectOptions"
onchange="javaScript:setInputSelectOption('Management'); return false;">
<option value="0">Not Present</option>
<option selected="selected" value="1">Occasionally</option>
<option value="2">Customarily and Regularly</option>
<option value="3">Constantly</option>
</select>
</div>
My .js file contains this code:
function setInputSelectOption(question) {
var n = $('[id$=' + question + '_q2]>[id$=hidSelector]').val();
var v = $('[id$=' + question + '_q2]>[id$=ddlInputSelectOptions]');
setDDLData(n, v);
}
Using Chrome, I have tried these variants on the "var v = " line with the corresponding results:
$('[id$=' + question + '_q2]>[id$=ddlInputSelectOptions]'):
d.fn.d.init[1] $('[id$=' + question +
'_q2]>[id$=ddlInputSelectOptions]').value: undefined $('[id$=' +
question + '_q2]>[id$=ddlInputSelectOptions]').val(): ""
So I am (yet again) looking for the right incantion to utter to jQuery so that it will return the selected value from the DDL.
I would suggest keeping it simple. Add a data- attribute to the DDL you wish to get the values from. Use jQuery to find the value.
ddl.Attributes.Add("data-ddl","reference");
Then in JS.
// get value
var ddlValue = $("select[data-ddl='reference']").val();
// assign value
$("select[data-ddl='reference']").val("option");
Also, if the JS is only for UI logic, it's best to keep it out of the C# code and run it on the page ready using jQuery. So in your JS file.
$(function(){
// bind a function to the select change event
$("select[data-ddl='reference']").change(function(){
// insert UI logic here
});
});
am having Some kendoui listviews which consists of kendoui dropdown lists and i want to get those dropdown list selected values. To do this am trying,
$("#cnty1").val();
and here is my dropdownlist,i.e., list of countries coming from Database table,
<input select STYLE="width:90px;height:auto" id ="cnty1" data-bind="value:cnty1"
name="cnty1" data-type="string" data-text-field="cnty"
data-value-field="cntyid" data-source="sourcedata1" class="k-d"
data-role="dropdownlist" />
<span data-for="cnty1" class="k-invalid-msg"></span>
here cnty1 is the id of the dropdown list, but am not getting the value instead am getting "id" of the slected value but not the selected value.
And also if the value is not selected am getting the first value id by using $("#cnty1").val();
So, please suggest me a solution so that,
1) I should get only the Selected value and
2) Value of the dropdown list Only if the user selects a value from the list, but don't get the value of the list without selecting.
try this one.
<select STYLE="width:90px;height:auto" id ="cnty1" data-bind="value:cnty1"
data-text-field="cnty" data-value-field="cntyid" data-source="sourcedata1" data-role="dropdownlist" data-change="cntySelect" data-option-label="Select"></select>
function cntySelect(e) {
var dropDownVal = $("#cnty1").val();
alert(dropDownVal);
}
Use the following jquery to get selected value/text:
For value:
$("#cnty1 option:selected").val();
For text use:
$("#cnty1 option:selected").text();
Although this code is being used for FK JSON objects in KendoUI grid, the idea is similar. You have to bind the object on dropdown value selection. The dropdown essentially contains options that are your value ID's, not the objects themselves. Therefore, you have to iterate through the data source to find which object has been selected and then do the replacement in data model.
/**
* KendoDropDownEditor Class
* */
var KendoDropDownEditor = Class({
initialize: function (schema, gridId, readUrl) {
var readUrl = readUrl || base + schema.entityName + "/read";
this.dataSource = DataSourceGenerator.crudDS(schema, gridId, readUrl);
this.dataTextField = schema.model.dropDownTextField;
this.dataValueField = schema.model.id;
},
/**
*
* */
do:function (container, options) {
var self = this;
var a = $('<input data-text-field="' + self.dataTextField + '" data-value-field="' + self.dataValueField + '" data-bind="value:' + options.field + '"/>')
.appendTo(container)
.kendoDropDownList({
autoBind:false,
dataSource:self.dataSource,
close:function (e) {
$.each(self.dataSource.data(), function(key, value) {
if (value[self.dataValueField] == e.sender.value()) {
options.model[options.field] = value;
return false;
}
});
}
});
}
});
Also look at Knockout-Kendo, it could make your life easier.