How to set an id to option in HTML.DropDownList - html-select

I have an HTML.DropDownList where I can set datavaluefield and datatextfield like the following,
<select>
<option value="Fruit">APPLE</option>
</select>
Even, I can able to set the ID to dropdown list using html attributes but Since I need to set the 'Id' to the option like following,
<select>
<option ID='1' value="Fruit">APPLE</option>
</select>
Can anyone share the idea on it...

You can use the id attribute to set the ID to the option tag and use this.value into the onchange callback with select element.
Below is the working example
document.getElementById("select1").onchange = function() {
if (this.value == 'Fruit') {
var optionID=document.getElementById('1');
alert(optionID.value);
}
if (this.value == 'Flower') {
var optionID=document.getElementById('2');
alert(optionID.value);
}
}
<select name="select01" id="select1" onchange="handleSelect()">
<option value="Fruit" id="1">Apple</option>
<option value="Flower" id="2">Rose</option>
</select>

Try this, It will alert your selected value
<select onchange="alert(this.value)">
<option id="1">APPLE</option>
<option id="2">Orange</option>
</select>

Related

Drop down item not being selected by default in Razor view

I have the following code written in Razor view in MVC in C#. I want to select one of the item based on value but it is not working. I confirmed that the variable Facilities contain value Un-Funded but it doesn't select this item.
<select id="facilities" class="form-control" style="width:200px;">
<option #{ if (Facilities == "Funded") { Response.Write(" selected "); } }>Funded</option>
<option #{ if (Facilities == "Un-Funded") { Response.Write(" selected "); } }>Un-Funded</option>
</select>
Here's screenshot of how HTML looks like. Notice it is not printing selected for any of the option.
I am using Response.Write which doesn't work in Razor view. Using #Html.Raw("some string") fixed the issue. So the code will look like this:
#{ if(Facilities == "Funded") { #Html.Raw("selected='selected'") } }
You can try to use js,so that if you have many options,you don't need to check on each option:
<select id="facilities" class="form-control" style="width:200px;">
<option value="Funded">Funded</option>
<option value="Un-Funded">Un-Funded</option>
</select>
<script>
$(function () {
$("#facilities").val("#Facilities");
//Or you can use $("#facilities").val(#Html.Raw(Json.Encode(Facilities)));
})
</script>
With MVC 5 you can use this method #: to insert your selected:
<select id="facilities" class="form-control" style="width:200px;">
<option value="Funded" #{ if (Facilities == "Funded") { #: selected="selected"
}}>
Funded
</option>
<option value="Un-Funded" #{ if (Facilities == "Un-Funded") { #: selected="selected"
}}>
Un-Funded
</option>
</select>
for older version you can check this link :
setting-the-selected-option-in-mvc3

emberjs: Passing selected value to select field in form

I am attempting to add a SELECT field from first principles using ember and am having difficulty working out how to pass the currently selected option to a form when editing a record.
I have set the form up as a component and am able to use it successfully when creating a new record, with the selected value being passed to the Rails backend.
My issue is that I cannot work out a way to apply this selected value to the form component when editing an existing record.
Here is the component template section (book-form.hbs):
<div class="form-group">
<select id="format" onchange={{action 'updateValue' value='target.value'}}>
<option value=""></option>
<option value="Paperback">Paperback</option>
<option value="Hardcover">Hardcover</option>
<option value="E-Book">E-Book</option>
</select>
Template code (book-form.js):
import Component from '#ember/component';
export default Component.extend({
actions: {
submitChange(param) {
this.onSave(param, this.selectedOpt);
},
selectedOpt: "",
updateValue(value) {
this.set('value', value);
this.selectedOpt = value;
},
}
});
new & edit templates:
{{book-form onSave=(action 'saveBook') model=model}}
new controller:
export default Controller.extend({
actions: {
saveBook(newBook,format) {
var tmp = this.store.createRecord('book', {
title: newBook.title,
author: newBook.author,
genre: newBook.genre,
format: format,
});
tmp.save();
this.transitionToRoute('books.list');
}
}
});
edit controller:
actions: {
saveBook(book) {
book.save();
this.transitionToRoute('books.list');
}
}
I know I'm missing something somewhere to pass the model value through to the component but am not sure how to do it or where it belongs.
I would appreciate any assistance at all.
If anyone looking at this question is using Ember Octane (3.14+)
This'd be what you want (based on #AhmetEmre's answer):
The Template:
<select id="format" {{on 'change' this.updateValue}}>
<option value=""></option>
<option value="Paperback" selected={{eq this.value "Paperback"}} >Paperback</option>
<option value="Hardcover" selected={{eq this.value "Hardcover"}} >Hardcover</option>
<option value="E-Book" selected={{eq this.value "E-Book"}}>E-Book</option>
</select>
The JS for the component:
import Component from '#glimmer/component';
import { tracked } from '#glimmer/tracking';
import { action } from '#ember/object';
export default class MyComponent extends Component {
#tracked value = 'Hardcover';
#action updateValue(event) {
this.value = event.target.value;
}
}
HTML select element's default value can be achieved by using selected argument in option tag.
So your template .hbs will be like:
<select id="format" onchange={{action 'updateValue'}}>
<option value=""></option>
<option value="Paperback" selected={{eq value "Paperback"}} >Paperback</option>
<option value="Hardcover" selected={{eq value "Hardcover"}} >Hardcover</option>
<option value="E-Book" selected={{eq value "E-Book"}}>E-Book</option>
</select>
and your component.js will be like:
value: 'Hardcover',
actions: {
updateValue(event){
this.set('value', event.target.value);
}
}
You can take a look at this twiddle for example usage. By the way, this example depends on ember-truth-helpers addon by using eq helper.

ternary operator in option element in asp.net core

