Default value of drop-down list with JavaScript and JSON - drop-down-menu

I have a City field in my form when user select his province/state a drop-down list of cities appear according to selected state. However for the cities list there is no default value like 'Select your city'. I want to add this value.
Below is my field.js :
function getAjaxReqest(action, selectCountry, stateId, normalImput,selectedCity) {
var request = new Ajax.Request(action,
{
method: 'GET',
onSuccess: function (data) {
$('billing:city').replace('<select id="billing:city" name="billing[city]" class="required-entry">' +
'<option value=""></option>' + convertJsonToHtml(data.responseText, this,selectedCity) +
'</select>');
},
onFailure: $('billing:city').replace(normalImput),
parameters: {city_id: stateId, country_id: selectCountry}
}
);
}
function getAjaxReqestCustomer(action, selectCountry, stateId, normalImput, selectedCity) {
var request = new Ajax.Request(action,
{
method: 'GET',
onSuccess: function (data) {
$('city').replace('<select id="city" name="city" class="required-entry">' +
'<option value=""></option>' + convertJsonToHtml(data.responseText, this, selectedCity) +
'</select>');
},
onFailure: $('city').replace(normalImput),
parameters: {city_id: stateId, country_id: selectCountry}
}
);
}
function getAjaxReqestShip(action, selectCountry, stateId, normalImput,selectedCity) {
if (normalImput != null) {
var resetShip = true;
} else {
var resetShip = false;
}
var request = new Ajax.Request(action,
{
method: 'GET',
onSuccess: function (data) {
$('shipping:city').replace('<select id="shipping:city" name="shipping[city]" class="required-entry">' +
'<option value=""></option>' + convertJsonToHtml(data.responseText, this,selectedCity) +
'</select>');
},
onFailure: function (resetShip) {
if (resetShip) {
$('shipping:city').replace(normalImput)
}
},
parameters: {city_id: stateId, country_id: selectCountry}
}
);
}
function convertJsonToHtml(data, ship, selectedCity) {
var jsonData = data.evalJSON();
if (jsonData.length == 0) {
ship.replace(normalImput);
return;
}
console.log(jsonData);
htmlData = '';
jsonData.each(function (item) {
if (item.cityname == selectedCity) {
htmlData += '<option value="' + item.cityname + '" selected>' + item.cityname + '</option>';
} else {
htmlData += '<option value="' + item.cityname + '">' + item.cityname + '</option>';
}
});
return htmlData;
}
While the following code generates the City field on frontend in the form.
<div class="input-box">
<input type="text" title="<?php echo $this->__('City') ?>" name="billing[city]"
value="<?php echo $this->escapeHtml($this->getAddress()->getCity()) ?>"
class="input-text <?php echo $this->helper('customer/address')->getAttributeValidationClass('city') ?>"
id="billing:city"/>
</div>
Any help and tips are appreciated.I am a novice in Javascript and JSON so i am having a hard time playing with it.
EDIT:
I tried this:
div class="input-box">
<input type="text" title="<?php echo $this->__('City') ?>" name="billing[city]"
value="<?php echo $this->escapeHtml($this->getAddress()->getCity()) ?>"
class="input-text <?php echo $this->helper('customer/address')- >getAttributeValidationClass('city') ?>"
id="billing:city"/>
<select name="anything"><option value="undefined" disabled="selected">Select your city</option></select>
</div>
This works but adds the text 'Select your city' below the city field NOT inside it.

use this code as default showing before selecting city (i.e)set value as "undefined" disabled selected.
' +
'Select your city' + convertJsonToHtml(data.responseText, this, selectedCity) +
''

Related

How can I fetch autocomplete data into their respected element using Ajax and Laravel?

