您好我想知道如何创建循环以便我的js通过id,因为我有2个不同表单的2个字段的电子邮件ID 然后我可以选择当我点击我的表单的ID时,只在正确的表单上显示错误,反之亦然
我的代码:
<script type="text/javascript">
$(document).ready(function(){
$("input#id_st-courriel").focusout(checkEmailField);
});
function checkEmailField() {
$fieldValue = $("input#id_st-courriel").val();
$.ajax({
url: '/ajax/checkEmailField',
data: ({
value: $fieldValue
}),
type: 'GET',
success: function($data, $textStatus, $XMLHttpRequest) {
if ($data != '') {
$("input#id_st-courriel").parent().prev('errorlist').remove();
$("input#id_st-courriel").parent().before($data);
}
}
})
}
</script>
我有一个id:id_st-courriel 和我的第二个公式的另一个id:id_em-courriel
目前,我的第一个表单上的错误显示为id:id_st-courriel
编辑:
我的views.py
def ajax_check_email_field(request):
form = LoginForm(request.POST)
HTML_to_return = ''
if 'value' in request.GET:
field = forms.EmailField()
try:
field.clean(request.GET['value'])
except exceptions.ValidationError as ve:
HTML_to_return = '<ul class="errorList">'
for message in ve.messages:
HTML_to_return += '<li>' + message + '</li>'
HTML_to_return += '</ul>'
return HttpResponse(HTML_to_return)
答案 0 :(得分:2)
<ul>
<li>foo</li>
<li>bar</li>
</ul>
//You can select the list items and iterate across them:
$( "li" ).each(function( index ) {
console.log( index + ": " + $( this ).text() );
});
答案 1 :(得分:1)
您可以将$(this)
传递给函数checkEmailField
以引用当前的焦点字段,尝试:
$(document).ready(function(){
$("input#id_st-courriel, input#id_em-courriel").focusout(function(){
checkEmailField($(this));
});
});
function checkEmailField(_this) {
$fieldValue = _this.val();
$.ajax({
url: '/ajax/checkEmailField',
data: ({
value: $fieldValue
}),
type: 'GET',
success: function($data, $textStatus, $XMLHttpRequest) {
if ($data != '') {
$(_this).parent().prev('errorlist').remove();
$(_this).parent().before($data);
}
}
})
}
希望这有帮助。
答案 2 :(得分:1)
您可以进行一些小修改,例如
this
引用动态选择当前元素 - 在事件处理程序this
中将引用触发事件的输入元素所以
$(document).ready(function() {
$("#id_st-courriel, #id_em-courriel").focusout(checkEmailField); //you can simplify the selector if you can add a common class to both these fields and then use the class selector to add the event handler
});
function checkEmailField() {
var $fileld = $(this);
var $fieldValue = $fileld.val();
$.ajax({
url: '/ajax/checkEmailField',
data: ({
value: $fieldValue
}),
type: 'GET',
success: function($data, $textStatus, $XMLHttpRequest) {
$fileld.parent().prev('.errorlist').remove();//may be .errorlist if it is a class
if ($data != '') {
$fileld.parent().before($data);
}
}
})
}