I'm using asp.net core 2.1 and I want to use selected option element and set values manually in it like the code below:
<select>
<option selected="#(typeCar== "Volvo" ? "selected" : string.Empty)" value="volvo">Volvo</option>
<option selected="#(typeCar== "Saab" ? "selected" : string.Empty)" value="saab">Saab</option>
<option value="vw">VW</option>
<option value="audi">Audi</option>
</select>
but when i wanted to use ternary operator in both of them selected="selected" is equal to selected="" So the two options are selected and apparently there is no difference between selected="selected" and selected="", for example when typeCar=Volvoview page source in browser is like below:
<select>
<option selected="selected" value="volvo">Volvo</option>
<option selected="" value="saab">Saab</option>
<option value="vw">VW</option>
<option value="audi">Audi</option>
</select>
and second option is selected!
how can i solve this problem?
Return null from your ternary instead of string.Empty. If the attribute's value is null, Razor will remove it automatically, but since you're setting it to something, even if it's just an empty string, it will persist.
<select>
<option selected="#(typeCar== "Volvo" ? "selected" : null)" value="volvo">Volvo</option>
<option selected="#(typeCar== "Saab" ? "selected" : null)" value="saab">Saab</option>
<option value="vw">VW</option>
<option value="audi">Audi</option>
</select>
As Shyju said, you can't use ternary operator expression to create selected attribute like your current example does. Use either JS/jQuery expression like this example:
$('select').append('<option value="' + typeCar + '"' + (typeCar == 'somevalue') ? ' selected="selected"' : '') + '>' + typeCar + '</option>';
Or simply use <select> tag helper:
<select asp-for="TypeCar" asp-items="Model.Cars"></select>
which populated from a list which contains SelectListItem:
public List<SelectListItem> Cars { get; set; } = CarsList.Select(x => new SelectListItem { Text = x.CarName, Value = x.CarId, Selected = x.IsSelected }).ToList();
Further reference: ASP.NET Core Tag Helpers

MVC 4 .NET use jquery to modify the set of options in a dropdown list

I am using #Html.DropDownListFor to build a select object that looks like this:
<select id="GroupCode" name="GroupCode" tabindex="4"><option value="">Select One</option>
<option value="1">One thing</option>
<option value="17">Another thing</option>
<option value="7">A Third thing</option>
</select>
There comes a time when something else changes on the page, and I want to swap out the options, ending up with something like
<select id="GroupCode" name="GroupCode" tabindex="4"><option value="">Select One</option>
<option value="21">A completely different list</option>
<option value="17">A second item only</option>
</select>
However, when I set a breakpoint in the view and look at $('#GroupCode').html, I see something like this:
$('#GroupCode').html
function(a){return p.access(this,function(a){var c=this[0]||{},d=0,e=this.length;if(a===b)return c.nodeType===1?c.innerHTML.replace(bm,""):b;if(typeof a=="string"&&!bs.test(a)&&(p.support.htmlSerialize||!bu.test(a))&&(p.support.leadingWhitespace||!bn.test(
__proto__:
function() {
[native code]
}
arguments: null
caller: null
length: 1
prototype: {...}
where I was expecting to see something like the html above.
What I'm concerned about is whether, by replacing the html for #GroupCode, I will lose what was provided by the #Html.DropDownFor code.
Bottom line: what is a good way to replace the contents of a dropdown list like this?
See this Working fiddle example
HTML
<select id="GroupCode" name="GroupCode" tabindex="4">
<option value="">Select One</option>
<option value="1">One thing</option>
<option value="17">Another thing</option>
<option value="7">A Third thing</option>
</select>
<button id="testBtn" type="button">replace list with items with ids (21, 7)</button>
Script:
$(function () {
$(document).on("click", "#testBtn", function () {
$('#GroupCode').empty().append(
$('<option/>', {
value: "",
text: 'Select One'
}),
$('<option/>', {
value: "21",
text: "A completely different list"
}),
$('<option/>', {
value: "17",
text: "A second item only"
}));
});
});

How do I enable/disable options in Select Box using jquery

I have a select box which contains the options and optgroup that are generated dynamically using php.Now when I select "ALL" all the other optgroup, options should be disabled and when I select any option other than "ALL" the "ALL" option should be disabled
<select name="select1" id ="select1" onchange="handleSelect()">
<option value ="-1">ALL</option>
<optgroup label="CARS">
<option value="ford">FORD</option>
<option value="Nissan">Nissan</option>
</optgroup>
</select>
<script>
function handleSelect() {
var selectVal = $("#select1:selected").text();
if (selectVal == "ALL") {
// cannot disable all the options in select box
$("#select1 option").attr("disabled", "disabled");
}
else {
$("#select1 option[value='-1']").attr('disabled', 'disabled');
$("#select1 option").attr('disabled', '');
}
}
</script>
How can I make this working?
This is kind of a strange thing to be doing but here's code that meets your requirements.
$('select').on('change', function() {
if (this.value == '-1') {
$('optgroup option').prop('disabled', true);
} else {
$('optgroup option').prop('disabled', false);
}
});
Live Example - http://jsfiddle.net/NpNFh/
You can use the following code.Let us consider you have three select boxes as follows
<select class="sel_box" id="sel_1" onchange="disable_sel(this.value);" ></select>
<select class="sel_box" id="sel_2" onchange="disable_sel(this.value);" ></select>
<select class="sel_box" id="sel_3" onchange="disable_sel(this.value);" ></select>
and in function let 'opt' is argument now use following
$('.sel_box option[value="'+opt+'"]').attr("disabled", true);
You can use two variations on the syntax for the disabled attribute, depending on the version of HTML you are targeting:
HTML4: <option value="spider" disabled>Spider</option>
XHTML: <option value="spider" disabled="disabled">Spider</option>

Resources