Here is my problem.
I'm trying to fetch the data from an auto-completing text-box.
There are two text-boxes:
Region and province.
I have successfully fetched the data on the text-box having region as name.
My problem is, it gives the same value to the next text-box having province as name.
In my Laravel blade I have this code:
<input id="region" type="text" class="form-control" name="region" value="" required autofocus>
<div id="regionList"> </div>
<input id="province" type="text" class="form-control" name="province" value="" required autofocus>
<div id="provinceList"> </div>
I have also a javascript file named auto-complete
$(document).ready(function() {
$('#region').keyup(function() {
var region = $(this).val();
if (region != '')
{
var _token = $('input[name="_token"]').val();
$.ajax({
url: "register/showRegion",
method: "POST",
data: { region: region, _token: _token },
success: function(data)
{
$('#regionList').fadeIn();
$('#regionList').html(data);
}
});
}
});
$(document).on('click', 'li', function() {
$('#region').val($(this).text());
$('#regionList').fadeOut();
});
$('#province').keyup(function() {
var province = $(this).val();
if (province != '')
{
var _prov_token = $('input[name="_token"]').val();
$.ajax({
url: "register/showProvince",
method: "POST",
data: { province: province, _token: _token },
success: function(data)
{
$('#provinceList').fadeIn();
$('#provinceList').html(data);
}
});
}
});
$(document).on('click', 'li', function() {
$('#province').val($(this).text());
$('#provinceList').fadeOut();
});
});
And on my routes I included this
Route::post('/register/showRegion', 'LocationController#showRegion');
Route::post('/register/showProvince', 'LocationController#showProvince');
And on my controller is this
public function index() {
return view('auth.register');
}
function showRegion(Request $request)
{
if ($request->get('region'))
{
$region = $request->get('region');
$regions = Refregion::where('regDesc', 'LIKE', "$region%")->get();
$output = '<ul class="dropdown-menu" style="display:block; position:absolute;">';
foreach($regions as $region)
{
$output .= '<li>'.$region->regDesc.'</li>';
}
$output .= '</ul>';
echo $output;
}
}
function showProvince(Request $request)
{
if ($request->get('province'))
{
$province = $request->get('province');
$province = Refprovince::where('provDesc', 'LIKE', "province%")->get();
$output = '<ul class="dropdown-menu" style="display:block; position:absolute;">';
foreach($provinces as $province)
{
$output .= '<li>'.$province->provDesc.'</li>';
}
$output .= '</ul>';
echo $output;
}
}
I'm trying to figure out why it gives the same value to the other text-box "province" when I have selected region.
Can someone help me with this, or at least explain to me why this happen?
Thank you
change it
$(document).on('click', 'li', function() {
$('#region').val($(this).text());
$('#regionList').fadeOut();
});
on this
$('#regionList').on('click', 'li', function() {
$('#region').val($(this).text());
$('#regionList').fadeOut();
});
and change it
$(document).on('click', 'li', function() {
$('#province').val($(this).text());
$('#provinceList').fadeOut();
});
on this
$('#provinceList').on('click', 'li', function() {
$('#province').val($(this).text());
$('#provinceList').fadeOut();
});

A dropdown in the laravel for filtering table data

