Is there a way to use something like $(".class").change(function(){
or $("#id").change(function(){
, but to change the value the value attribute of an option element like so?
<select>
<option value="changeThis">opt</option>
</select>
I'm using a for loop to generate each option of a select list from a relational database, so I need to have a function to automatically increment the value so they're unique.
New code:
<div class="facilitySelection">
<select name="Facility" class="form-control">
<option selected disabled>Select a facility...</option>
@{
var i = 1;
foreach (var item in Model)
{
<option value="@i">@Html.DisplayFor(modelItem => item.FacilityName</option>
i++;
}
}
</select>
</div>
Newer code:
I have a table of Facilities, with an ID and Name field. Now using a foreach
loop to use the ID directly from the database rather than generating the number from a variable in the script block, to ensure the ID and Name from the database line up correctly.
<div class="facilitySelection">
<select id="Facility" name="Facility" class="form-control">
<option selected disabled>Select a facility...</option>
@{
foreach(var f in ViewBag.Facilities)
{
<option value="@f.Id">@f.Name</option>
}
}
</select>
</div>
You change attributes with the attr
function:
$("selector-for-the-option").attr("value", "new value");
You can also use prop
because the value
of an option
element has a reflected property called value
( unlike input
elements, where the value
property is not the reflected property for the value
attribute):
$("selector-for-the-option").prop("value", "new value");
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.