I have six fields which are editable in my Yii2 form widget. What i want to do is once i input integer values into editable fields calculate "Green leaf net weight" automatically based on the given input. my coding are work perfectly. But the problem is if i change already input value in the fields it'll not update the the "Green leaf net weight" read only field.
$(document).ready(function(){
var A = $('#A');
var B = $('#B');
var C = $('#C');
var D = $('#D');
var E = $('#E');
E.change(function(e){
var result = ((A.val() - B.val()) * C.val())/100;
var result2 = ((A.val() - B.val()) * D.val()) / 100;
var final = ((A.val() - B.val()) - result - result2) - E.val();
Math.round(final);
$('#F').val(final);
})
});
my form widget coding (updated code)
<?php $form = ActiveForm::begin(); ?>
<?= $form->field($model, 'Gross_weight',[
'feedbackIcon' => [
'default' => 'shopping-cart',
'success' => 'ok',
'error' => 'exclamation-sign',
]
])->textInput(['id' => 'A', **'class' => 'factors'** ]) ?>
<div class="panel panel-primary" style="padding: 10px;">
<div style="text-align: center; color: #008000;"><b>Deductions</b></div>
<?= $form->field($model, 'Bags_count',[
'feedbackIcon' => [
'default' => 'shopping-cart',
'success' => 'ok',
'error' => 'exclamation-sign',
]
])->textInput() ?>
<?= $form->field($model, 'Bags_weight',[
'feedbackIcon' => [
'default' => 'shopping-cart',
'success' => 'ok',
'error' => 'exclamation-sign',
]
])->textInput(['id' => 'B', **'class' => 'factors'** ]) ?>
<?= $form->field($model, 'Course_leaf',[
'feedbackIcon' => [
'default' => 'shopping-cart',
'success' => 'ok',
'error' => 'exclamation-sign',
]
])->textInput(['id' => 'C', **'class' => 'factors'**]) ?>
<?= $form->field($model, 'Water',[
'feedbackIcon' => [
'default' => 'shopping-cart',
'success' => 'ok',
'error' => 'exclamation-sign',
]
])->textInput(['id' => 'D', **'class' => 'factors'**]) ?>
<?= $form->field($model, 'Boiled_leaf',[
'feedbackIcon' => [
'default' => 'shopping-cart',
'success' => 'ok',
'error' => 'exclamation-sign',
]
])->textInput(['id' => 'E',**'class' => 'factors'**]) ?>
</div>
<?= $form->field($model, 'Greanleaf_net_weight',[
'feedbackIcon' => [
'default' => 'shopping-cart',
'success' => 'ok',
'error' => 'exclamation-sign',
]
])->textInput(['disabled' => 'disabled', 'id' => 'F']) ?>
Thanks for everyone.
Inorder to execute the calculation on the change of all the input fields you have to add a class to all the input fields and use that class as the jQuery selector for change event.
<input id="A" class="factors" ... />
...
...
$(".factors").change(function(e) {
...
...
}
See Demo
Related
I did a simple gridview table with filters on yii2, seems to be working great, but I noticed the javascript functions doesn't work after I apply any filter on the gridview table, i think its refreshing the whole page instead only refresh the table.
I did the $.pjax.reload method but it didn't work, this is how i applied the pjax reload method:
//inventariosearch-amb_id is the ID of one of my filterselects on the gridview
$("#inventariosearch-amb_id").on("pjax:end", function() {
$.pjax.reload({container:"#inventario_lista"}); //Reload GridView
});
Let me know if i applied wrong the method.
well, as I said I think the pjax is refreshing the whole page cause it changes my page title from this:
To this:
That's how I notice the changes and the javascript doesn't work properly anymore.
What can I do?.
My view index.php:
<?php
use yii\helpers\Html;
use yii\helpers\ArrayHelper;
use yii\helpers\Url;
use yii\grid\GridView;
use yii\grid\ActionColumn;
use yii\widgets\Pjax;
use yii\bootstrap4\Modal;
use app\models\Ambiente;
use app\models\TipoServicio;
use app\models\Empresa;
/* #var $this yii\web\View */
/* #var $dataProvider yii\data\ActiveDataProvider */
$this->registerJsFile("#web/js/inventario.js",[
'depends' => [
\yii\web\JqueryAsset::className()
]
]);
$this->title = 'Servidores';
$this->params['breadcrumbs'][] = $this->title;
?>
<div class="inventario-index">
<?php $this->beginBlock('bloque_titulo'); ?>
<div class="page-title-icon">
<i class="fa fa-archive icon-gradient bg-arielle-smile">
</i>
</div>
<div>
<?= Html::encode($this->title) ?>
<div class="page-title-subheading">
Lista de servidores
</div>
</div>
<?php $this->endBlock(); ?>
<p>
<?= Html::a('<i class="fa fa-plus"></i> AƱadir nuevo', ['create'], ['class' => 'btn btn-success']) ?>
</p>
<?php Pjax::begin(['id'=>'inventario_lista','timeout'=> false,'clientOptions' => ['method' => 'POST','registerClientScript' => 'alert("lol")']]); ?>
<?= GridView::widget([
'dataProvider' => $dataProvider,
'filterModel' => $model,
'columns' => [
['class' => 'yii\grid\SerialColumn'],
[
'attribute' => 'amb_id',
'value' => 'amb.amb_desc',
'filter' => Html::activeDropDownList($model, 'amb_id', ArrayHelper::map(Ambiente::find()->asArray()->all(), 'amb_id', 'amb_desc'), [
'class' => 'form-control',
'prompt' => '--- Seleccione ---'
])
],
'inv_plataforma',
'inv_host_computername',
[
'attribute' => 'tise_id',
'value' => 'tise.tise_desc',
'filter' => Html::activeDropDownList($model, 'tise_id',ArrayHelper::map(TipoServicio::find()->orderby(['tise_desc'=>SORT_ASC])->asArray()->all(), 'tise_id', 'tise_desc'), [
'class' => 'form-control',
'prompt' => '--- Seleccione ---'
])
],
[
'attribute' => 'emp_id',
'value' => 'emp.emp_desc',
'filter' => Html::activeDropDownList($model, 'emp_id',ArrayHelper::map(Empresa::find()->orderby(['emp_desc'=>SORT_ASC])->asArray()->all(), 'emp_id', 'emp_desc'), [
'class' => 'form-control',
'prompt' => '--- Seleccione ---'
])
],
//'inv_servicio',
//'inv_ip_admin',
//'inv_ip_servicio',
//'inv_ip_nfs',
//'sad_id',
//'usu_id_responsable_sistema',
//'usu_id_2doresponsable_sistema',
//'inv_modelo_servidor',
//'prov_id',
//'inv_serial_equipo',
//'inv_codigo_remedy',
//'inv_serial_dispositivo',
//'sop_id',
//'inv_version_so',
//'inv_alta_disponibilidad',
//'inv_ubicacion',
//'inv_ala',
//'inv_fila',
//'inv_rack',
//'inv_cpu_core',
//'inv_cpu_modelo',
//'inv_cpu_velocidad',
//'inv_gb_memoria',
//'hat_id',
//'inv_tipo_contrato_proveedor',
//'inv_responsable_funcional',
//'spa_id',
//'fv_id',
//'pr_id',
//'inv_observaciones',
//'inv_performance_review',
//'inv_performance_management',
//'inv_obsoleto',
//'inv_motivo_obsoleto',
//'inv_arbol',
//'inv_arbol_1er_nivel',
//'inv_fin_venta',
//'inv_fin_partes',
//'inv_fin_soporte',
//'inv_fecha_cons_obsoleto',
['class' => 'yii\grid\ActionColumn',
'buttons'=>[
'view'=>
function($url,$model,$key){
$btn = Html::button("<i class='fa fa-eye'></i>",[
'value'=>Yii::$app->urlManager->createUrl('inventario/view/'.$key),
'class'=>'serverview grid-action btn btn-info',
'title'=>'Ver datos del servidor',
'data-toggle'=> 'modal',
'data-target'=> '#modalviewserver',
]);
return $btn;
},
'update'=>function ($url,$model,$key) {
return Html::a('<i class="fa fa-edit"></i>', ['/inventario/update/'.$key], ['class'=>'btn btn-success grid-button']);
},
],
],
],
]); ?>
<?php Pjax::end(); ?>
</div>
<?php
Modal::begin([
'title' => '<h4>Ver servidor</h4>',
'id' => 'modalviewserver',
'size' => 'modal-lg',
]);
echo "<div id='viewservercontent'></div>";
Modal::end();
?>
My action controller:
public function actionIndex()
{
$model = new InventarioSearch();
$dataProvider = $model->search(Yii::$app->request->post());
return $this->render('index', [
'dataProvider' => $dataProvider,
'model' => $model
]);
}
And my JS (just in case):
$(document).ready(function ()
{
// $("#inventariosearch-amb_id").on("pjax:end", function() {
// $.pjax.reload({container:"#inventario_lista"}); //Reload GridView
// });
$('.serverview').click(function()
{
$('#modalviewserver').appendTo("body").modal('show')
.find('#viewservercontent')
.load($(this).attr('value'));
});
});
If you want your link to refresh whole page you have to remove your pjax.
Other way, try to set your javascript in pjax:success like this:
$(document).on('ready pjax:success', function(){
//your javascript here
$('.serverview').click(function()
{
$('#modalviewserver').appendTo("body").modal('show')
.find('#viewservercontent')
.load($(this).attr('value'));
});
})
I have a table with these fields:
aca_class_subjects:
class_subject_id, class_subject_subject_id,
class_subject_class_group_id, class_subject_class_id
class_subject_id is the Primary Key and it is auto_increment.
class_subject_class_id and class_subject_class_group_id form a dependent dropdownlist.
class_subject_subject_id is from a table called aca_subjects and it will form the checkbox.
Controller: AcaClassSubjectsController
public function actionCreate()
{
$model = new AcaClassSubjects();
$searchModel = new AcaSubjectsSearch();
$searchModel->is_status = 0 ;
$dataProvider = $searchModel->search(Yii::$app->request->queryParams);
return $this->render('create', [
'searchModel' => $searchModel,
'dataProvider' => $dataProvider,
'model'=> $model,
]);
}
public function actionUpdate($id)
{
$model = $this->findModel($id);
if ($model->load(Yii::$app->request->post()) && $model->save()) {
return $this->redirect(['view', 'id' => $model->class_subject_id]);
} else {
return $this->render('update', [
'model' => $model,
]);
}
}
Model: AcaClassSubjects
public function attributeLabels()
{
return [
'class_subject_id' => Yii::t('aca', 'ID'),
'class_subject_subject_id' => Yii::t('aca', 'Subject'),
'class_subject_class_id' => Yii::t('aca', 'Class'),
'class_subject_class_group_id' => Yii::t('aca', 'Class Group'),
];
}
AcaSubjectsSearch
public function search($params)
{
$query = AcaSubjects::find()->where(['<>', 'is_status', 2]);
$dataProvider = new ActiveDataProvider([
'query' => $query, 'sort'=> ['defaultOrder' => ['subject_id'=>SORT_DESC]],
'pagination' => [ 'pageSize' => 5 ]
]);
$this->load($params);
if (!$this->validate()) {
// uncomment the following line if you do not want to any records when validation fails
// $query->where('0=1');
return $dataProvider;
}
$query->andFilterWhere([
'subject_id' => $this->subject_id,
]);
$query->andFilterWhere(['like', 'subject_name', $this->subject_name])
->andFilterWhere(['like', 'subject_code', $this->subject_code]);
return $dataProvider;
}
View
<div class="col-xs-12" style="padding-top: 10px;">
<div class="box">
<?php $form = ActiveForm::begin([
'id' => 'academic-level-form',
'enableAjaxValidation' => false,
'fieldConfig' => [
'template' => "{label}{input}{error}",
],
]); ?>
<div class="col-xs-12 col-lg-12 no-padding">
<div class="col-xs-12 col-sm-6 col-lg-6">
<?= $form->field($model, 'class_subject_class_group_id')->widget(Select2::classname(), [
'data' => ArrayHelper::map(\app\modules\academic\models\AcaClassGroups::find()->where(['is_status' => 0])->all(),'class_group_id','class_group_name'),
'language' => 'en',
'options' => ['placeholder' => '--- Select Class Group ---',
'onchange'=>'
$.get( "'.Url::toRoute('dependent/getclassmaster').'", { id: $(this).val() } )
.done(function( data ) {
$( "#'.Html::getInputId($model, 'class_subject_class_id').'" ).html( data );
}
);'
],
// 'disabled'=>'true',
'pluginOptions' => [
'allowClear' => true
],
]); ?>
</div>
<div class="col-xs-12 col-sm-6 col-lg-6">
<?= $form->field($model, 'class_subject_class_id')->widget(Select2::classname(), [
'data' => ArrayHelper::map(\app\modules\academic\models\AcaClassMaster::findAll(['class_id' => $model->class_subject_class_id]),'class_id','class_name'),
'language' => 'en',
'options' => ['placeholder' => '--- Select Class ---'],
'pluginOptions' => [
'allowClear' => true
],
]); ?>
</div>
</div>
<div class="box-body table-responsive">
<h4><strong><u>Select Subject(s)</u></strong></h4>
<div class="course-master-index">
<?= GridView::widget([
'id'=>'grid',
'dataProvider' => $dataProvider,
'filterModel' => $searchModel,
'columns' => [
[
'class' => 'yii\grid\CheckboxColumn',
'header' => Html::checkBox('selection_all', false, [
'class' => 'select-on-check-all',
'label' => 'All',
]),
'visible'=> true,
'contentOptions' =>['style' => 'vertical-align:middle;width:30px'],
'checkboxOptions' => function($model, $key, $index, $column) {
return ['value' => $model->subject_id];
}
],
['class' => 'yii\grid\SerialColumn'],
// 'id',
'subject_name',
],
]); ?>
<?= Html::input('hidden','keylists',$value='', $options=['id'=>'keylist']) ?>
<div class="form-group">
<?= Html::submitButton('Submit', ['class' =>'btn btn-success btn-block btn-lg','id'=>"button123"]) ?>
</div>
</div>
</div>
<?php ActiveForm::end(); ?>
</div>
</div>
My questions are
After selecting particular rows (subject_id) using checkboxes from Table aca_subjects, and also select the dropdownlist as shown in the diagram
How do I insert them (class_subject_subject_id,class_subject_class_id, class_subject_class_group_id) to the Table aca_class_subjects?
How do I update them (class_subject_subject_id,class_subject_class_id, class_subject_class_group_id) to the Table aca_class_subjects?
How do I display a dialogue box when nothing is selected?
Note: class_subject_subject_id (checkbox in gridview),class_subject_class_id (dropdownlist), class_subject_class_group_id (dropdownlist)
When I clicked on submit, nothing goes to the database
Well, the question is a bit broad as you haven't shown any code related to solving your problem specifically so my wild guess is that you have a basic showstopper for collecting the class_subject_subject_id from the gridview. so i will suggest the javascript part in my answer where it submits the form with ajax.
But before i suggest you a solution you have a basic problem that you are wrapping the gridview with the form you are using to insert the subjects in the aca_class_subjects
Why?
Because if you wrap the Gridview with a form along with the gridview filters the GridView does not create its own hidden form that it uses for submitting the filter inputs for search in the GridView, and hence when you will try search by typing in the GridView filter input it would submit it to the action specified in your outer form that can have a different action like in your case.
So if you still want to use the ActiveForm do not wrap the Gridview inside the form keep it separate, and close it before you call the GridView::widget() but you have the button placed in the end of the Gridview and you dont want to change the design so change the code for the button from Html::submitButton() to Html::button() and keep it outside the ActiveForm that you have created. You can submit the form with javascript.
So your view code should look like below
<div class="col-xs-12" style="padding-top: 10px;">
<div class="box">
<?php
$form = ActiveForm::begin([
'id' => 'academic-level-form',
'enableAjaxValidation' => false,
'action'=>\yii\helpers\Url::to(['assign-subjects'])
'fieldConfig' => [
'template' => "{label}{input}{error}",
],
]);
?>
<div class="col-xs-12 col-lg-12 no-padding">
<div class="col-xs-12 col-sm-6 col-lg-6">
<?=
$form->field($model, 'class_subject_class_group_id')->widget(Select2::classname(), [
'data' => ArrayHelper::map(\app\modules\academic\models\AcaClassGroups::find()->where(['is_status' => 0])->all(), 'class_group_id', 'class_group_name'),
'language' => 'en',
'options' => ['placeholder' => '--- Select Class Group ---',
'onchange' => '
$.get( "' . Url::toRoute('dependent/getclassmaster') . '", { id: $(this).val() } )
.done(function( data ) {
$( "#' . Html::getInputId($model, 'class_subject_class_id') . '" ).html( data );
}
);'
],
// 'disabled'=>'true',
'pluginOptions' => [
'allowClear' => true
],
]);
?>
</div>
<div class="col-xs-12 col-sm-6 col-lg-6">
<?=
$form->field($model, 'class_subject_class_id')->widget(Select2::classname(), [
'data' => ArrayHelper::map(\app\modules\academic\models\AcaClassMaster::findAll(['class_id' => $model->class_subject_class_id]), 'class_id', 'class_name'),
'language' => 'en',
'options' => ['placeholder' => '--- Select Class ---'],
'pluginOptions' => [
'allowClear' => true
],
]);
?>
</div>
</div>
<?=Html::input('hidden', 'keylists', $value = '', $options = ['id' => 'keylist']) ?>
<?php ActiveForm::end(); ?>
<div class="box-body table-responsive">
<h4><strong><u>Select Subject(s)</u></strong></h4>
<div class="course-master-index">
<?=
GridView::widget([
'id' => 'grid',
'dataProvider' => $dataProvider,
'filterModel' => $searchModel,
'columns' => [
[
'class' => 'yii\grid\CheckboxColumn',
'header' => Html::checkBox('selection_all', false, [
'class' => 'select-on-check-all',
'label' => 'All',
]),
'visible' => true,
'contentOptions' => ['style' => 'vertical-align:middle;width:30px'],
'checkboxOptions' => function($model, $key, $index, $column){
return ['value' => $model->subject_id];
}
],
['class' => 'yii\grid\SerialColumn'],
// 'id',
'subject_name',
],
]);
?>
<div class="form-group">
<?=Html::button('Submit', ['class' => 'btn btn-success btn-block btn-lg', 'id' => "button123"]) ?>
</div>
</div>
</div>
</div>
</div>
Now about the saving of the records.
You can get all the selected subjects that are in the grid view by using the following javascript code where you select all the checked checkboxes which have the name selection[]. Add the below code on top of your view
$reflect = new ReflectionClass($model);
$subjectId = $reflect->getShortName() . '[class_subject_subject_id][]';
$js = <<<JS
$("#button123").on('click',function(e){
e.preventDefault();
$("#academic-level-form").yiiActiveForm('submitForm');
});
$("#academic-level-form").on('beforeSubmit',function(e){
e.preventDefault();
// yii.getCsrfParam(),yii.getCsrfToken(),
let subjects=$("input[name='selection[]']:checked");
let subjectsSelected=subjects.length;
if(!subjectsSelected){
alert('select some subjects first');
}else{
let data=$(this).serializeArray();
$.each(subjects,function(index,elem){
data.push({name:"$subjectId",value:$(elem).val()})
});
let url=$(this).attr('action');
$.ajax({
url:url,
data:data,
type:'POST',
}).done(function(data){
alert(data);
}).fail(function(jqxhr,text,error){
alert(error);
});
}
return false;
});
JS;
$this->registerJs($js, \yii\web\View::POS_READY);
Now if you have print_r(Yii::$app->request->post()) inside the actionAssignSubjects() in your controller where the form is submitting you can see the output of the posted variables and your subjects will be under the same model array that you are using for populating the dropdowns with the name class_subject_subject_id and all the selected subjects would be under this array. You can loop over them to save to your desired model.
I leave the rest of the work on you to do by your self and if you run into any problems you should post a separate question with the targetted code.
I use the yii2 kartik switch input with the type radio and i want to get the value of the selected option in javascript (specially in a JsExpression), here is my code :
$model->orientation = 'Portrait';
echo $form->field($model, 'orientation')->widget(SwitchInput::classname(), [
'name' => 'information_orientation',
'type' => SwitchInput::RADIO,
'value' => 'Portrait',
'items' => [
['label' => 'Portrait   ', 'value' => 'Portrait'],
['label' => 'Paysage   ', 'value' => 'Paysage'],
],
'pluginOptions' => [
'onText' => 'Oui',
'offText' => 'Non',
'onColor' => 'success',
'offColor' => 'danger',
'size' => 'mini'
],
'labelOptions' => ['style' => 'font-size: 13px'],
]);
I have tried :
$([name='information-orientation']).val()
But it returned an undifined value
SwitchInput class does not care about the name property you give it
according to their docs, you need to wrap name in a options array
echo $form->field($model, 'orientation')
->widget(SwitchInput::classname(), [
'options' => ['name' => 'information_orientation'],
'type' => SwitchInput::RADIO,
....
from docs:
options: array the HTML attributes for the widget input tag.
edit:
you can then use the following
// to get value:
$("[name='information_orientation']").val()
// to check if the switch is or on off
$("[name='information_orientation']").prop('checked')
I want to show the sum of a gridview column in a textbox. When the page loads, the sum should pass to the textbox.
I've written the following javascript code in my index.php file. But not getting the sum. The javascript code might not be correct. Please let me know how to do it -
index.php -
<?php
use yii\helpers\Html;
use yii\grid\GridView;
/* #var $this yii\web\View */
/* #var $searchModel frontend\modules\sgledger\models\SellitemsgSearch */
/* #var $dataProvider yii\data\ActiveDataProvider */
$this->title = 'Sunglass Ledger';
$this->params['breadcrumbs'][] = $this->title;
?>
<div class="sellitemsg-index">
<h1>Sunglass Ledger</h1>
<?php // echo $this->render('_search', ['model' => $searchModel]); ?>
<div class= 'col-md-6'>
<?= GridView::widget([
'id' => 'purchasetable',
'dataProvider' => $dataProvider2,
'filterModel' => $searchModel2,
'columns' => [
['class' => 'yii\grid\SerialColumn'],
//'poisg_id',
[
'attribute' => 'Date',
'value' => 'posg.posg_date'
],
'posg_invno',
[
'attribute' => 'Vendor',
'value' => 'posg.posg_vname'
],
//'poisg_sgname',
'poisg_qty',
//['class' => 'yii\grid\ActionColumn'],
],
]); ?>
</div>
<div class= 'col-md-6'>
<?= GridView::widget([
'id' => 'selltable',
'dataProvider' => $dataProvider,
'filterModel' => $searchModel,
'columns' => [
['class' => 'yii\grid\SerialColumn'],
//'ssgi_id',
[
'attribute' => 'Date',
'value' => 'sellsg.ssg_date'
],
'ssgi_invoiceno',
[
'attribute' => 'Customer',
'value' => 'sellsg.ssg_customer'
],
//'ssgi_sgname',
//'ssgi_price',
//['class' => 'yii\grid\ActionColumn'],
],
]); ?>
</div>
</div>
<?php
/* start getting the textboxes */
$script = <<< JS
$(document).on('ready', function(e) {
var purgrid = purchasetable.getElementsByTagName('poisg_qty');
var total0 = 0;
for (var i = 0; i < purgrid.length; i++) {
var totp = purgrid[i].value
total0 = parseInt(total0) + parseInt(totp);
}
// ^ This number takes (n+1)th column
console.log('First table total value: ' + total0);
})
JS;
$this->registerJs($script);
/* end getting the textboxes */
?>
Present output -
Could be you can use showFooter for gridView
Firts you ca can calculate the value using the dataProvider
$yourTotal =0;
$numRow = 0;
foreach ($dataProvider->models as $key => $value) {
$yourTotal += $value['your_attribute'];
$numRow++;
}
Then in GridView you can set showFooter => TRUE and in the column you need you can add footer (and eventually footerOptions)
echo GridView::widget([
'dataProvider' => $dataProvider,
......
'showFooter'=>TRUE,
.....
'columns' => [
['class' => 'yii\grid\SerialColumn'],
......
[ 'attribute' => 'your_attribute',
'label' => 'Your Lable',
'footer' => $yourTotal,
'footerOptions' => ['style' => 'text-align:right;'],
],
........
and you can add you text using input
<?= Html::textInput('your_name', $yourTotal , options[]); ?>
or you can add a simple div
<div id='my_id'> <?= $yourTotal ?> </div>
The error messages on this form ('after') should be getting hidden by default and only showing when the user presses "Register" submit button. However all the error messages are being shown by default - could any help suggest why this isnt working? The javascript file is printing to the console so it can find the file. Ive put the PHP for the form and the javascript below - any help would be very much appreciated, thank you,
This is the PHP to display the form:
<div class="span5 pull-right reg-form hidden">
<?php
echo $this->Form->create('Users.Register', array(
'url' => '/register',
'class' => 'span12 pull-right'));
echo $this->Form->hidden('current_url', array('value' => $this->here));
echo $this->Form->input('username', array(
'class' => 'reg-input',
'label' => array('text' => 'Email:', 'class' => 'reg-label main-color'),
'div' => array('class' => 'span12 reg-div'),
'required' => FALSE,
'after' => '<span class="hidden show-email-err show-err">This email address is already taken</span>
<span class="hidden show-emailvalid-err show-err">This email is not valid</span>'
));
echo $this->Form->input('confirm_username', array(
'class' => 'reg-input',
'label' => array('text' => 'Confirm Email:', 'class' => 'reg-label main-color'),
'div' => array('class' => 'span12 reg-div'),
'required' => FALSE,
'after' => '<span class="hidden show-user-err show-err">Re-email is incorrect</span>'
));
echo $this->Form->input('password', array(
'class' => 'reg-input',
'label' => array('text' => 'Password:', 'class' => 'reg-label main-color'),
'div' => array('class' => 'span12 reg-div'),
'required' => FALSE,
'after' => '<span class="hidden show-pass-long show-err">Password must be at least 6 characters</span>'
));
echo $this->Form->input('confirm_password', array(
'class' => 'reg-input',
'type' => 'password',
'label' => array('text' => 'Confirm Password:', 'class' => 'reg-label main-color'),
'div' => array('class' => 'span12 reg-div'),
'required' => FALSE,
'after' => '<span class="hidden show-pass-err show-err">Re-password is incorrect</span>'
));
echo $this->Form->input('firstname', array(
'class' => 'reg-input',
'label' => array('text' => 'Name:', 'class' => 'reg-label main-color'),
'div' => array('class' => 'span12 reg-div'),
'required' => FALSE,
'after' => '<span class="hidden show-firstname-err show-err">This field must not empty</span>'
));
echo $this->Form->input('lastname', array(
'class' => 'reg-input',
'label' => array('text' => 'Last Name:', 'class' => 'reg-label main-color'),
'div' => array('class' => 'span12 reg-div'),
'required' => FALSE,
'after' => '<span class="hidden show-lastname-err show-err">This field must not empty</span>'
));
?>
<?php echo $this->Form->end(array('label' => 'Register', 'div' => false, 'id' => 'RegSubmit', 'class' => 'btn-sign pull-right')); ?>
</div>
This is the javascript:
(function($){
/** $(document).ready(function(){}) */
$(function(){
console.log('cover');
/*
$('#btn-reg').on('click', function(){
$('#RegisterUsername').val($('#LoginUsername').val());
$('.reg-form').removeClass('hidden');
});
*/
$('#RegSubmit').on('click', function(e) {
//console.log(e);
if($('.show-user-err').attr('class').indexOf('hidden') < 0)
$('.show-user-err').addClass('hidden');
var username = $('#RegisterUsername').val(),
re_username = $('#RegisterConfirmUsername').val(),
password = $('#RegisterPassword').val(),
re_password = $('#RegisterConfirmPassword').val(),
firstname = $('#RegisterFirstname').val(),
lastname = $('#RegisterLastname').val();
var check = 0;
var email_regex = /^([a-z0-9_\.-]+)#([\da-z\.-]+)\.([a-z\.]{2,6})$/;
$.each(user_emails, function(index, value){
if(value==username){
check = 1;
}
});
if(check == 1){
$('.show-err').addClass('hidden');
$('.show-email-err').removeClass('hidden');
return false;
}
if(!email_regex.test(username) || username == '') {
$('.show-err').addClass('hidden');
$('.show-emailvalid-err').removeClass('hidden');
return false;
}
if(username != re_username){
$('.show-err').addClass('hidden');
$('.show-user-err').removeClass('hidden');
return false;
}
if(password.length < 6){
$('.show-err').addClass('hidden');
$('.show-pass-long').removeClass('hidden');
return false;
}
if(password != re_password){
$('.show-err').addClass('hidden');
$('.show-pass-err').removeClass('hidden');
return false;
}
if(firstname == ''){
$('.show-err').addClass('hidden');
$('.show-firstname-err').removeClass('hidden');
return false;
}
if(lastname == ''){
$('.show-err').addClass('hidden');
$('.show-lastname-err').removeClass('hidden');
return false;
}
});
});
})(jQuery);
I'd guess that one of the other classes like show-err has display:block and that's overriding the hidden class. If you inspect the element in either Chrome or Firefox then it should show you the CSS rules that are being applied.