我想使用jQuery和Codeigniter创建验证表单。 这段代码实际上运行良好。但我想要的是让这段代码变得更简单。
<?php if (validation_errors()==true) {?>
<script type="text/javascript">
<?php if (form_error('nama')) { ?>
$('#nama').addClass('isInValid');
$('#nama').on('keyup',function(){
$('#nama').removeClass('isInValid');
});
<?php } ?>
<?php if (form_error('email')) { ?>
$('#email').addClass('isInValid');
$('#email').on('keyup',function(){
$('#email').removeClass('isInValid');
});
<?php } ?>
<?php if (form_error('message')) { ?>
$('#message').addClass('isInValid');
$('#message').on('keyup',function(){
$('#message').removeClass('isInValid');
});
<?php } ?>
</script>
<?php } ?>
这是我的控制器代码:
$this->form_validation->set_rules('nama','Name','htmlspecialchars|trim|required|min_length[5]|max_length[30]');
$this->form_validation->set_rules('email','Email','htmlspecialchars|trim|required|min_length[5]|max_length[30]|valid_email');
$this->form_validation->set_rules('message','Message','htmlspecialchars|trim|required|min_length[5]|max_length[400]');
if ($this->form_validation->run()===true) {
$nama =$this->security->xss_clean($this->input->post('nama'));
$email = $this->security->xss_clean($this->input->post('email'));
$message = $this->security->xss_clean($this->input->post('message'));
$this->Contact_m->sendMessage($nama,$email,$message);
$this->session->set_flashdata('success','Thanks for contact us'.$nama);
redirect('Halaman/contact');
}
答案 0 :(得分:0)
对于jQuery,您可以在js函数中添加removeClass,addClass和keyup事件,并在需要时简单地对该函数进行分类,而不是重复代码
<?php if (validation_errors()==true) {?>
<script type="text/javascript">
function errorClass(id) {
$(id).addClass('isInValid');
$(id).on('keyup',function(){
$(id).removeClass('isInValid');
});
}
<?php if (form_error('nama')) { ?>
errorClass('#nama');
<?php } ?>
<?php if (form_error('email')) { ?>
errorClass('#email');
<?php } ?>
<?php if (form_error('message')) { ?>
errorClass('#message');
<?php } ?>
</script>
<?php } ?>