I have used made use of ajax before, but have not encounted this sort of problem,
here is my form
<form action="" method="post" enctype="multipart/form-data" class="m-form m-form--fit m-form--label-align-right" id="basicinfoform">
{{ csrf_field() }}
<input type="hidden" value="{{ $studentinfo->id }}" name="studentformid">
<div class="form-group m-form__group row">
<center><label for="sphoto">
<?php
$photo = "student.png";
if($studentinfo->photo !== ""){
$photo = $studentinfo->id.'.'.$studentinfo->photo;
}
?>
<img style="width:180px;height:180px;cursor:pointer;border:2px solid lightblue" id="schoollogo" src="<?php echo asset('images/passports/'.$photo) ?>" alt="">
</label>
<input onchange="getPhoto.call(this);showsavebuttonforviewstudentedit();" type="file" class="form-control m-input newb" style="display:none" value="" id="sphoto" name="sphoto" aria-describedby="emailHelp" >
<br>
<span class="m-form__help text-accent">
<b>Click the image to change it</b>
</span>
</center>
<input type="hidden" value="" id="studentid" name="studentid">
</div>
<div class="form-group m-form__group row">
<div class="col-md-4">
<label for="exampleInputPassword1">
Admission No:
</label>
<input type="text" disabled="disabled" class="form-control m-input m-input--square" value="{{ $studentinfo->admissionid }}">
</div>
<div class="col-md-4">
<label for="exampleInputEmail1">
Full name
</label>
<input type="text" name="fullname" class="form-control m-input m-input--square newb" value="{{ $studentinfo->fullname }}" onchange="showsavebuttonforviewstudentedit()">
</div>
<div class="col-md-4">
<label for="exampleInputPassword1">
Gender
</label>
<!-- <input type="password" class="form-control m-input m-input--square" id="exampleInputPassword1" placeholder="Password"> -->
<select name="gender" id="gender" class="form-control m-input m-input--square newb" onchange="showsavebuttonforviewstudentedit()">
<option value="1" {{($studentinfo->gender == "1") ? "selected" : ""}}>Male</option>
<option value="2" {{($studentinfo->gender == "2") ? "selected" : ""}}>Female</option>
</select>
</div>
</div>
<div class="form-group m-form__group row">
<div class="col-md-4">
<label for="exampleInputEmail1">
Class
</label>
<!-- <input type="text" class="form-control m-input m-input--square" id="exampleInputEmail1" aria-describedby="emailHelp" placeholder="Enter email"> -->
<select name="class" id="theclass" class="form-control m-input m-input--square newb" onchange="showsavebuttonforviewstudentedit();getArms();">
#foreach($allclasses as $list)
<option value="{{$list->id}}" {{ ($studentinfo->class == $list->id) ? "selected" : ""}}>{{ $list->classname }}</option>
#endforeach
</select>
</div>
<div class="col-md-4">
<label for="exampleInputPassword1">
Arm
</label>
<select name="arm" id="thearm" class="form-control m-input m-input--square newb" onchange="showsavebuttonforviewstudentedit()">
#foreach($allarms as $list)
<option value="{{$list->id}}" {{ ($studentinfo->arm_id == $list->id) ? "selected" : ""}}>{{ $list->arm }}</option>
#endforeach
</select>
</div>
<div class="col-md-4">
<label for="exampleInputPassword1">
House:
</label>
<select name="house" id="house" class="form-control m-input m-input--square newb" onchange="showsavebuttonforviewstudentedit()">
#foreach($allhouses as $list)
<option value="{{$list->id}}" {{ ($studentinfo->house == $list->id) ? "selected" : ""}}>{{ $list->house }}</option>
#endforeach
</select>
</div>
</div>
<div class="form-group m-form__group row">
<div class="col-md-4">
<label for="exampleInputEmail1">
Date of Birth
</label>
<input type="text" class="form-control m-input m-input--square newb" name=""dob id="dob10" value="{{ $studentinfo->dob}}" onchange="showsavebuttonforviewstudentedit()">
</div>
<div class="col-md-4">
<label for="exampleInputPassword1">
State
</label>
<select name="state" id="stateid" class="form-control m-input m-input--square newb" onchange="getLGA();showsavebuttonforviewstudentedit()">
#foreach($allstates as $list)
<option value="{{$list->StateID}}" {{ ($studentinfo->s_of_o == $list->StateID) ? "selected" : ""}}>{{ $list->State }}</option>
#endforeach
</select>
</div>
<div class="col-md-4">
<label for="exampleInputPassword1">
Local Govt.
</label>
<select name="lga" id="lgafield" class="form-control m-input m-input--square newb" onchange="showsavebuttonforviewstudentedit()">
#foreach($alllga as $list)
<option value="{{$list->lgaId}}" {{ ($studentinfo->lga == $list->lgaId) ? "selected" : ""}}>{{ $list->lga }}</option>
#endforeach
</select>
</div>
</div>
<div class="form-group m-form__group row">
<div class="col-md-4">
<!-- <input type="text" class="form-control m-input m-input--square" id="exampleInputEmail1" aria-describedby="emailHelp" placeholder="Enter email"> -->
<button type="submit" id="basicbtn" onclick="return submitStudentDetailInViewStudentPage();" disabled="disabled" class="btn btn-brand">   Save <i class="fa fa-spinner fa-spin" style="display:none"></i>  </button>
</div>
</div>
</div>
</form>
onclick of the save button, ajax is firedup, this is the ajax
form = document.getElementById('basicinfoform');
formdata = new FormData(form);
console.log(formdata)
$.ajax({
url : "/ajax/post/studentinfo",
data: formdata,
method: 'post',
processData: false,
contentType: false,
success : function (res){
if(res){
console.log(res)
}
}
});
return false;
here is my controller
public function viewStudent(Request $request, $studentid = null)
{
if(!Auth::check()){
return redirect('/');
}
if($request){
echo 'yes';
}
if(!is_null($studentid)){
$data['allstates'] = DB::table('tblstates')->get();
$data['alllga'] = DB::table('tbl_lga')->get();
$data['studentinfo'] = DB::table('tblstudents')
->where('id', $studentid)
->first();
return view('Students.viewstudents', $data);
}
return redirect('/all/students');
}
in this controller, i have set a condition to check if request has been made so to make edit, so I simply echoed 'Yes' for the sake of testing and this question. Meaning my ajax response is simply suppose to be 'Yes' string literal, but below is what I get in the as response
<!DOCTYPE html>
<!-- Required meta tags -->
--begin::Base Styles -->
<!--begin::Page Vendors -->
<link href="http://127.0.0.1:8000/assets/vendors/custom/fullcalendar/fullcalendar.bundle.css" rel="stylesheet" type="text/css" />
<!--end::Page Vendors -->
<link href="http://127.0.0.1:8000/assets/vendors/base/vendors.bundle.css" rel="stylesheet" type="text/css" />
<link href="http://127.0.0.1:8000/assets/demo/default/base/style.bundle.css" rel="stylesheet" type="text/css" />
<!-- <link rel="stylesheet" type="text/css" href="//netdna.bootstrapcdn.com/bootstrap/3.1.1/css/bootstrap.min.css"> -->
<!--end::Base Styles -->
<link rel="shortcut icon" href="http://127.0.0.1:8000/assets/demo/default/media/img/logo/favicon.ico" />
<link rel="stylesheet" type="text/css" href="http://127.0.0.1:8000/DataTables/datatables.min.css"/>
<link rel="stylesheet" type="text/css" href="http://127.0.0.1:8000/css/bootstrap.css"/>
I think it should look something like this
public function viewStudent(Request $request, $studentid = null)
{
if(!Auth::check())
{
return redirect('/');
}
if($request)
{
// echo outputs to the server, but you should really return something
// for the requester, thus we will return "YES" to the response
// and since we are returning, it will return and no further executions will made.
return 'yes';
}
if(!is_null($studentid))
{
$data['allstates'] = DB::table('tblstates')->get();
$data['alllga'] = DB::table('tbl_lga')->get();
$data['studentinfo'] = DB::table('tblstudents')
->where('id', $studentid)
->first();
return view('Students.viewstudents', $data);
}
return redirect('/all/students');
}
what happens in your case is, it echos yes, but it keeps executing the rest of the code, and it returns a view file. So you get the html response.
if you need to see the echoed text simply add exit() after the echo statement and you will get the 'Yes' response
if($request){
echo 'yes';
exit();
}
You could use return json for returning data to ajax request like
return response()->json(['success' => 'yes']);
Do not use echo for return value to ajax response
Do some functionality as your requirement in ajax call. I'm filtering table data using the search input.
$.ajax({
headers: {'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')},
type :"POST",
url :"{{route('filter')}}",
dataType:"JSON",
data :{keyword:keyword,'_token':'{!!csrf_token()!!}'},
success :function(response)
{
if (response.status=='success')
{
$('#table_body').html(response.data);
}
}
});
And now on my controller after fetching tables data using query i send the data on another blade view that i want to return in responce and my code is something like this:-
public function filter(Request $r)
{
$keyword=$r->keyword;
$orders=DB::table('orders')->where('print_orders.address','like','%' .$keyword. '%')->paginate(50);
$html=view('orders',compact('orders'))->render();
if ($this->check_count($orders)>0)
{
return response::json(['status'=>'success','data'=>$html]);
}
else
{
return response::json(['status'=>'fail','Nothing Found!!']);
}
}
Related
good afternoon everyone. I'm making a form to edit leave allocation data with jquery ajax. the form consists of (id_kategoricuti, id_karyawan,durasi, mode_alokasi, tgl_masuk, tgl_sekarang, aktif_dari, sampai).
Previously in from create, the conditions are:
when id_kategoricuti is selected, the form durasi, mode_alokasi will be filled in automatically using ajax.
For example, in the selected id_kategoricuti id form Cuti Tahunan, the tgl_masuk and tgl_sekarang forms will appear.
then, when selecting id_karyawan, the tanggal_masuk form will automatically be filled according to the entry date data in the employee table. so that only the aktif_dari and sampai forms are filled in.
condition from edit leave allocation:
data appears according to the id that has been selected.
the user makes changes to the desired data.
save.
however, I'm facing a problem on this edit form:
because when I click on one of the data to edit, what appears on the form is only id_kategoricuti and id_karyawan.
the form mode_alokasi, durasi, aktif_dari and sampai are empty.
The form was only filled in when id_karyawan/id_kagotericuti was edited.
the data in the box below the category form is the data that should appear on the form.
This is the appearance of the leave allocation edit form before editing:
this is the appearance of the leave allocation edit form after the leave id_categories are edited:
my Controller:
public function getTglmasuk(Request $request)
{
try {
$getTglmasuk = Karyawan::select('tglmasuk')
->where('id','=',$request->id_karyawan)->first();
// dd($request->id_karyawan,$getTglmasuk);
if(!$getTglmasuk) {
throw new \Exception('Data not found');
}
return response()->json($getTglmasuk,200);
} catch (\Exception $e){
return response()->json([
'message' =>$e->getMessage()
], 500);
}
}
public function getSettingalokasi(Request $request)
{
try {
$getSettingalokasi=Settingalokasi::select('id','id_jeniscuti','durasi','mode_alokasi')
->where('id_jeniscuti','=',$request->id_jeniscuti)->first();
if(!$getSettingalokasi) {
throw new \Exception('Data not found');
}
return response()->json($getSettingalokasi,200);
} catch (\Exception $e){
return response()->json([
'message' =>$e->getMessage()
], 500);
}
}
my Editalokasi.blade.php:
{{-- FORM SETTING ALOKASI--}}
<div class="modal fade" id="editalokasi{{$data->id}}" tabindex="-1" role="dialog" aria-
labelledby="editalokasi" aria-hidden="true">
<div class="modal-dialog modal-lg">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-
hidden="true">×</button>
<h4 class="modal-title" id="editalokasi">Edit Alokasi Cuti</h4>
</div>
<div class="modal-body">
<form class="input" action="/updatealokasi/{{$data->id}}" method="POST"
enctype="multipart/form-data">
#csrf
#method('POST')
<div class="panel-body">
<div class="col-md-6">
<div class="form-group col-sm">
<label for="id_jeniscuti" class="col-form-label">Kategori
Cuti</label>
<select name="id_jeniscuti" id="idjeniscuti" class="form-control">
<option value="{{$data->id_jeniscuti}}" selected>
{{$data->jeniscutis->jenis_cuti}}
</option>
#foreach ($jeniscuti as $jenis)
<option value="{{$jenis->id }}">{{ $jenis->jenis_cuti }}
</option>
#endforeach
</select>
</div>
<input type="text" class="form-control" name="durasi"
placeholder="durasi" id="idsettingalokasi" value="{{$data-
>id_settingalokasi}} --> id settingalokasi" readonly>
<input type="text" class="form-control" name="durasi"
placeholder="durasi" id="idjeniscutis" value="{{$data->id_jeniscuti}}
--> id kategori" readonly>
<input type="text" class="form-control" name="durasi"
placeholder="durasi" id="idjeniscutis" value="{{$data->id_karyawan}} -
->id karyawan" readonly>
<input type="text" class="form-control" name="durasi"
placeholder="durasi" id="idjeniscutis" value="{{$data->durasi}} Hari
--> durasi" readonly>
<input type="text" class="form-control" name="durasi"
placeholder="durasi" id="idjeniscutis" value="{{$data->mode_alokasi}}
-->mode alokasi" readonly>
<input type="text" class="form-control" name="durasi"
placeholder="durasi" id="idjeniscutis" value="
{{\Carbon\carbon::parse($data->aktif_dari)->format('m/d/Y')}} --
>aktif dari" readonly>
<input type="text" class="form-control" name="durasi"
placeholder="durasi" id="idjeniscutis" value="
{{\Carbon\carbon::parse($data->sampai)->format('m/d/Y')}} -->sampai tanggal"readonly>
<div class="form-group col-sm" id="idkaryawan">
<label for="id_karyawan" class="col-form-label">Karyawan</label>
<select name="id_karyawan" id="id_karyawan" class="form-control">
<option value="{{$data->id_karyawan}}" selected>{{$data->karyawans->nama}}</option>
#foreach ($karyawan as $data)
<option value="{{ $data->id }}">{{ $data->nama }}</option>
#endforeach
</select>
</div>
<div class="form-group">
<label for="durasi" class="col-form-label">Durasi (Hari)</label>
<input type="text" class="form-control" name="durasi" placeholder="durasi" id="duration" value="{{$data->durasi}}" readonly>
</div>
<div class="form-group">
<label for="mode_alokasi" class="col-form-label">Mode Alokasi</label>
<input type="text" class="form-control" name="mode_alokasi" placeholder="mode alokasi" value="{{$data->mode_alokasi}}" id="modealokasi" readonly>
</div>
</div>
<div class="col-md-6">
<div class="" id="tglmulai">
<div class="form-group">
<label for="tgl_masuk" class="form-label">Tanggal Masuk</label>
<div class="input-group">
<input type="text" class="form-control" placeholder="mm/dd/yyyy" id="tglmasuk" name="tgl_masuk" autocomplete="off" readonly>
<span class="input-group-addon bg-custom b-0"><i class="mdi mdi-calendar text-white"></i></span>
</div>
</div>
</div>
<div class="" id="tglnow">
<div class="form-group">
<label for="tgl_sekarang" class="form-label">Tanggal Sekarang</label>
<div class="input-group">
<input type="text" class="form-control" id="tglsekarang" name="tgl_sekarang" autocomplete="off" readonly>
<span class="input-group-addon bg-custom b-0"><i class="mdi mdi-calendar text-white"></i></span>
</div>
</div>
</div>
<div class="" id="tanggalmulai">
<div class="form-group">
<label for="tgl_mulai" class="form-label">Aktif Dari</label>
<div class="input-group">
<input type="text" class="form-control" placeholder="mm/dd/yyyy" id="datepicker-autoclosea3" name="aktif_dari" value="{{\Carbon\carbon::parse($data->aktif_dari)->format('m/d/Y')}}" autocomplete="off">
<span class="input-group-addon bg-custom b-0"><i class="mdi mdi-calendar text-white"></i></span>
</div>
</div>
</div>
<div class="" id="tanggalselesai">
<div class="form-group">
<label for="sampai" class="form-label">Sampai</label>
<div class="input-group">
<input type="text" class="form-control" placeholder="mm/dd/yyyy" id="datepicker-autoclosea4" name="sampai" value="{{\Carbon\carbon::parse($data->sampai)->format('m/d/Y')}}" autocomplete="off">
<span class="input-group-addon bg-custom b-0"><i class="mdi mdi-calendar text-white"></i></span>
</div>
</div>
</div>
</div>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-light" data-dismiss="modal">Close</button>
<button type="submit" class="btn btn-info" name="submit" value="save">Save Changes</button>
</div>
</form>
</div>
</div>
</div>
</div>
<!-- jQuery -->
<script src="assets/js/jquery.min.js"></script>
<script src="assets/js/app.js"></script>
<script src="assets/pages/form-advanced.js"></script>
my Javascript:
<!-- script to fetch data settingalokasi from table settingalokasi -->
<script>
$('#idjeniscuti').on('change',function(e){
var id_jeniscuti = e.target.value;
$.ajaxSetup({
headers: {'X-CSRF-TOKEN': $('meta[name="csrf-token"]')
.attr('content')
}
});
$.ajax({
type:"POST",
url: '{{route('get.Setting.alokasi')}}',
data: {'id_jeniscuti':id_jeniscuti},
success:function(data){
// console.log(data);
$('#idsettingalokasi').val(data.id);
$('#duration').val(data.durasi);
$('#modealokasi').val(data.mode_alokasi);
}
});
});
</script>
<!-- script to fetch data tanggal_masuk from table karyawan-->
<script>
$('#id_karyawan').on('change',function(e){
var id_karyawan = e.target.value;
$.ajaxSetup({
headers: {'X-CSRF-TOKEN': $('meta[name="csrf-token"]')
.attr('content')
}
});
$.ajax({
type:"POST",
url: '{{route('get.Tanggalmasuk')}}',
data: {'id_karyawan':id_karyawan},
success:function(data){
// console.log(data);
$('#tgl_masuk').val(data.tglmasuk);
// console.log(data?.tglmasuk)
}
});
});
</script>
<script type="text/javascript">
$(function()
{
$('#tglmulai').prop("hidden", true);
$('#tglnow').prop("hidden", true);
$('#jenicuti').on('change', function(a)
{
if(a.target.value == 1)
{
$('#tglmulai').prop("hidden", false);
$('#tglnow').prop("hidden", false);
} else
{
$('#tglmulai').prop("hidden", true);
$('#tglnow').prop("hidden", true);
}
});
});
</script>
this is my first time using JQUERY AJAX for AUTOFILL. can anyone help me to solve this problem?
I got this error yesterday and I thought I fixed it. I am submitting an update form.
#extends('layouts.master')
#section('content')
<form action="{{url('/student/update')}}" method="POST" role="form">
{{ csrf_field() }}
{{method_field('PUT')}}
<legend>Create a Student</legend>
<input type="hidden" name="id" class="form-control" value="{{$student->id}}">
<div class="form-group">
<label for="">Name</label>
<input type="text" class="form-control" name="name" value="{{$student->name }}"required="required">
</div>
<div class="form-group">
<label for="">Address</label>
<input type="text" class="form-control" name="address" value="{{$student->address }}" required="required">
</div>
<div class="form-group">
<label for="">Phone</label>
<input type="text" class="form-control" name="phone" value="{{$student->phone }}" required="required">
</div>
<div class="form-group">
<label for="">Career</label>
<select name="career" class="form-control" required="required">
<option>Select a Career</option>
<option value="math"{{$student->career == 'math' ? 'selected' : ''}}>Math</option>
<option value="physics"{{$student->career == 'physics' ? 'selected' : ''}}>Physics</option>
<option value="engineering"{{$student->career == '' ? 'engineering' : ''}}>Engineering</option>
</select>
</div>
<button type="submit" class="btn btn-primary">Update Student</button>
</form>
#endsection
The error says that it relates to my ClientController on line 82.
protected function updateOneStudent($parameters)
{
$studentId = $parameters['id'];
return $this-
>performPutRequest("https://lumenapi.juandmegon.com/students/{$studentId}",
$parameters);
}
It was the same function that was giving me the problem yesterday. The problem was that I was not calling a function. The performPutRequest function is like this.
protected function performPutRequest($url, $parameters = [])
{
$contents = $this->performAuthorizeRequest('PUT', $url, $parameters);
$decodedContents = json_decode($contents);
return $decodedContents->data;
}
Any help would be appreciated.
Thanks beginner for point me in the right direction. I had the code below.
protected function updateOneStudent($parameters)
{
$studentId = $parameters['id';
return $this->performPutRequest("https://lumenapi.juandmegon.com/students/{$studentId}", $parameters);
}
I missed a bracket from the id. So it should look like this
protected function updateOneStudent($parameters)
{
$studentId = $parameters['id'];
return $this->performPutRequest("https://lumenapi.juandmegon.com/students/{$studentId}", $parameters);
}
I am not sure why I am getting this error. Here is the method in the ClientController.
protected function updateOneStudent($parameters)
{
$studentId = $parameters['id'];
return $this- >performPutRequest("https://lumenapi.juandmegon.com/students/{$studentId}", $parameters);
}
Basically I am trying to update a selected student. Below is the update form.
#extends('layouts.master')
#section('content')
<form action="{{url('/student/update')}}" method="POST" role="form">
{{ csrf_field() }}
{{method_field('PUT')}}
<legend>Create a Student</legend>
<div class="form-group">
<label for="">Name</label>
<input type="text" class="form-control" name="name" value="{{$student->name }}"required="required">
</div>
<div class="form-group">
<label for="">Address</label>
<input type="text" class="form-control" name="address" value="{{$student->address }}" required="required">
</div>
<div class="form-group">
<label for="">Phone</label>
<input type="text" class="form-control" name="phone" value="{{$student->phone }}" required="required">
</div>
<div class="form-group">
<label for="">Career</label>
<select name="career" class="form-control" required="required">
<option>Select a Career</option>
<option value="math"{{$student->career == 'math' ? 'selected' : ''}}>Math</option>
<option value="physics"{{$student->career == 'physics' ? 'selected' : ''}}>Physics</option>
<option value="engineering"{{$student->career == '' ? 'engineering' : ''}}>Engineering</option>
</select>
</div>
<button type="submit" class="btn btn-primary">Update Student</button>
</form>
#endsection
The request I was sending was wrong. The error was in the StudentController.
I had
public function getUpdateStudent()
{
$students = $this->obtainAllStudents;
return view('students.select-student', ['students'=> $students]);
}
It it should have been
public function getUpdateStudent()
{
$students = $this->obtainAllStudents();
return view('students.select-student', ['students'=> $students]);
}
I missed the brackets to call the getUpdateStudent. Sorry guys I did not show this code earlier.
When the user picks either phone or email I want the form to then generate a box to enter the details of which they selected. How do I do this? Thanks.
<div class="field-container full clearfix">
<label class="required">What is your prefered method of contact? </label>
<select name="fields[contact]">
<option value="blank"></option>
<option value="phone">Phone</option>
<option value="email">E-mail</option>
</select>
</div>
<div class="field-container full clearfix">
<label class="required">Phone</label>
<input type="text" name="fields[phone]" value="<?= (isset($fields['phone']) ? $fields['phone'] : '' )?>"/>
</div>
<div class="field-container full clearfix">
<label class="required">E-mail Address</label>
<input type="text" name="fields[email]" value="<?= (isset($fields['email']) ? $fields['email'] : '' )?>"/>
</div>
Here's a snippet that shows you how to do that with javascript:
document.getElementById('selection').addEventListener('change',function(){
var inputs = document.querySelectorAll('.hideAndShowInput > input');
for (var i = 0; i<inputs.length;i++) {
inputs[i].setAttribute('type','hidden');
inputs[i].parentNode.style.display= 'none';
}
document.getElementById(this.value).parentNode.style.display='block';
document.getElementById(this.value).setAttribute('type',this.value);
});
<div class="field-container full clearfix">
<label class="required">What is your prefered method of contact? </label>
<select id="selection" name="fields[contact]">
<option value="blank"></option>
<option value="phone">Phone</option>
<option value="email">E-mail</option>
</select>
</div>
<div class="field-container full clearfix hideAndShowInput" style="display:none;">
<label class="required">Phone</label>
<input type="hidden" id="phone" name="fields[phone]" value="">
</div>
<div class="field-container full clearfix hideAndShowInput" style="display:none;">
<label class="required">E-mail Address</label>
<input type="hidden" id="email" name="fields[email]" value=""/>
</div>
<div class="field-container full clearfix">
<label class="required">otherField1</label>
<input type="text" id="other" name="fields[p]" value="otherField">
</div>
<div class="field-container full clearfix">
<label class="required">otherField2</label>
<input type="text" id="lsd" name="fields[em]" value="otherField2"/>
</div>
Please note that I added a Id to the select element and to the input elements.
EDIT | USAGE
Create a file, call it script.js or whatever you like and put this in it:
document.getElementById('selection').addEventListener('change',function(){
var inputs = document.querySelectorAll('.hideAndShowInput > input');
for (var i = 0; i<inputs.length;i++) {
inputs[i].setAttribute('type','hidden');
inputs[i].parentNode.style.display= 'none';
}
document.getElementById(this.value).parentNode.style.display='block';
document.getElementById(this.value).setAttribute('type',this.value);
});
Save the file to a folder on your server that is accesible. For example /public/js/script.js
In your html, add
<script src="/public/js/script.js"></script> <!-- or however your path is -->
to the very end of your file, directly before the closing </body> tag So that it looks like this
<div class="field-container full clearfix">
<label class="required">What is your prefered method of contact? </label>
<select id="selection" name="fields[contact]">
<option value="blank"></option>
<option value="phone">Phone</option>
<option value="email">E-mail</option>
</select>
</div>
<div class="field-container full clearfix hideAndShowInput" style="display:none;">
<label class="required">Phone</label>
<input type="hidden" id="phone" name="fields[phone]" value="">
</div>
<div class="field-container full clearfix hideAndShowInput" style="display:none;">
<label class="required">E-mail Address</label>
<input type="hidden" id="email" name="fields[email]" value=""/>
</div>
<div class="field-container full clearfix">
<label class="required">otherField1</label>
<input type="text" id="other" name="fields[p]" value="otherField">
</div>
<div class="field-container full clearfix">
<label class="required">otherField2</label>
<input type="text" id="lsd" name="fields[em]" value="otherField2"/>
</div>
<script src="/public/js/script.js"></script> <!-- here is the script included -->
</body>
That's it.
This worked for me:
Add an id to your select: select name="fields[contact]" id="contact"
Set phone and email fields to hidden by using a class or inline style: div class="field-container full clearfix hide-this" id="phone-container"
--or just set style: display:none;
Javascript:
$('#contact').change(function(){
if(this.selectedOptions[0].text == 'phone') {
$('#phone-container').show().focus();
}else{$('#phone-container').hide();}
});
This should do the trick... let me know?
//CODE
<!DOCTYPE html>
<html>
<head>
<style>
.field-hide{
display: none;
}
</style>
<script>
function valChange(ele){
var fields = document.getElementById("container").children;
for(var i=0; i < fields.length; i++){
fields[i].classList.add("field-hide");
}
switch(ele.value){
case "phone":
document.getElementById("phone").classList.remove("field-hide");
break;
case "email":
document.getElementById("email").classList.remove("field-hide");
break;
}
}
</script>
</head>
<body>
<div class="field-container full clearfix">
<label class="required">What is your preferred method of contact?</label>
<select type="text" name="fields[contact]" onchange="valChange(this)">
<option value="blank" selected disabled>Choose</option>
<option value="phone">Quoted</option>
<option value="email">Labour Only</option>
</select>
</div>
<div id="container">
<div class="field-container full clearfix field-hide" id="phone">
<label class="required">Phone</label>
<input type="text" name="fields[phone]" placeholder="enter phone number">
</div>
<div class="field-container full clearfix field-hide" id="email">
<label class="required">E-mail Address</label>
<input type="text" name="fields[email]" placeholder="enter email">
</div>
</div>
</body>
</html>
I have the following form that needs to feed into the database but I would like it to be validated before it can be saved into the database :
<form name="add_walkin_patient_form" class="add_walkin_patient_form" id="add_walkin_patient_form" autocomplete="off" >
<div class="form-line">
<div class="control-group">
<label class="control-label">
Patient Name
</label>
<div class="controls">
<input type="text" name="patientname" id="patientname" required="" value=""/>
</div>
</div>
<div class="control-group">
<label class="control-label">
Patient Phone Number
</label>
<div class="controls">
<input type="text" name="patient_phone" id="patient_phone" required="" value=""/>
</div>
</div>
<div class="control-group">
<label class="control-label">
Department
</label>
<div class="controls">
<select name="department" required="" class="department" id="department">
<option value="">Please select : </option>
<option value="Pharmacy">Pharmacy</option>
<option value="Laboratory">Laboratory</option>
<option value="Nurse">Nurse</option>
</select>
</div>
</div>
</div>
<button name="add_walkin_patient_button" type="submit" id="add_walkin_patient_button" class="btn add_walkin_patient_button btn-info pull-right">
Add Walk In Patient
</button>
</form>
And the submit is done by a jquery script using the following script :
<script type="text/javascript">
$(document).ready(function () {
//delegated submit handlers for the forms inside the table
$('#add_walkin_patient_button').on('click', function (e) {
e.preventDefault();
//read the form data ans submit it to someurl
$.post('<?php echo base_url() ?>index.php/reception/add_walkin', $('#add_walkin_patient_form').serialize(), function () {
//success do something
// $.notify("New Patient Added Succesfully", "success",{ position:"left" });
$(".add_walkin_patient_form").notify(
"New Walkin Patient Added Successfully",
"success",
{position: "center"}
);
setInterval(function () {
var url = "<?php echo base_url() ?>index.php/reception/";
$(location).attr('href', url);
}, 3000);
}).fail(function () {
//error do something
$(".add_walkin_patient_form").notify(
"There was an error please try again later or contact the system support desk for assistance",
"error",
{position: "center"}
);
})
})
});
</script>
How can I put form validation to check if input is empty before submitting it into the script?
I am using javascript to do the validations.
Following is the form code:
<form action="upload.php" method="post" onSubmit="return validateForm()">
<input type="text" id="username">
<input type="text" password="password">
<input type="submit" value='Login' name='login'>
</form>
To perform validation write a javascript function:
<script>
function checkform(){
var uname= document.getElementById("username").value.trim().toUpperCase();
if(uname=== '' || uname=== null) {
alert("Username is blank");
document.getElementById("username").backgroundColor = "#ff6666";
return false;
}else document.getElementById("username").backgroundColor = "white";
var pass= document.getElementById("password").value.trim().toUpperCase();
if(pass=== '' || pass=== null) {
alert("Password is blank");
document.getElementById("password").backgroundColor = "#ff6666";
return false;
}else document.getElementById("password").backgroundColor = "white";
return true;
}
</script>
You are using,
<button name="add_walkin_patient_button" type="submit" id="add_walkin_patient_button" class="btn add_walkin_patient_button btn-info pull-right">
Add Walk In Patient
</button>
Here, submit button is used for submitting a form and will never trigger click event. Because, submit will be triggered first thus causing the click event skip.
$('#add_walkin_patient_button').on('click', function (e) {
This would have worked if you have used normal button instead of submit button
<input type="button">Submit</button>
Now to the problem. There are two solution for it ,
If you use click event, then you should manually trigger submit on correct validation case,
<input type="button" id="add_walkin_patient_button">Submit</button>
//JS :
$("#add_walkin_patient_button").click(function() {
if(valid){
$("#form-id").submit();
}
Another option is to use submit event;which is triggered just after you click submit button. Here you need to either allow form submit or halt it based on your validation criteria,
$("#form-id").submit(function(){
if(invalid){
//Suppress form submit
return false;
}else{
return true;
}
});
P.S
And i would recommend you to use jQuery Validate as suggested by #sherin-mathew
make a javascript validation method (say, validateForm(), with bool return type). add [onsubmit="return validateForm()"] attribute to your form and you are done.
You need to prevent default action.
$('#add_walkin_patient_form').on('submit', function(e) {
e.preventDefault();
//Validate form and submit
});
<html>
<head>
<title></title>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css">
<!-- jQuery library -->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<!-- Popper JS -->
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.12.9/umd/popper.min.js"></script>
<!-- Latest compiled JavaScript -->
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/js/bootstrap.min.js"></script>
</head>
<body>
<style>
#first{
display: none;
}
</style>
<div class="container"><br>
<div class="col-lg-6 m-auto d-block">
<form action="" method="" onsubmit="return validation()" class="bg-light">
<div class="form-group">
<label for="">Title</label>
<span class="text-danger">*</span>
<!-- <input class="form-control" type="text" > -->
<select name="title" id="title" class="form-control" >
<option value=""class="form-control" >Select</option>
<option value="Mr" class="form-control">Mr</option>
<option value="Mrs" class="form-control">Mrs</option>
</select>
<span id="tit" class="text-danger font-weight-bold"> </span>
</div>
<div class="form-group">
<div class="row">
<div class="col">
<label for="firstName">FirstName</label>
<span class="text-danger">*</span>
<input type="text" class="form-control" placeholder="First name" id="firstName" >
<span id="first" class="text-danger font-weight-bold"> </span>
</div>
<div class="col">
<label for="lastName">LastName</label>
<span class="text-danger">*</span>
<input type="text" class="form-control" placeholder="Last name" id="lastName">
<span id="last" class="text-danger font-weight-bold"> </span>
</div>
</div>
</div>
<div class="form-group">
<label for="email">Your Email</label>
<span class="text-danger">*</span>
<input type="text" class="form-control" placeholder="Email" id="email">
<span id="fillemail" class="text-danger font-weight-bold"> </span>
</div>
<div class="form-group">
<label for="contact">Your Contact</label>
<span class="text-danger">*</span>
<input type="text" class="form-control" placeholder="Contact Number" id="contact">
<span id="con" class="text-danger font-weight-bold"> </span>
</div>
<div class="form-group">
<label for="password">Your Password</label>
<span class="text-danger">*</span>
<input type="text" class="form-control" placeholder="Password" id="password">
<span id="pass" class="text-danger font-weight-bold"> </span>
</div>
<div class="form-group">
<label for="conPassword">Confirm Password</label>
<span class="text-danger">*</span>
<input type="text" class="form-control" placeholder="Password" id="conPassword">
<span id="conPass" class="text-danger font-weight-bold"> </span>
</div>
<div class="checkbox">
<label><input type="checkbox"> I accept Terms and Conditions</label>
</div>
<div class="checkbox">
<label><input type="checkbox"> I agree to recieve Email Terms and Conditions</label>
</div>
<div class="checkbox">
<label><input type="checkbox"> I agree to recieve SMS Terms and Conditions</label>
</div>
<input type="submit" name="submit" value="SignUp" id="signUp" class="btn btn-success" autocomplete="off">
</form><br><br>
</div>
</div>
<script type="text/javascript">
function validation(){
var title = document.getElementById('title').value;
var firstName = document.getElementById('firstName').value;
var email=document.getElementById('email').value;
var contact=document.getElementById('contact').value;
var password=document.getElementById('password').value;
var conPassword=document.getElementById('conPassword').value;
var signBut=document.getElementById('signUp');
console.log(firstName);
if(title == ""){
document.getElementById("tit").innerHTML =" Please select the title feild first field";
return false;
}
// if(firstName == "" & firstName.length<=3){
// document.getElementById("first").innerHTML =" Please Enter First Name";
// return false;
// document.getElementById("signUp").addEventListener("click", function(event){
// event.preventDefault()
// });
// }
signBut.addEventListener('click',function(e){
if(firstName=="" & firstName<3)
{
document.getElementById("first").innerHTML="Please Enter proper Name";
e.preventDefault();
}
},false);
if(lastName == ""){
document.getElementById("last").innerHTML =" Please Enter Last Name";
return false;
}
else if(email ==""){
document.getElementById("fillemail").innerHTML="Please Enter Email";
}
else if(contact ==""){
document.getElementById("con").innerHTML="Please Enter Your Contact";
}
else if(password ==""){
document.getElementById("pass").innerHTML="Please Enter Your Password";
}
else if(conPassword ==""){
document.getElementById("conPass").innerHTML="Please Confirm Password";
}
}
</script>
</body>
</html>
I think you should use type button
and then eventClick function of jquery