Auto populate dropdown fields doesn't work - javascript

I have 2 drop down fields which both auto populated.
Example :
car_model -> dropdown_field1
car_model_variants -> dropdown_field2
When I select a model in car_model field, car_model_variants must update its values.
In my case, I have index.php where you can click a button that will show the modal box and you'll find the auto populated drop down fields.
First attempt, when selecting a car_model it works the car_model_variants field is updating its values. But it doesn't work if I submit a form when car_model_variants is empty, If I try to select a car_model again? the dropdown 2 field is not updating. Below is my code.
(function ($) {
$('.edit').formPopup({
'modalParams': {
'parent_container': $('div.autodeal')
},
'callback': function (settings)
{
$('.modal')
.addClass('large')
.css({'z-index': 101});
$('#used_car_car_model').change(function () {
var select = $(this);
$.ajax({
'url': '{{ path("autodeal_backend_filter_select") }}',
'data': {'carModelId': select.val(), 'carGuideOnly': 0, 'isVerified': 1, 'showCompleteName': 1},
success: function (html)
{
$('#used_car_car_model_variant').html(html);
}
});
});
},
'formSubmitParams': {
'retainFormUrl': false,
'submit_callback': function ()
{
window.location.reload();
},
'error_callback': function (form, settings)
{
$('.close, .exit', $(settings.container))
.click(function () {
window.location.reload();
});
}
}
});
})(jQuery);
Here's the full code.
<form novalidate="" action="/app_dev.php/used-car-listings/164/edit" method="POST">
<div class="marginbottom row gutters">
<div class="col span_12">
<div>
<div>
<label for="used_car_plate_number" class="required">Plate number</label>
<input type="text" id="used_car_plate_number" name="used_car[plate_number]" required="required" value="GS0909">
</div>
<div>
<label for="used_car_year" class="required">Year</label>
<input type="text" id="used_car_year" name="used_car[year]" required="required" value="2015">
</div>
<div>
<label for="used_car_car_model" class="required">Car Model</label>
<select id="used_car_car_model" name="used_car[car_model]" required="required">
<option value="">Select A Model</option><option value="102">Mercedes-Benz A-Class</option><option value="401" selected="selected">Mercedes-Benz AMG</option><option value="103">Mercedes-Benz B-Class</option><option value="105">Mercedes-Benz C-Class Coupe</option><option value="104">Mercedes-Benz C-Class Sedan</option><option value="115">Mercedes-Benz CLA-Class</option><option value="576">Mercedes-Benz CLC-Class</option><option value="577">Mercedes-Benz CLK-Class</option><option value="106">Mercedes-Benz CLS-Class</option><option value="107">Mercedes-Benz E-Class</option><option value="578">Mercedes-Benz G-Class</option><option value="108">Mercedes-Benz GL-Class</option><option value="109">Mercedes-Benz GLK-Class</option><option value="110">Mercedes-Benz M-Class</option><option value="111">Mercedes-Benz S-Class</option><option value="112">Mercedes-Benz SL-Class</option><option value="113">Mercedes-Benz SLK-Class</option><option value="114">Mercedes-Benz SLS-Class</option><option value="579">Mercedes-Benz Viano</option></select>
</div>
<div>
<label for="used_car_car_model_variant" class="required">Car Model Variant</label>
<select id="used_car_car_model_variant" name="used_car[car_model_variant]" required="required"><option value="">Select Mercedes-Benz A-Class Variant</option><option value="343">2014 Mercedes-Benz A-Class A 250 Sport 4MATIC</option><option value="344">2014 Mercedes-Benz A-Class A 45 AMG</option></select>
</div>
<div>
<label for="used_car_mileage" class="required">Mileage</label>
<input type="text" id="used_car_mileage" name="used_car[mileage]" required="required" value="1700">
</div>
<div>
<label for="used_car_price" class="required">Price</label>
<input type="text" id="used_car_price" name="used_car[price]" required="required" value="3288300">
</div>
<div>
<label for="used_car_used_car_color" class="required">Color</label>
<select id="used_car_used_car_color" name="used_car[used_car_color]" required="required">
<option value="">Select A Color</option><option value="1">Red</option><option value="2">Blue</option><option value="3">Black</option><option value="4">White</option><option value="5">Green</option><option value="6">Silver</option><option value="7" selected="selected">Grey</option><option value="8">Yellow</option><option value="9">Brown</option><option value="10">Beige</option><option value="11">Orange</option><option value="12">Purple</option><option value="13">Pink</option><option value="14">Turquoise</option><option value="15">Bronze</option></select>
</div>
<div>
<label for="used_car_description" class="required">Description</label>
<textarea id="used_car_description" name="used_car[description]" required="required" cols="4" rows="3">Body color, Tenorite Gray</textarea>
</div>
<div>
<label class="required">City</label>
<input type="hidden" id="used_car_city_id" name="used_car[city][id]" value="20"><input type="text" id="used_car_city_text" name="used_car[city][text]" required="required" autocomplete="off" value="San Juan, Metro Manila">
</div>
<div>
<label class="required">Is service record submitted</label>
<div id="used_car_is_service_record_submitted"><label class="marginleft marginright"><input type="radio" id="used_car_is_service_record_submitted_0" name="used_car[is_service_record_submitted]" required="required" value="1">Yes
</label><label class="marginleft marginright"><input type="radio" id="used_car_is_service_record_submitted_1" name="used_car[is_service_record_submitted]" required="required" value="0" checked="checked">No</label></div>
</div>
<div>
<label class="required">Is LTO verified</label>
<div id="used_car_is_lto_verified"><label class="marginleft marginright"><input type="radio" id="used_car_is_lto_verified_0" name="used_car[is_lto_verified]" required="required" value="1" checked="checked">Yes
</label><label class="marginleft marginright"><input type="radio" id="used_car_is_lto_verified_1" name="used_car[is_lto_verified]" required="required" value="0">No
</label></div>
</div>
<div>
</div>
</div>
<input type="hidden" id="used_car__token" name="used_car[_token]" value="4e4UOHBr5SmtV7Pb0WoWv4xSz90LoVarNG8hw0dy_RY"> <hr class="nomargin marginbottom30 margintop20">
<div class="row">
<button type="submit" class="button">Save</button>
</div>
</form>

