<input type="hidden" id="amenities" value="@Model.Amenities" />
<script type="text/javascript">
$(function () {
arr = new Array();
var str = document.getElementById("amenities").value;
arr = str.split(",");
for(count =0;count<arr.length;count++)
{
$("input[type=checkbox][value=arr[count]]").prop("checked",true);
}
</script>
In the model there is an attribute called "Amenities" of type string. It stores all the amenities like wifi, pool , park etc with delimiter (,). When I go to the edit page I want all those amenities to be checked which were earlier stored for that particular property.
I suggest to do it on the server when you generate the view. All you need is:
public class MyModel
{
...
public string[] Amenities { get; set; }
...
}
Then in the view:
@Html.Checkbox("WiFi", @Model.Amenities.Contains("WiFi"))
@Html.Checkbox("Pool", @Model.Amenities.Contains("Pool"))
Of course it's just an example and in real life you'll probably have a list of possible Amenities and you iterate through to render checkboxes for each of them. Also instead of strings as values I would recommend and enum.
This works:
<script type="text/javascript">
$(document).ready(function(){
var arr = $("#amenities").val().split(",");
$('input[type=checkbox]').each(function(){
if($.inArray($(this).val(), arr) >= 0){
$(this).attr("checked",true);
}
});
});
</script>
<script type="text/javascript">
$(function () {
var arr = new Array();
var str = $("#amenities").val();
arr = str.split(",");
$('input[type=checkbox]').each(function(key,val){
if(jQuery.inArray( $(this).val(), arr){
$(this).prop("checked",true);
}
})
});
</script>
Check the above code.!!
One recommendation, Since you are using jQuery, GO with jQuery syntax.
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.