I want to know something in Laravel. I want a dropdown for classes so when the user selects any class and press the submit button then the users related to that specific class will be displayed below in the table... Is it possible?
Below is the code I did for getting the data but I want this data to refer to my table in the HTML because there is something more I want and I can't add those things to the ajax table
//My ajax
$(document).ready(function() {
$('select[name="students_class_id"]').on('change', function() {
var classID = $(this).val();
if(classID) {
$.ajax({
url: '/myform/ajax/'+classID,
type: "GET",
dataType: "json",
success:function(data) {
var markup = '';
$.each(data, function(key, value) {
markup += '<tr> <td>' + value.id + '</td> <td>' + value.student_id + '</td> <td>' + value.first_name+ ' ' + value.last_name + '</td> <tr>';
});
$('table[id="studentsData"]').html(markup);
}
});
}
});
});
//Controller
public function index(Request $request){
$classes = StudentsClass::pluck('class_name', 'id')->all();
return view('admin.students.attendance.index', compact( 'classes'));
}
public function mytableAjax($id) {
$students = Student::where('students_class_id', $id)->get();
return json_encode($students);
}
//My view
<select name="students_class_id" class="form-control" style="width:350px">
<option value="">--- Select State ---</option>
#foreach ($classes as $key => $value)
<option value="{{ $key }}">{{ $value }}</option>
#endforeach
</select>
<table id="studentsData" class="table table-striped table-bordered table-list-search">
<thead>
<tr>
<th>#</th>
<th>Student ID</th>
<th>Student Name</th>
<th>Attendance</th>
</tr>
</thead>
<tbody>
<tr>
<td>
<div class="form-group">
<select class="form-control" id="gender">
<option>Present</option>
<option>Absent</option>
<option>Leave</option>
</select>
</div>
</td>
</tr>
</tbody>
</table>
<a class="fas fa-folder-open btn btn-success float-right mb-4 mr-2"> Save</a>
</div>
Check the following code that will add the attendance column for every row :
$(document).ready(function() {
$('select[name="students_class_id"]').on('change', function() {
var classID = $(this).val();
if (classID) {
$.ajax({
url: '/myform/ajax/' + classID,
type: "GET",
dataType: "json",
success: function(data) {
var attendance = `<div class="form-group">
<select class="form-control" id="gender" name="attendance[]">
<option>Present</option>
<option>Absent</option>
<option>Leave</option>
</select>
</div>`;
var markup = '';
$.each(data, function(key, value) {
markup += '<tr> <td><input type="hidden" value="'+value.id+'" name="id[]">' + value.id + '</td> <td>' + value.student_id + '</td> <td>' + value.first_name + ' ' + value.last_name + '</td> <td> ' + attendance + '</td> <tr>';
});
$('#studentsData tbody').html(markup);
var thead_markup += '<tr> <th>A</th> <th>B</th> <th>C</th> <td>D</th> <tr>';
$('#studentsData thead').html(thead_markup);
}
});
}
});
});
It depends upon your code, if you are using ajax datatables api then here is a similar example:
$(document).ready(function() {
$('#example').DataTable( {
initComplete: function () {
this.api().columns().every( function () {
var column = this;
var select = $('<select><option value=""></option></select>')
.appendTo( $(column.footer()).empty() )
.on( 'change', function () {
var val = $.fn.dataTable.util.escapeRegex(
$(this).val()
);
column
.search( val ? '^'+val+'$' : '', true, false )
.draw();
} );
column.data().unique().sort().each( function ( d, j ) {
select.append( '<option value="'+d+'">'+d+'</option>' )
} );
} );
}
} );
} );
Reference: datatables.net multi filter select
If you are not using datatables api and do not want ajax then use below code and change according to your need:
$("#selectDropdown").on("change", function () {
var value = $(this).val();
$("table tr").each(function (index) {
if (index != 0) {
$row = $(this);
var id = $row.find("td:first").text();
if (id.indexOf(value) != 0) {
$(this).hide();
}
else {
$(this).show();
}
}
});
});

Fetch corresponding value of a drop downlist

