Javascript 如何使用jquery验证动态填充的表单字段?
我有一个包含10个问题的列表,用于对用户进行评级,如下所示: 根据用户的职业动态获取列表。以下是我获取列表的方式:Javascript 如何使用jquery验证动态填充的表单字段?,javascript,jquery,asp.net-mvc,razor,Javascript,Jquery,Asp.net Mvc,Razor,我有一个包含10个问题的列表,用于对用户进行评级,如下所示: 根据用户的职业动态获取列表。以下是我获取列表的方式: @for (int i = 0; i < Model.AppraisalQuestions.ToList().Count; i++) { @Html.HiddenFor(m => m.AppraisalQuestions[i].QuestionId) @Html.HiddenFor(m => m.AppraisalQuestions[i].Ques
@for (int i = 0; i < Model.AppraisalQuestions.ToList().Count; i++)
{
@Html.HiddenFor(m => m.AppraisalQuestions[i].QuestionId)
@Html.HiddenFor(m => m.AppraisalQuestions[i].QuestionDescription)
<p>
@Html.DisplayFor(m => m.AppraisalQuestions[i].QuestionDescription)
@Html.ValidationMessageFor(m => m.AppraisalQuestions[i].SelectedAnswer, "", new { @class = "text-danger" })
</p>
<div class="row lead evaluation">
<div id="colorstar" class="starrr ratable"></div>
<span id="count">0</span> star(s) - <span id="meaning"> </span>
@foreach (var answer in Model.AppraisalQuestions[i].PossibleAnswers)
{
//var inputId = Model.AppraisalQuestions[i].QuestionId + "-" + answer.ID;
@Html.HiddenFor(m => m.AppraisalQuestions[i].SelectedAnswer, new { id = "SelectedAns", required = "required" })
}
</div>
}
@for(int i=0;im.evaluationQuestions[i].QuestionId)
@Html.HiddenFor(m=>m.evaluationQuestions[i].QuestionDescription)
@DisplayFor(m=>m.evaluationQuestions[i].QuestionDescription)
@Html.ValidationMessageFor(m=>m.evaluationQuestions[i]。选择回答,“,新建{@class=“text danger”})
零星(s)-
@foreach(模型中的var答案。评估问题[i]。可能答案)
{
//var-inputId=Model.evaluationQuestions[i].问题ID+“-”+answer.ID;
@Html.HiddenFor(m=>m.evaluationquestions[i].SelectedAnswer,new{id=“SelectedAns”,required=“required”})
}
}
这就是模型:
public class AppraisalInputModel
{
public int AppraisalId { get; set; }
public AppraisalInputModel()
{
AppraisalQuestions = new List<AppraisalQuestionInputModel>();
}
public string FullName { get; set; }
public string JobTitle { get; set; }
public int StaffId { get; set; }
public int ScorerId { get; set; }
public int BranchId { get; set; }
public string AppraisalTitle { get; set; }
public IList<AppraisalQuestionInputModel> AppraisalQuestions { get; set; }
}
公共类模型
{
public int valid{get;set;}
公共评估模型()
{
评估问题=新列表();
}
公共字符串全名{get;set;}
公共字符串JobTitle{get;set;}
public int StaffId{get;set;}
public int ScorerId{get;set;}
公共整数{get;set;}
公共字符串{get;set;}
公共IList评估问题{get;set;}
}
这是评估问题输入模型
public class AppraisalQuestionInputModel
{
public int QuestionId { get; set; }
public string QuestionDescription { get; set; }
public bool IsGeneral { get; set; }
[Required]
[Display(Name = "Score")]
public int? SelectedAnswer { get; set; }
public IEnumerable<AnswerVM> PossibleAnswers => new List<AnswerVM>()
{
new AnswerVM {ID = 1, Text = "1 - Poor"},
new AnswerVM {ID = 2, Text = "2 - Below Expectation"},
new AnswerVM {ID = 3, Text = "3 - Meets Expectation"},
new AnswerVM {ID = 4, Text = "4 - Good"},
new AnswerVM {ID = 5, Text = "5 - Excellent"},
};
}
公共类评估问题输入模型
{
public int QuestionId{get;set;}
公共字符串QuestionDescription{get;set;}
公共布尔是一般的{get;set;}
[必需]
[显示(Name=“分数”)]
public int?SelectedAnswer{get;set;}
public IEnumerable可能答案=>new List()
{
新的应答器vm{ID=1,Text=“1-Poor”},
新答案VM{ID=2,Text=“2-低于预期”},
新的应答器vm{ID=3,Text=“3-满足期望”},
新的应答器vm{ID=4,Text=“4-Good”},
新的应答器vm{ID=5,Text=“5-极好”},
};
}
这是脚本部分代码:
@section Scripts{
@Scripts.Render("~/bundles/jqueryval")
<script type="text/javascript">
// Starrr plugin (https://github.com/dobtco/starrr)
var __slice = [].slice;
(function($, window) {
var Starrr;
Starrr = (function() {
Starrr.prototype.defaults = {
rating: void 0,
numStars: 5,
change: function(e, value) {}
};
function Starrr($el, options) {
var i,
_,
_ref,
_this = this;
this.options = $.extend({}, this.defaults, options);
this.$el = $el;
_ref = this.defaults;
for (i in _ref) {
_ = _ref[i];
if (this.$el.data(i) != null) {
this.options[i] = this.$el.data(i);
}
}
this.createStars();
this.syncRating();
this.$el.on('mouseover.starrr', 'span', function(e) {
return _this.syncRating(_this.$el.find('span').index(e.currentTarget) + 1);
});
this.$el.on('mouseout.starrr', function() {
return _this.syncRating();
});
this.$el.on('click.starrr', 'span', function(e) {
return _this.setRating(_this.$el.find('span').index(e.currentTarget) + 1);
});
this.$el.on('starrr:change', this.options.change);
}
Starrr.prototype.createStars = function() {
var _i, _ref, _results;
_results = [];
for (_i = 1, _ref = this.options.numStars; 1 <= _ref ? _i <= _ref : _i >= _ref; 1 <= _ref ? _i++ : _i--) {
_results.push(this.$el.append("<span class='glyphicon .glyphicon-star-empty'></span>"));
}
return _results;
};
Starrr.prototype.setRating = function(rating) {
if (this.options.rating === rating) {
rating = void 0;
}
this.options.rating = rating;
this.syncRating();
return this.$el.trigger('starrr:change', rating);
};
Starrr.prototype.syncRating = function(rating) {
var i, _i, _j, _ref;
rating || (rating = this.options.rating);
if (rating) {
for (i = _i = 0, _ref = rating - 1; 0 <= _ref ? _i <= _ref : _i >= _ref; i = 0 <= _ref ? ++_i : --_i) {
this.$el.find('span').eq(i).removeClass('glyphicon-star-empty').addClass('glyphicon-star');
}
}
if (rating && rating < 5) {
for (i = _j = rating; rating <= 4 ? _j <= 4 : _j >= 4; i = rating <= 4 ? ++_j : --_j) {
this.$el.find('span').eq(i).removeClass('glyphicon-star').addClass('glyphicon-star-empty');
}
}
if (!rating) {
return this.$el.find('span').removeClass('glyphicon-star').addClass('glyphicon-star-empty');
}
};
return Starrr;
})();
return $.fn.extend({
starrr: function() {
var args, option;
option = arguments[0], args = 2 <= arguments.length ? __slice.call(arguments, 1) : [];
return this.each(function() {
var data;
data = $(this).data('star-rating');
if (!data) {
$(this).data('star-rating', (data = new Starrr($(this), option)));
}
if (typeof option === 'string') {
return data[option].apply(data, args);
}
});
}
});
})(window.jQuery, window);
$(function() {
return $(".starrr").starrr();
});
$(document).ready(function () {
var starCount;
var correspondence = ["", "Poor", "Below Expectation", "Above Expectation", "Good", "Excelent"];
$('.ratable').on('starrr:change', function(e, value) {
$(this).closest('.evaluation').children('#count').html(value);
$(this).closest('.evaluation').children('#SelectedAns').val(value);
starCount = $(this).closest('.evaluation').children('#SelectedAns').val(value);
if (starCount === null) {
swal("", "Please Enter First Name", "error");
}
$(this).closest('.evaluation').children('#meaning').html(correspondence[value]);
var currentval = $(this).closest('.evaluation').children('#count').html();
var target = $(this).closest('.evaluation').children('.indicators');
target.css("color", "black");
target.children('.rateval').val(currentval);
target.children('#textwr').html(' ');
});
$('#hearts-existing').on('starrr:change', function(e, value) {
$('#count-existing').html(value);
});
});
</script>
<script type="text/javascript">
$(document).ready(function () {
$('[data-toggle="tooltip"]').tooltip();
});
</script>
}
@节脚本{
@Scripts.Render(“~/bundles/jqueryval”)
//Starr插件(https://github.com/dobtco/starrr)
var _slice=[].slice;
(函数($,窗口){
var Starr;
starr=(函数(){
Starrr.prototype.defaults={
评级:无效0,
numStars:5,
更改:函数(e,值){}
};
功能Starr($el,可选){
var i,
_,
_参考号,
_这个=这个;
this.options=$.extend({},this.defaults,options);
这.$el=$el;
_ref=this.defaults;
对于(i in _ref){
_=_ref[i];
如果(此.$el.data(i)!=null){
this.options[i]=此.$el.data(i);
}
}
这个.createStars();
这是syncRating();
此.$el.on('mouseover.starr','span',函数(e){
返回_this.syncRating(_this.$el.find('span').index(e.currentTarget)+1);
});
此.el.on('mouseout.starr',function(){
返回_this.syncRating();
});
此.$el.on('click.starr','span',函数(e){
返回_this.setRating(_this.$el.find('span').index(e.currentTarget)+1);
});
this.$el.on('starr:change',this.options.change);
}
Starrr.prototype.createStars=函数(){
变量i,参考,结果;
_结果=[];
对于(_i=1,_ref=this.options.numStars;1您的视图正在为相同的SelectedAnswer
生成5个隐藏输入。您只需要一个(只有第一个的值将由DefaultModelBinder
绑定),并且需要在starr:change
事件中设置其值
但是,默认情况下不会验证隐藏的输入,因此您还需要配置$.validator
以进行客户端验证
首先,修改视图以删除foreach
循环,并将其替换为单个隐藏输入。请注意,id
属性已替换为类名(重复的id
属性是无效的html)
请注意,与starCount
相关的代码似乎没有必要,并且不清楚该方法中的其他一些代码在做什么,也不清楚为什么要使用它(例如currentval
与value
的值相同)
最后,要获得客户端验证,请添加以下脚本(但document.ready()中的not)
您的视图正在为相同的SelectedAnswer
生成5个隐藏输入。您只需要一个输入(只有第一个输入的值将被DefaultModelBinder
绑定),并且需要在starr:change
事件中设置其值
但是,默认情况下不会验证隐藏的输入,因此您还需要配置$.validator
以进行客户端验证
首先,修改视图以删除foreach
循环,并将其替换为单个隐藏输入。请注意,id
属性已替换为类名(重复的id
属性是无效的html)
请注意,与starCount
相关的代码似乎不是必需的,并且不清楚其中的一些其他代码是什么
@for (int i = 0; i < Model.AppraisalQuestions.ToList().Count; i++)
{
@Html.HiddenFor(m => m.AppraisalQuestions[i].QuestionId)
@Html.HiddenFor(m => m.AppraisalQuestions[i].QuestionDescription)
<p>
@Html.DisplayFor(m => m.AppraisalQuestions[i].QuestionDescription)
@Html.ValidationMessageFor(m => m.AppraisalQuestions[i].SelectedAnswer, "", new { @class = "text-danger" })
</p>
<div class="row lead evaluation">
<div class="starrr ratable"></div> // remove invalid id attribute
<span class="count">0</span> star(s) - <span class="meaning"> </span>
@Html.HiddenFor(m => m.AppraisalQuestions[i].SelectedAnswer, new { @class = "rating" })
</div>
}
$('.ratable').on('starrr:change', function(e, value) {
var container = $(this).closest('.evaluation'); // cache it
container.children('.count').html(value); // modify
container.children('.rating').val(value); // set value of input
container.children('.meaning').html(correspondence[value]); // modify
....
})
$.validator.setDefaults({
ignore: ":hidden:not('.rating')"
});