Related

Knockoutjs checked binding function call issue

I am trying to call a function when the check box is checked and set the field values accordingly. The checkbox and the address fields are like below
<div class="form-check">
<input class="form-check-input position-static" type="checkbox" id="SameAsShippingAddress" value="SameAsShippingAddress" data-bind="checked: sameAsShippingAddress" />
<label>Check this box if Shipping Address and Billing Address are the same.</label>
</div>
<div class="row">
<div class="col-md-6">
<h4>Shipping Address:</h4>
<div class="form-group required">
<label for="EmailCompetitor" class="control-label">Email:</label>
<input type="email" maxlength="150" id="EmailCompetitor" name="EmailCompetitor" class="form-control" data-bind="value: emailCompetitor" required />
</div>
<div class="form-group required">
<label for="FirstNameCompetitor" class="control-label">First Name:</label>
<input type="text" maxlength="150" id="FirstNameCompetitor" name="FirstNameCompetitor" class="form-control" data-bind="value: firstNameCompetitor" required />
</div>
</div>
<div class="col-md-6">
<h4>Billing Address:</h4>
<div class="form-group required">
<label for="EmailCompetitor_Billing" class="control-label">Email:</label>
<input type="email" maxlength="150" id="EmailCompetitor_Billing" name="EmailCompetitor_Billing" class="form-control" data-bind="value: emailCompetitor_Billing" required />
</div>
<div class="form-group required">
<label for="FirstNameCompetitor_Billing" class="control-label">First Name:</label>
<input type="text" maxlength="150" id="FirstNameCompetitor_Billing" name="FirstNameCompetitor_Billing" class="form-control" data-bind="value: firstNameCompetitor_Billing" required />
</div>
</div>
I want the check box boolean value captured seperately as well as when check box is checked it needs to call the function. So in js I have like
var orderRequestFormViewModel = function () {
var self = this;
self.currentPage = ko.observable(1);
self.referringPage = ko.observable();
...............
self.sameAsShippingAddress = ko.observable().extend({ required: false });
..........
self.sameAsShippingAddress = function () {
if (this.checked) {
$("#EmailCompetitor_Billing").val($("#EmailCompetitor").val());
$("#FirstNameCompetitor_Billing").val($("#FirstNameCompetitor").val());
} else {
$("#EmailCompetitor_Billing").val("");
$("#FirstNameCompetitor_Billing").val("");
}
}
But when the checkbox is checked/unchecked this function is not being called at all
I tried put the breakpoint but the function is not being it. New to this JS world, any help is greatly appreciated
Hey I made you a little snippet to show you that it works perfectly fine when using an observable and checked binding, when checkbox is checked, it is "true" if not it´s "false"
To make custom stuff like setting .val() of other input just use a computed function, it will be called whenever isChecked changes
var model = function () {
var self = this;
self.isChecked = ko.observable(false);
self.doStuffWhenChecked = ko.computed(function(){
if(self.isChecked()){
$('#textinput').val("whatever");
}else{
$('#textinput').val("");
}
},this);
}
var vm = new model();
ko.applyBindings(vm);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/knockout/3.4.2/knockout-min.js"></script>
<label>Check this: </label>
<input type="checkbox" data-bind="checked: isChecked">
<span data-bind="visible: isChecked()"> Only show when checked </span>
<input type="text" id="textinput" >

Ajax form submit doesn't work on 1 page

I've a form that I submit with JQuery AJAX. But after I clicked submit, my page is redirect to my form submit.php. I've tried almost everything, but I can't find the bug...
The PHP script is working fine. I only echo once,
HTML:
<form class="offerte-form" method="post">
<div class="col-sm-6">
<input type="text" class="name" id="naamofferte" name="naam" placeholder="Naam*" required="" style="border-radius: 4px;">
<input type="text" class="name" id="naambedrijf" name="naambedrijf" placeholder="Naam bedrijf" style="border-radius: 4px;">
<input type="text" class="name" id="adresofferte" name="adres" placeholder="Adres" style="border-radius: 4px;">
<input type="text" class="name" id="vestplaats" name="vestplaats" placeholder="Vestigingsplaats" style="border-radius: 4px;">
<input type="text" class="name" id="postcode" name="postcode" placeholder="Postcode" style="border-radius: 4px;">
<input type="email" class="name" id="emailofferte" name="email" placeholder="Emailadres*" required="" style="border-radius: 4px;">
</div>
<div class="col-sm-6">
<input type="text" class="name" id="telnrofferte" name="telnr" placeholder="Telefoonnummer*" required="" style="border-radius: 4px;">
<select class="name" name="offertevoor" id="offertevoor" style="border-radius: 4px;" required>
<option value="none">
Selecteer een optie
</option>
<option value="pallets aanbieden">
Ik wil pallets aanbieden
</option>
<option value="pallets kopen">
Ik wil pallets kopen
</option>
<option value="containerservice">
Containerservice
</option>
</select>
<textarea placeholder="Uw opmerkingen" id="messageofferte" name="message" required="" style="border-radius: 4px;"></textarea>
<input type="submit" value="Verstuur">
</div>
</form>
JS:
$(function() {
// Get the form.
var form3 = $('.offerte-form');
// Get the messages div.
var formMessages3 = $('.offerte-form-message');
$(form3).submit(function(event) {
// Stop the browser from submitting the form.
event.preventDefault();
// Serialize the form data.
var formData3 = $(form3).serialize();
console.log(formData3);
$.ajax({
type: 'POST',
url: $(form3).attr('action'),
data: formData3
}).done(function(response) {
// Make sure that the formMessages div has the 'success' class.
$(formMessages3).removeClass('alert alert-danger');
$(formMessages3).addClass('alert alert-success');
// Set the message text.
$(formMessages3).text(response);
// Clear the form.
$('#naamofferte').val('');
$('#naambedrijf').val('');
$('#adresofferte').val('');
$('#vestplaats').val('');
$('#postcode').val('');
$('#emailofferte').val('');
$('#telnrofferte').val('');
$('#offertevoor').val('');
$('#messageofferte').val('');
}).fail(function(data) {
// Make sure that the formMessages div has the 'error' class.
$(formMessages3).removeClass('alert alert-success');
$(formMessages3).addClass('alert alert-danger');
// Set the message text.
if (data.responseText !== '') {
$(formMessages3).text(data.responseText);
} else {
$(formMessages3).text('Helaas, er ging iets fout, probeer het opnieuw');
}
});
});
Sorry for these lines, I needed to add more 'details' but I don't have them.
Thanks in advance!
ajax url u call to attr('action') of .offerte-form but I cant see action in your form.check it please.
<form class="offerte-form" method="post" action="submit.php">

sending multiple parameters as post request in angular js to a laravel backend

Hi I am trying to submit a form data using post request in angular js. Here are the codes :
contact.html
<form class="acodehub-form" ng-submit="submit()" method="post" novalidate>
<div class="form-group first_name">
<label for="first_name">First Name</label><br>
<input type="text" id="first_name" ng-model="fname" name="fname" class="acodehub-input form-control " required tabindex="10" maxlength="40" value="" placeholder="First Name" />
<div class="errorMessage" ng-show="errorFN">First name cannot be empty</div>
</div>
<div class="form-group last_name">
<label for="last_name">Last Name</label><br>
<input type="text" id="last_name" ng-model="lname" name="lname" class="acodehub-input form-control " required tabindex="11" maxlength="40" value="" placeholder="Last Name" />
<div class="errorMessage" ng-show="errorLN">Last name cannot be empty</div>
</div>
<div class="form-group inputEmail">
<label for="email">Email</label><br>
<input type="email" id="inputEmail" ng-pattern = "regexemail" ng-model="email" name="email" class="acodehub-input form-control" required tabindex="12" value="" maxlength="40" placeholder="Email" />
<div class="errorMessage" ng-show="errorE">Please enter a valid email address</div>
</div>
<div class="form-group reason">
<label for="reason">Subject</label>
<select name="reason" ng-model="reason" id="reason" class="typeselects acodehub-input acodehub-select form-control" placeholder="What can we help you with?" tabIndex="13" required>
<option selected value="">What can we help you with?</option>
<option value="Marketing">Marketing</option>
<option value="Advertise" >Advertise</option>
<option value="Product Review">Product Review</option>
<option value="Tutorial Request">Tutorial Request</option>
<option value="Freebie Request">Freebie Request</option>
<option value="Write for us" >Write for us</option>
<option value="Sticker Request">Ask a question?</option>
<option value="Privacy Policy" >Privacy Policy</option>
<option value="Other">Other</option>
</select>
<div class="errorMessage" ng-show="errorR">Select a valid subject</div>
</div>
<div class="form-group inputDescription">
<label for="inputDescription">Tell Us More</label><br>
<textarea name="description" ng-model="description" value="" id="inputDescription" required class="form-control acodehub-input acodehub-textarea" tabindex="14"></textarea>
<div class="errorMessage" ng-show="errorD">Please tell us something about your query. Minimum 50 letters.</div>
</div>
<div>
<button type="submit" class="acodehub-btn acodehub-btn-dark"
data-ga-track="true" data-ga-group="Contact Us"
data-ga-event="Contact Us - Click to Submit Form"
data-ga-val="Submit">
Submit
</button>
</div>
</form>
controller.js
angular.module('app.controllers',[
'app.directives',
'app.factories'
]).controller('ContactController',['$scope','$http','$httpParamSerializer',function($scope,$http,$httpParamSerializer){
$scope.submit = function() {
var text = {"first_name":$scope.fname,"last_name":$scope.lname,"email":$scope.email,"reason":$scope.reason,"description":$scope.description};
$http.defaults.headers.post["Content-Type"] = "application/x-www-form-urlencoded";
$http.post('/api/contact',$httpParamSerializer(text)).then(function (data, status, headers, config) {
alert("success");
console.log(data);
console.log(status);
console.log(headers);
console.log(config);
},function (data, status, headers, config) {
alert("error");
console.log(data);
console.log(status);
console.log(headers);
console.log(config);
});
}
}]);
web.php(in laravel)
Route::post('/api/contact','ContactController#submit');
contactcontroller
public function submit(Request $request) {
$this->validate($request,array(
'first_name'=>'required',
'last_name'=>'required',
'email'=>'required|email',
'reason'=>'required',
'description'=>'required|min:20'
));
$data = array(
'first_name'=>$request->first_name,
'last_name'=>$request->last_name,
'email'=>$request->email,
'reason'=>$request->reason,
'description'=>$request->description
);
Mail::queue('emails.contact',$data,function($message) use($data) {
$message->from($data['email']);
$message->to('gaurav.roy142#gmail.com');
$message->subject($data['reason']);
});
//dd($request);
//echo 'hello '.$submit;
if(count(Mail::failures())>0) {
return $request;
}else {
return $request;
}
//return $data;
}
I am getting the output in the console as:
Object {data: "<!DOCTYPE html>
↵<html ng-app="app">
↵<head>
↵ <b…rc="/app/services.js"></script>
↵</body>
↵</html>", status: 200, config: Object, statusText: "OK", headers: function}
undefined
undefined
undefined
I tried every solution provided on stackoverflow or any other website but I am not able to set it up correctly, everytime I am getting the same output as above. I know I am missing something somewhere and now I am out of any ideas how to set it up correctly. Please help me fix it up.
$http returns a promise. In case of success or error, an object containing data, status, config, statusText and headers properties (as you can see in your console log) is resolved or rejected.
So, change your code to :
$http.post('/api/contact',$httpParamSerializer(text)).then(function (response) {
alert("success");
console.log(response.data);
console.log(response.status);
console.log(response.headers);
console.log(response.config);
},function (error) {
alert("error");
console.log(error.data);
console.log(error.status);
console.log(error.headers);
console.log(config);
});

Jquery Validation plug-in dependency from Radio buttons not working

I need some inputs to be required only if certain options are checked in another input (radio). In short, if Type 1 documents is chosen, I need type 1 field number to be obligatory. It's easier to visualize through this jsfiddle below:
https://jsfiddle.net/kbhatd51/2/
Could you please help me? Thanks in advance
<form id="registerform" method="post">
<div class="form-group">
<label >Type of Document</label><br>
<input type="radio" class="radioForm" id="fis" name="tipop" value="0" > <label for="fis"> Type 1</label><br>
<input type="radio" class="radioForm" id="jur" name="tipop" value="1" > <label for="jur"> Type 2</label><br>
</div>
<label for="tipop"> Number</label>
<div class="form-group">
<fieldset id="cpf1">
<label for=cpf1>Type 1 No.:</label>
<input type="number" class="form-control" placeholder="000.000.000-00" name="cpf" id="cpf" >
</fieldset>
<fieldset id="cnpj1">
<label for=cnpj1> Type 2 No.:
<input type="number" class="form-control" placeholder=" 00.000.000/0001-00" name="cnpj" id="cnpj"></label>
</fieldset>
</div>
<input name="submit" type="submit" value="Submit!">
</form>
JS validate:
$("#registerform").validate({
rules: {
cpf: {
required: "#fis:checked"
},
cnpj: {
required: "#jur:checked"
}
}
});
The required method needs to return true for the field to be required.
So you can simply pass a function to required which will check if the radio element is checked
required method
required( dependency-callback )
Type: Function()
The function is executed with the element as it's only argument: If it returns true, the element is required.
$("#registerform").validate({
debug: true,
rules: {
cpf: {
required: function(elem) {
return $('#fis').is(":checked")
}
},
cnpj: {
required: function(elem) {
return $('#jur').is(":checked")
}
}
}
});
Check out the -- JSFiddle Example -- here.

Autocomplete multiple fields based on one field (jQuery Autocomplete)

My JSON information:
{
"RES_ID":"2622959",
"PROP_ID":"76055",
"RES_CHECK_IN":"2015-04-21",
"RES_CHECK_OUT":"2015-04-25",
"RES_N_ADULTS":"6",
"RES_GUEST_FIRSTNAME":"Nicolas",
"RES_GUEST_LASTNAME":"Prantzos"
}
I want the RES_ID as autocomplete for the following input:
<input id="reservation_id" class="ui-autocomplete-input form-control" />
And when the input reservation_id will be filled take the rest RES_CHECK_IN and RES_CHECK_OUT and autofill them in
<input type="text" class="form-control" name="start">
<span class="input-group-addon">to</span>
<input type="text" class="form-control" name="end">
I tried to mix ajax + autocomplete do achieve that without any luck.
(function autocomplete_search() {
//this function take the #res_id input
$("#reservation_id").autocomplete({
source: "/police/get_res"
});
})();
How I show RES_ID as autocomplete and how i fill the rest of the inputs based on the RES_ID?
$("#reservation_id").kendoAutoComplete( {
dataTextField: "name",
dataSource: {
transport: {
read: {
url: "JSON File name",
serverPaging:true,
type: "POST",
data: {
json: JSON.stringify([{"name": "Karan"}, {"name": "Singh"}] )
}
}
}
}
} );
and in HTMl Side
<input id="reservation_id" />
Go : Link
or :
var data = [{
"RES_ID":"2622959",
"PROP_ID":"76055",
"RES_CHECK_IN":"2015-04-21",
"RES_CHECK_OUT":"2015-04-25",
"RES_N_ADULTS":"6",
"RES_GUEST_FIRSTNAME":"Nicolas",
"RES_GUEST_LASTNAME":"Prantzos"
}];
$("#reservation_id").autocomplete({
source: function (request, response) {
response($.map(data, function(v,i){
return {
label: v.RES_ID,
value: v.RES_GUEST_LASTNAME
};
}));
}
});
Final Fiddle :-Final
So I haven't found an easy solution for this. had to code myself.
jQuery:
(function autocomplete_search() {
//this function take the #res_id input
var ac_config = {
source: "/police/get_res",
select: function(event, ui) {
$("#reservation_id").val(ui.item.RES_ID);
$("#checkin").val(ui.item.RES_CHECK_IN);
$("#checkout").val(ui.item.RES_CHECK_OUT);
$("#firstname").val(ui.item.RES_GUEST_FIRSTNAME);
$("#lastname").val(ui.item.RES_GUEST_LASTNAME);
},
minLength: 1
};
$("#reservation_id").autocomplete(ac_config);
})();
HTML:
<div class="form-group">
<label class="col-md-3 control-label" for="inputTooltip">Firstname <span class="required">*</span>
</label>
<div class="col-md-6">
<input type="text" title="" data-toggle="tooltip" data-trigger="hover" class="form-control" data-original-title="What is your name?" id="firstname" aria-describedby="tooltip332323">
</div>
</div>
<div class="form-group">
<label class="col-md-3 control-label" for="inputTooltip">Lastname <span class="required">*</span>
</label>
<div class="col-md-6">
<input type="text" title="" data-toggle="tooltip" data-trigger="hover" class="form-control" data-original-title="What is your Last name?" id="lastname" aria-describedby="tooltip332323">
</div>
</div>
<div class="form-group">
<label class="col-md-3 control-label">Checkin / Checkout:</label>
<div class="col-md-6">
<div class="input-daterange input-group" data-plugin-datepicker="">
<span class="input-group-addon"><i class="fa fa-calendar"></i></span>
<input type="text" class="form-control" id="checkin" name="checkin" value="">
<span class="input-group-addon">to</span>
<input type="text" class="form-control" id="checkout" name="checkout" value="">
</div>
</div>
</div>
Codeigniter model which generates the JSON:
function get_res($q) {
$this->db->select('RES_ID, PROP_ID, RES_CHECK_IN, RES_CHECK_OUT, RES_N_ADULTS, RES_GUEST_FIRSTNAME, RES_GUEST_LASTNAME');
$this->db->like('RES_ID', $q);
$query = $this->db->get('reservations');
if($query->num_rows() > 0){
foreach ($query->result_array() as $row){
//build an array
$row['value'] = $row['RES_ID'];
$row['label'] = "{$row['RES_ID']}";
$matches[] = $row;
}
echo json_encode($matches); //format the array into json data
exit;
}
}
Controller:
function get_res(){
if (isset($_GET['term'])){
$q = strtolower($_GET['term']);
$this->Police_model->get_res($q);
}
}
Hope It will help someone!

Categories

Resources