I want to fetch the corresponding value of my dropdown the image below shows the form and the database. the table was inside the javascript and Iam having a dificult time in figuring out this problem. please help me how to solve this problem... Thank you very much in advance...
Database
forms entry
My Controller
function getFeetypeEndDate() {
$feetype_id = $this->input->get('feety_id[]');
$data = $this->feegroup_model->getFeetypeByEndDate($feetype_id);
echo json_encode($data);
}
My Model
public function get($id = null) {
$this->db->select()->from('feetype');
$this->db->where('is_system', 0);
if ($id != null) {
$this->db->where('id', $id);
} else {
$this->db->order_by('id');
}
$query = $this->db->get();
if ($id != null) {
return $query->row_array();
} else {
return $query->result_array();
}
}
My Javascript in the View Section
<script>
$(document).ready(function (){
$("body").on('click', '.btn-add-more', function (e) {
e.preventDefault();
var amount = $("#amount").val();
var penalty = $("#penalty").val();
var $sr = ($(".jdr1").length + 1);
var rowid = Math.random();
var $html = '<tr class="jdr1" id="' + rowid + '">' +
'<td><span class="btn btn-sm btn-default">' + $sr + '</span><input type="hidden" name="count[]" value="'+Math.floor((Math.random() * 10000) + 1)+'"></td>' +
'<td><select id="feetype_id[]" name="feetype_id[]" class="form-control" >' +
'<?php foreach ($feetypeList as $feetype) { ?>' +
' <option value="<?php echo $feetype['id'] ?>" ' +
'<?php if (set_value('feetype_id[]') == $feetype['id']) { echo "selected =selected"; } ?>><?php echo $feetype['type'] ?></option> <?php $count++; } ?> </select></td>' +
'<td><input type="text" id="startDate" name="startDate" value="<?php echo date($this->customlib->getSchoolDateFormat($feetype->start_date), $this->customlib->dateyyyymmddTodateformat($feetype->start_date)); ?>" placeholder="Start Date" class="form-control input-sm"/></td>' +
'<td><input type="text" id="endDate" name="endDate" value="<?php echo date($this->customlib->getSchoolDateFormat($feetype->end_date), $this->customlib->dateyyyymmddTodateformat($feetype->end_date)); ?>" placeholder="End Date" class="form-control input-sm"/></td>' +
'<td><input type="text" name="amount_td[]" placeholder="Amount" class="form-control input-sm" value="'+amount+'"></td>' +
'<td><input type="text" name="penalty_td" placeholder="Penalty" class="form-control input-sm" value="'+penalty+'"></td>' +
'</tr>';
$("#table-details").append($html);
});
$("body").on('click', '.btn-remove-detail-row', function (e) {
e.preventDefault();
if($("#table-details tr:last-child").attr('id') != 'row1'){
$("#table-details tr:last-child").remove();
}
});
});

Form submission using AJAX and handling response in Wordpress Website

