I made a form with ajax email validation. My problem is that I need to have more than 1 email input field. The code in jquery that I wrote works only with one. I don’t want to use the solution with copy and paste changing the id because it is not efficient and also the amount of email fields is not constant.
This is my js file:
// 0 - email not valid
// 1 - email valid
$(document).ready(function() {
$("#ClientEmail_0").focusout(function() {
// span with loader gif
$("#ajax_status_0").css('display','inline');
// span with the results
$("#email_ajax_result_0").css('display','none');
var $email = $("#ClientEmail_0").val();
$.post("/reservations/reservations/ajax_check_email/",{data:{Client:{email:$email}}},function(data) {
$("#ajax_status_0").css('display','none');
if (data == 1) {
$("#email_ajax_result_0").attr('class','ajax_success');
$("#email_ajax_result_0").text('Email is available');
}
if (data == 0){
$("#email_ajax_result_0").attr('class','ajax_error');
$("#email_ajax_result_0").text('You are already our client. Proceed with the reservation.');
}
$("#email_ajax_result").css('display','inline');
});
});
});
This is my view:
<?php
for($i = 0 ; $i < $this->params['nr'] ; $i++){
echo $this->Form->input('Client.'.$i.'.email', array(
'label'=>$this->Html->tag(
'span',
$html->image("icons/ajax-loader.gif", array(
"alt" => "loading",
)),
array(
'id' => 'ajax_status_'.$i,
)),
'div'=>'IconMail clearValue',
'after' => $this->Html->tag(
'span',
'',
array(
'id' => 'email_ajax_result_'.$i,
)),
));
}
?>
Thanks!
Try doing this –
First give common class name say mail to your basic trigger element (in your example ClientEmail_0 one)
then use the below code.
edit your view to this –
My basic idea in above example is that the id of the basic trigger element should be present in every further element’s id.
for example:
if main trigger element id is say ClientMail
then the further elements id becomes
email_ClientMail
ajax_ClientMail
ie the first part is constant and further part is the main elements id.
it will work even when there are an unknown number of elements.
Try it out and let me know.