Reputation: 265
Hello I want to know how to make a loop so that my js is through an id because I have an email id for 2 fields for 2 different forms I would then be able to choose when I click on the id of my form right that displays the error only on the right form and vice versa
My code :
<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>
I have an id : id_st-courriel and an other id for my second formulaire : id_em-courriel
For the moment I're the error display on my first form with the id: id_st-courriel
Edit :
My 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)
Upvotes: 2
Views: 77
Reputation: 388316
You can make some minor changes to do it like
this
reference - in the event handler this
will refer to the input element which triggered the event So
$(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);
}
}
})
}
Upvotes: 1
Reputation:
<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() );
});
Upvotes: 2
Reputation: 67505
You could pass $(this)
to you function checkEmailField
to refer to the current focused out field, try :
$(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);
}
}
})
}
Hope this helps.
Upvotes: 1