Hello all I have drop down list where I am binding it using server side code in asp.net as follows
if (ds1.Tables.Count > 0) {
foreach (DataRow row in ds1.Tables[0].Rows) {
if (row["EmpId"] != DBNull.Value) {
ListItem item = new ListItem(row["EmpName"].ToString(), row["EmpId"].ToString());
item.Attributes.Add("Duration", row["Duration"].ToString());
EmpType.Items.Add(item);
}
}
}
I have a change method for the drop down in my JavaScript to select the duration which is working fine
function UpdateDuration() {
if (document.frmMain.EmpType.selectedIndex > 0) {
var dur = document.frmMain.EmpType.item(document.frmMain.EmpType.selectedIndex).Duration;
document.frmMain.Duration.value = dur;
}
}
But as per my requirement in some cases I will remove one of the option and adding it dynamically as follows which is working fine
$('#EmpType').append($('<option>', {
value: 18,
text: 'Part-Time',
Duration:'60'
}));
But on change of EmpType
I am calling the UpdateDuration()
and showing the duration in one of the text boxes. But as for the dynamically added option the duration is showing in small letters it is unable to fetch the associated value. It is possible to get or add option with out case sensitive.
I can mimic the code to get the other if Duration undefined and get the other, but I would like to know if there is other approach instead of doing that.
CodePudding user response:
Try this, check for both Duration
and duration
function UpdateDuration() {
if (document.frmMain.EmpType.selectedIndex > 0) {
var item = document.frmMain.EmpType.item(document.frmMain.EmpType.selectedIndex);
var dur = item.Duration || item.duration;
document.frmMain.Duration.value = dur;
}
}
or to make it consistent always use lower case duration
item.Attributes.Add("duration", row["Duration"].ToString());
Updated after comment
I though of this too but is there other in JavaScript upon adding option it is treating as small case
HTML attributes are case sensitive. Still if you want be case sensitive I have a work around using
Example
$('#EmpType').append($('<option>', {
value: 18,
text: 'Part-Time',
}));
$('#EmpType option:last').get(0).setAttributeNS(null, "Duration", "60");
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<select id="EmpType">
</select>