I have a wordpress website. I have made a contact form and it is POSTed by AJAX.
Here's the code:
<script type="text/javascript">
jQuery(document).ready(function(){
$("#error_box").hide();
$('#contact_form').submit(function(e){
// prevent the form from submitting normally
e.preventDefault();
var na=$("#1").val();
var email2=$("#2").val();
var subject2 = $("#3").val();
var message2 = $("#4").val();
var mydata = "pn2="+na+"&email="+email2+"&subject="+subject2+"&msg="+message2;
alert(mydata);
$("#contact_form").css({"opacity":"0.1"});
$.ajax ({
type: 'POST',
url: $(this).attr.action, // Relative paths work fine
data: mydata,
success: function(){
$("#contact_form").css({"opacity":"1"});
$('#error_box').fadeIn('fast').css({"height": "auto"});
}
});
});
});
</script>
When the form is submitted, I want the error box (#error_box) to display a message according to the data submitted, for example if one of the fields is empty it should display an error, or display a success message if the processing is successful and the form has been mailed. Is there any way I can do this?
[UPDATE]
Here's my contact-form.php file(the action)
<?php if(isset($_POST['pn2']) && isset($_POST['email']) && isset($_POST['subject']) && isset($_POST['msg']))
{
if(empty($_POST['pn2']) || empty($_POST['email']) || empty($_POST['subject']) || empty($_POST['msg'])){
echo 'EMPTY ERROR';
}
else
{
$name = $_POST['pn2'];
$email = $_POST['email'];
$subj = $_POST['subject'];
$msg = $_POST['msg'];
$to = "ankushverma61#gmail.com";
$mail_cont = "FROM: $person_name. \n Email: $email. \n Msg: $msg";
echo "success";
mail($recipient, $subj, $mail_cont) or die("UNABLE TO SEND!!!");
}
}
?>
Form submission using Ajax call
Contact Form
<form action="#" id="contactForm" method="post">
<input class="require" type="text" placeholder="First Name" name="firstName">
<span class="fieldError"></span>
<input class="require" type="text" placeholder="Last Name" name="lastName">
<span class="fieldError"></span>
.
.
.
<input type="submit" value="Submit">
</form>
client side validation with ajax call
jQuery('#contactForm').submit(ajaxSubmit);
function ajaxSubmit(){
var newContactForm = jQuery(this).serialize();
var flag = 0;
jQuery('.require', '#contactForm').each(function(){
var inputVal = jQuery(this).val();
if(jQuery.trim(inputVal) === ""){
flag = 1;
jQuery(this).next().html("Can't be blank");
jQuery(this).next().show();
}
else{
jQuery(this).next().hide();
}
});
if(flag){
return false;
}
jQuery.ajax({
type:"POST",
url: "/wp-admin/admin-ajax.php?action=contactForm",
data: newContactForm,
success:function(data){
jQuery(':input','#contactForm')
.not(':button, :submit, :reset, :hidden')
.val('')
.removeAttr('checked')
.removeAttr('selected');
jQuery("#feedback").html(data);
jQuery("#feedback").fadeOut(10000);
},
error: function(errorThrown){
alert(errorThrown);
}
});
return false;
}
store form data in db and send mail
add the following code in functions.php
wp_enqueue_script('jquery');
add_action('wp_ajax_addContactForm', 'addContactForm');
add_action('wp_ajax_nopriv_addContactForm', 'addContactForm');
function addContactForm(){
global $wpdb;
$first_name = $_POST['firstName']; $last_name = $_POST['lastName'];
$email = $_POST['email'];
.
.
.
if($wpdb->insert('table_name',array(
'first_name' => $first_name,
'last_name' => $last_name,
'email' => $email,
.
.
.
))===FALSE){
echo "Error";
}
else {
$headers = 'From: xyz <xyz#xyz.com>';
$subject = "Thank you";
$body = "<p>Thank you</p><p>.........</p>";
wp_mail( $email, $subject, $body, $headers);
echo "<div class='success'>Thank you for filling out your information, we will be in contact shortly.</div>";
}
exit;
}
You should use:
$.ajax ({
type: 'POST',
url: $(this).attr.action,
data: mydata,
success: function(response) { // here you receive response from you serverside
$("#contact_form").css({"opacity":"1"});
$('#error_box').html(response).fadeIn('fast').css({"height": "auto"});
}
});
Your server action url: $(this).attr.action, should return message which be inserted in #error_box
First create form like this
<p class="register-message"></p>
<form action="#" method="POST" name="testregister" class="register-form">
<fieldset>
<label><i class="fa fa-file-text-o"></i> Register Form</label>
<input type="text" name="firstname" placeholder="Username" id="firstname">
<p id="firstname-error" style="display:none">Firstname Must be Enter</p>
<input type="email" name="email" placeholder="Email address" id="email">
<p id="email-error" style="display:none">Email Must Be Enter</p>
<input type="submit" class="button" id="test" value="Register">
</fieldset>
</form>
then bind the click and send ajax call
<script type="text/javascript">
jQuery('#test').on('click', function(e) {
e.preventDefault();
var firstname = jQuery('#firstname').val();
var email = jQuery('#email').val();
if (firstname == "") {
jQuery('#firstname-error').show();
return false;
} else {
jQuery('#firstname-error').hide();
}
if (email == "") {
jQuery('#email-error').show();
return false;
} else {
jQuery('#email-error').hide();
}
jQuery.ajax({
type: "POST",
dataType: 'json',
url: "<?php echo admin_url('admin-ajax.php'); ?>",
data: {
action: "test", // redirect function in function.php
firstname: firstname,
email: email
},
success: function(results) {
//console.log(results);
if (results == "1") {
jQuery('.register-message').text("Email already exist");
} else {
jQuery('.register-message').text("Register successfu");
}
},
error: function(results) {}
});
});
</script>
In function.php add the below code to insert data in table
<?php
//
add_action('wp_ajax_test', 'test', 0);
add_action('wp_ajax_nopriv_test', 'test');
function test()
{
$firstname = stripcslashes($_POST['firstname']);
$email = stripcslashes($_POST['email']);
global $wpdb;
$q = $wpdb->prepare("SELECT * FROM wp_test WHERE email='" . $email . "' ");
$res = $wpdb->get_results($q);
if (count($res) > 0) {
echo "1";
} else {
$user_data = array(
'firstname' => $firstname,
'email' => $email
);
$tablename = $wpdb->prefix . 'test';
$user_id = $wpdb->insert($tablename, $user_data);
echo "0";
}
die;
}

Making Dependent Combobox in codeigniter project

i am suffering greatly but still unable to make a dependent dropdown box in Codeigniter .
Here is the schema :
groups(group_id,group)
forum(forum_id,subject)
group_forum(group_id,forum_id)
Here is my code :
model
function get_group(){
$query = $this->db->get('group');
return $query->result();
}
function get_subject_by_group($id)
{
$subjects=array();
$this->db->from('forum');
$this->db->join('group_forum','group_forum.forum_id=forum.forum_id','group_id='.$id);
$q=$this->db->get();
foreach($q->result() as $y)
{
$subjects[$y['forum_id']] = $y['subject'];
}
return $subjects;
}
}
Controller:
<?php
class C_control_form extends CI_Controller {
function add_all(){
#Validate entry form information
$this->load->model('Model_form');
$this->form_validation->set_rules('f_group', 'Group', 'trim|required');
$this->form_validation->set_rules('f_forum', 'Forum', 'trim|required');
$data['groups'] = $this->Model_form->get_group(); //gets the available groups for the dropdown
if ($this->form_validation->run() == FALSE)
{
$this->load->view('header_for_combo',$data);
$this->load->view('view_form_all', $data);
$this->load->view('footer_for_combo',$data);
}
else
{
#Add Member to Database
$this->Model_form->add_all();
$this->load->view('view_form_success');
}
}
function get_subjects($group)
{
//echo "hi";
$this->load->model('Model_form');
header('Content-Type: application/x-json; charset=utf-8');
echo (json_encode($this->Model_form->get_subject_by_group($group)));
}
}
?>
View
<html>
<head>
<script type="text/javascript" src="<?php echo base_url("js/jquery-1.7.2.min.js"); ?>" ></script>
<script type="text/javascript">
// $('#f_group, #f_forum').hide();
$(document).ready(function(){
$('#f_group').change(function(){
var group_id = $('#f_group').val();
if (group_id != ""){
var post_url = "index.php/c_control_form/get_subjects/"+group_id;
// var post_url = "<?php echo base_url();?>"+"c_control_form/get_subjects"+group_id;
$.ajax({
type: 'POST',
url: post_url,
dataType : 'json',
success: function(subjects) //we're calling the response json array 'cities'
{
$("#f_forum > option").remove();
// $('#f_forum').empty();
// $('#f_forum, #f_forum_label').show();
$.each(subjects,function(forum_id,subject)
{
var opt = $('<option/>'); // here we're creating a new select option for each group
opt.val(forum_id);
//alert(id);
opt.text(subject);
$('#f_forum').append(opt);
});
} //end success
}); //end AJAX
} else {
$('#f_forum').empty();
// $('#f_forum, #f_forum_label').hide();
}//end if
}); //end change
});
</script>
</head>
<body>
<?php echo form_open('c_control_form/add_all'); ?>
<p>
<label for="f_group">Group<span class="red">*</span></label>
<select id="f_group" name="f_group">
<option value=""></option>
<?php
foreach($groups as $group){
echo '<option value="' . $group->group_id . '">' . $group->group_name.'</option>';
}
?>
</select>
</p>
<p>
<label for="f_forum">Subject<span class="red">*</span></label>
<select id="f_forum" name="f_forum" id="f_forum_label">
<option value=""></option>
</select>
</p>
<?php echo form_close(); ?>
</body>
Please change
$subjects[$y['forum_id']] = $y['subject'];
to
$subjects[$y->forum_id] = $y->subject;
in the model file. Also spaces or newlines in model php file after and before the php tags.
EDIT: Added below
function(subjects){
var select = $('#f_forum').empty();
$.each(subjects.values, function(i,item) {
select.append( '<option value="'
+ item.id
+ '">'
+ item.name
+ '</option>' );
});

Resources