Multiple selection doesnt post selected id - javascript

I have an option panel in which you can select multiple variables. but when i select an variable it wont post the id in the database.
html form:
<form class="form-inline">
<div id="d1" title="Nieuwe afspraak" style="display: none">
<label class="control-label">Werknemer(s):</label>
<select name="werknemer[]" data-placeholder="werknemer..." id="werknemer" multiple="multiple" class="chzn-select" style="width:300px;" tabindex="4">
<option value=""></option>
<?if($werknemers !=null):foreach($werknemers as $row):?>
<option value='<?=$row->idWerknemer;?>'><?=$row->Voornaam;?> (<?=$row->Achternaam;?>)</option>
<?endforeach;endif;?>
</select><br />
<div class="control-group">
<label class="control-label">Titel:</label>
<div class="controls">
<input type="text" name="username" placeholder="Titel" id="name"/>*
</div>
</div>
<div class="control-group">
<label class="control-label">Omschrijving:</label>
<div class="controls">
<input type="text" name="userdesc" placeholder="Beschrijving" id="desc"/>*
</div>
</div>
<button style="float:right; margin-right:34px;" onclick="toggle_div_fun('sectiontohide');">Geavanceerd</button>
<div id="sectiontohide" style="display:none;">
<div class="control-group" >
<label class="control-label">Project:</label>
<div class="controls">
<select onChange='$("#klant").val("NULL");$("#klant").trigger("liszt:updated");' name="project" data-placeholder="Project..." class="chzn-select" id="project" style="width:160px;" tabindex="4">
<option value="NULL"></option>
<?if($projecten_titel !=null):foreach($projecten_titel as $row):?>
<option value='<?=$row->idProject;?>'><?=$row->Titel;?> (<?=$row->Naam;?>)</option>
<?endforeach;endif;?>
</select><br /><br /></div>
</div><div class="control-group" >
<label class="control-label">Klant:</label>
<div class="controls">
<select onChange='$("#project").val("NULL");$("#taak").val("NULL");$("#project").trigger("liszt:updated");$("#taak").trigger("liszt:updated");' name="klant" data-placeholder="Klant..." class="chzn-select" id="klant" style="width:160px;" tabindex="4">
<option value="NULL"></option>
<?if($klanten !=null):foreach($klanten as $row):?>
<option value='<?=$row->idKlant;?>'><?=$row->Naam;?></option>
<?endforeach;endif;?>
</select><br /><br /></div>
</div><div class="control-group" >
<label class="control-label">Taak:</label>
<div class="controls">
<select onChange='$("#klant").val("NULL");$("#klant").trigger("liszt:updated");' name="taak" data-placeholder="Klant..." class="chzn-select" id="taak" style="width:160px;" tabindex="4">
<option value="NULL"></option>
<?if($taken !=null):foreach($taken as $row):?>
<option value='<?=$row->idTaak;?>'><?=$row->Titel1;?></option>
<?endforeach;endif;?>
</select><br /><br /></div>
</div>
</div>
<div class="control-group">
<label class="control-label">Van:</label>
<div class="controls">
<input type="startdate" name="userstart" placeholder="Starttijd" id="start"/>*
<input type="time" name="mytime" value="00:00:00" placeholder="starttime" id="starttime"/>
</div>
</div>
<div class="control-group">
<label class="control-label">Tot:</label>
<div class="controls">
<input type="einddate" name="userend" placeholder="Eindtijd" id="end"/>*
<input type="time" name="mytime" value="00:00:00" placeholder="endtime" id="endtime"/>
</div>
</div>
<div class="control-group">
<label class="control-label">Color:</label>
<div class="controls">
<select name="color[]" id="colorstatus" data-placeholder="colors..." class="chzn-select" tabindex="4">
<?if($colors !=null):foreach($colors as $row):?>
<option value='<?=$row->colortag;?>'><?=$row->soort;?></option>
<?endforeach;endif;?>
</select><br />
</div>
</div></div>
<div id="d2" title="Checking Empty..." style="display:none;">
<p>Vul alstublieft wat in....!</p>
</div>
</div>
nieuwe afspraak.js:
$(function () {
// Dialog Open
$("#d1").dialog({
autoOpen: false,
height: 'auto',
width: 'auto',
modal: true,
closeOnEscape:true,
resizable:false,
show:'fade',
buttons: {
"Add": function() {
var id = $("#id").val(),
werknemer = $('#werknemer').val(),
project = $('#project').val(),
klant = $('#klant').val(),
taak = $('#taak').val(),
name = $('#name').val(),
desc = $('#desc').val(),
start = $('#start').val(),
starttime = $('#starttime').val(),
end = $('#end').val(),
endtime = $('#endtime').val();
colorstatus = $('#colorstatus').val();
if(id=='' || werknemer=='' || name=='' || desc=='' || start=='' || end=='')
{
//alert("Please do not empty....!",title="Hello");
$("#d2").dialog("open");
$("#d2").dialog({
buttons:{
"OK":function(){
$(this).dialog("close");
$("#id:first").focus();
}
}
});
exit;
}//End if statement
$.post('../testcalendar/db/process.php',{
user_id: id, user_werknemer: werknemer, user_project: project, user_klant: klant,user_taak: taak, user_name: name, user_desc: desc, user_start: start, user_starttime: starttime, user_end: end, user_endtime: endtime, user_color: colorstatus, action:'joined'
}); var nTime = 1 * 50;
window.setTimeout("location.reload()", nTime);//End Post
$("#id").val('');
$("#werknemer").val('');
$("#project").val('');
$("#klant").val('');
$("#taak").val('');
$("#name").val('');
$("#desc").val('');
$("#start").val('');
$("#starttime").val('');
$("#end").val('');
$("#endtime").val('');
$("#colorstatus").val('');
$(this).dialog("close");
},
"Cancel": function() {
$("#id").val('');
$("#werknemer").val('');
$("#project").val('');
$("#klant").val('');
$("#taak").val('');
$("#name").val('');
$("#desc").val('');
$("#start").val('');
$("#starttime").val('');
$("#end").val('');
$("#endtime").val('');
$("#colorstatus").val('');
$(this).dialog("close");
}
}
});
$("#d2").dialog({
autoOpen: false,
height: 'auto',
width: 'auto',
modal: true,
closeOnEscape:true,
resizable:false,
show:'fade',
buttons: {
"Ok": function() { $(this).dialog("close"); }
}
});
$("#b1").click(function(){
$("#d1").dialog("open");
});
$("#start").datepicker({ dateFormat: 'yy-mm-dd' });
$("#end").datepicker({ dateFormat: 'yy-mm-dd' });
$('input[type="time"] ').timepicker();
});
function showDiv() {
document.getElementById('welcomeDiv').style.display = "block";
}
process.php:
$q = "INSERT INTO evenement (id,idWerknemer,idProject,idKlant,idTaak,title,description,start,end,color) VALUES
('','".$user_werknemer."','".$user_project."','".$user_klant."','".$user_taak."','".$user_name."','".$user_desc."','".$user_start."','".$user_end."','".$user_color."')";
$qo = "INSERT INTO evenementontvanger (idWerknemer,idProject,idEvent,idKlant,idTaak) VALUES ('".$user_werknemer."','".$user_project."','','".$user_klant."','".$user_taak."')";
foreach ($user_werknemer as $werknemer){
mysql_query($q);
mysql_query($qo);
}}
if(isset($_POST['user_werknemer'],$_POST['user_project'],$_POST['user_klant'],$_POST['user_taak'],$_POST['user_name'],$_POST['user_desc'],$_POST['user_start'],$_POST['user_starttime'],$_POST['user_endtime'],$_POST['user_end'],$_POST['user_color'],$_POST['action'])){
$user_werknemer=$_POST['user_werknemer'];
$user_color=$_POST['user_color'];
$user_name=$_POST['user_name'];
$user_desc=$_POST['user_desc'];
$user_project=$_POST['user_project'];
$user_klant=$_POST['user_klant'];
$user_taak=$_POST['user_taak'];
$user_start=$_POST['user_start']." ".$_POST['user_starttime'];
$user_end=$_POST['user_end']." ".$_POST['user_endtime'];
$action=$_POST['action'];
if ($action=='joined'){
user_joined( $user_werknemer, $user_project, $user_klant, $user_taak, $user_name, $user_desc, $user_start, $user_end, $user_color);
}
} ?>
i think the foreach loop doesnt get the id for each "user_werknemer" somehow.

Looks like your query variables are in the wrong place. Also, you had an extra } after the loop.
foreach ($user_werknemer as $werknemer){
$q = "INSERT INTO evenement (id,idWerknemer,idProject,idKlant,idTaak,title,description,start,end,color) VALUES
('','".$user_werknemer."','".$user_project."','".$user_klant."','".$user_taak."','".$user_name."','".$user_desc."','".$user_start."','".$user_end."','".$user_color."')";
$qo = "INSERT INTO evenementontvanger (idWerknemer,idProject,idEvent,idKlant,idTaak) VALUES ('".$user_werknemer."','".$user_project."','','".$user_klant."','".$user_taak."')";
// for debugging only
print ("q = $q <br /> qo = $qo <br /><br />");
///////////////
mysql_query($q);
mysql_query($qo);
}

Related

Delayed execution of Javascript

In my project I have a modal window where a cascading dropdownlist is shown for two properties (Family, TypeID) of a class (Machine).
The issue:
The dependant dropdownlist populates only when the modal window has been open for the second time. On the first time, nothing happens:
Here is a picture of how it works for a better understanding:
Notice that the row that says Modelo (Modelo is the name for TypeID) is empty in the first moment, but once re-opened, it populates with the expected information.
The code:
Note The Javascript is located in the Index page that contains the link to the modal window
This modal window is used when a New Machine is Created, or Edited.
For that reason, in the first section of the Javascript, I check in which situation I am and check if the Machine property: MchName, has a value.
In case it doesn't have a value, I assign the value of the variable items to the property TypeID that should be shown when the Modal opens.
#section scripts{
<script src="~/js/machine-index.js" asp-append-version="true"></script>
<script type="text/javascript">
$(document).ready(function () {
$('#FamilyID').change(function () {
var url = '#Url.Content("~/")' + "Machines/GetModel";
var ddlsource = "#FamilyID";
$.getJSON(url, { FamilyID: $(ddlsource).val() }, function (data) {
var items = '';
$("#TypeID").empty();
$.each(data, function (i, model) {
items += "<option value='" + model.value + "'>" + model.text + "</option>";
});
$('#TypeID').html(items);
});
});
$('#modal-action-machine').on('shown.bs.modal', function () {
var test = "#MchName";
if ($(test).val()) {
} else {
var items = "<option value='0'>-- Seleccione Modelo --</option>";
$('#TypeID').html(items);
}
});
});
</script>
<script type="text/javascript">
$(function () {
$('.datepicker').datepicker({
"autoclose": true,
format: 'dd/mm/yyyy'
}).datepicker("setDate", new Date());
});
</script>
<script src="~/lib/bootstrap-datepicker/js/bootstrap-datepicker.js"></script>
}
Get Method:
[HttpGet]
public IActionResult CreateEdit(int? id)
{
//Lista de Familias
List<MachineFamily> FamilyList = new List<MachineFamily>();
FamilyList = (from family in _context.MachineFamilies
select family).ToList();
FamilyList.Insert(0, new MachineFamily { FamilyID = 0, FamilyDescription = "-- Seleccione Familia --" });
ViewBag.ListofFamily = FamilyList;
ViewBag.TypeID = string.Empty;
return PartialView("~/Views/Shared/Machines/_Create.cshtml");
}
JsonResult:
public JsonResult GetModel(int FamilyID)
{
List<MachineType> ListaModelos = new List<MachineType>();
ListaModelos = (from model in _context.MachineTypes
where model.FamilyID == FamilyID
select model).ToList();
ListaModelos.Insert(0, new MachineType { TypeID = 0, TypeDescription = "-- Seleccione Modelo --" });
return Json(new SelectList(ListaModelos, "TypeID", "TypeDescription"));
}
View: Modal
#model Application.Models.ApplicationviewModels.MachineIndexData
#using Application.Models
<form asp-action="CreateEdit" role="form">
#await Html.PartialAsync("_ModalHeader", new ModalHeader
{ Heading = String.Format("Actualización de Modelo") })
<div asp-validation-summary="ModelOnly" class="text-danger"></div>
<div class="modal-body form-horizontal">
<input type="hidden" asp-for="Id" />
<div class="form-group">
<label asp-for="FamilyID" class="col-md-2 control-label"></label>
<div class="col-md-10">
<select asp-for="FamilyID" class="form-control"
asp-items="#(new SelectList(ViewBag.ListofFamily,"FamilyID","FamilyDescription"))"></select>
</div>
</div>
<div class="form-group">
<label asp-for="TypeID" class="col-md-2 control-label"></label>
<div class="col-md-10">
<select asp-for="TypeID" class="form-control"
asp-items="#(new SelectList(ViewBag.TypeID,"TypeID","TypeDescription"))"></select>
</div>
</div>
<div class="form-group">
<label asp-for="BrandID" class="col-md-2 control-label"></label>
<div class="col-md-10">
<select asp-for="BrandID" class="form-control" asp-items="ViewBag.BrandID">
<option value="">-- Seleccione Marca --</option>
</select>
<span asp-validation-for="BrandID" class="text-danger"></span>
</div>
</div>
<div class="form-group">
<label asp-for="SupplierID" class="col-md-2 control-label"></label>
<div class="col-md-10">
<select asp-for="SupplierID" class="form-control" asp-items="ViewBag.SupplierID">
<option value="">-- Seleccione Proveedor --</option>
</select>
<span asp-validation-for="SupplierID" class="text-danger"></span>
</div>
</div>
<div class="form-group">
<label asp-for="StoreID" class="col-md-2 control-label"></label>
<div class="col-md-10">
<select asp-for="StoreID" class="form-control" asp-items="ViewBag.StoreID">
<option value="">-- Seleccione Tienda --</option>
</select>
<span asp-validation-for="StoreID" class="text-danger"></span>
</div>
</div>
<div class="form-group">
<label asp-for="MchName" class="col-md-2 control-label"></label>
<div class="col-md-10">
<input asp-for="MchName" class="form-control" />
<span asp-validation-for="MchName" class="text-danger"></span>
</div>
</div>
<div class="form-group">
<label asp-for="NumDevices" class="col-md-2 control-label"></label>
<div class="col-md-10">
<input id="NumDevices" asp-for="NumDevices" class="form-control" readonly />
<span asp-validation-for="NumDevices" class="text-danger"></span>
<input id="getNum" type="range" min="" max="10" step="1" onchange="fetch()" class="form-control" />
</div>
</div>
<div class="form-group">
<label asp-for="FechaCompra" class="col-md-2 control-label"></label>
<div class="col-md-10">
<input data-format="0:dd/MM/yyyy" type="datetime" asp-for="FechaCompra" class="form-control datepicker" />
<span asp-validation-for="FechaCompra" class="text-danger"></span>
</div>
</div>
<div class="form-group">
<label asp-for="CostoMaq" class="col-md-2 control-label"></label>
<div class="col-md-10">
<input asp-for="CostoMaq" class="form-control" />
<span asp-validation-for="CostoMaq" class="text-danger"></span>
</div>
</div>
<div class="form-group">
<label asp-for="MachineStatus" class="col-md-2 control-label"></label>
<div class="col-md-10">
<select name="MachineStatus" asp-for="MachineStatus" class="form-control" disabled>
<option value="0">Operativo</option>
<option value="1" selected="selected">Nuevo Item</option>
<option value="2">Reparación</option>
</select>
<input type="hidden" name="MachineStatus" value="1" />
<span asp-validation-for="MachineStatus" class="text-danger"></span>
</div>
</div>
#await Html.PartialAsync("_ModalFooter", new ModalFooter { })
</div>
</form>
Final notes: I believe that to fix this I should change the Javascript. Can someone please explain to me why this happens and how to fix it?
Update: Attempting to assign a new id to the ´MchName´ field and send it to the Script
View:
<div class="form-group">
<label asp-for="MchName" class="col-md-2 control-label"></label>
<div class="col-md-10">
<input id="MchName2" asp-for="MchName" class="form-control" />
<span asp-validation-for="MchName" class="text-danger"></span>
</div>
</div>
Script:
$('#modal-action-machine').on('shown.bs.modal', function () {
var test = document.getElementById("MchName2").value;
if (test) {
} else {
var items = "<option value='0'>-- Seleccione Modelo --</option>";
$('#TypeID').html(items);
}
});
No luck tho.
Update: Second attempt
View:
<div class="form-group">
<label asp-for="MchName" class="col-md-2 control-label"></label>
<div class="col-md-10" id="MchName2">
<input asp-for="MchName" class="form-control" />
<span asp-validation-for="MchName" class="text-danger"></span>
</div>
</div>
Script:
$('#modal-action-machine').on('shown.bs.modal', function () {
var test = "#MchName2 #MchName";
if ($(test).val()) {
} else {
var items = "<option value='0'>-- Seleccione Modelo --</option>";
$('#TypeID').html(items);
}
});
You should wrap both shown.bs.modal event handlers in one single document.ready function.
Every time when shown.bs.modal event is fired, it will bind a change event handler to your select element. You should bind it only once.
script type="text/javascript">
$(document).ready(function () {
$('#FamilyID').change(function () {
var url = '#Url.Content("~/")' + "Machines/GetModel";
var ddlsource = "#FamilyID";
$.getJSON(url, { FamilyID: $(ddlsource).val() }, function (data) {
var items = '';
$("#TypeID").empty();
$.each(data, function (i, model) {
items += "<option value='" + model.value + "'>" + model.text + "</option>";
});
$('#TypeID').html(items);
});
});
$('#modal-action-machine').on('shown.bs.modal', function () {
var test = "#MchName";
if ($(test).val()) {
} else {
var items = "<option value='0'>Select</option>";
$('#TypeID').html(items);
}
});
});
I have found an answer that works for this specific case.
The first thing that was wrong was evaluate a variable that is not defined inside an ifstatement.
$('#modal-action-machine').on('shown.bs.modal', function () {
var test = "#MchName";
if ($(test).val()) {
In this code I was assigning the value of #MchName to testbut in a first moment, #MchName does not get defined until the modal opens for a first time, and for that, not executing the rest of the code.
Second: A turn around was to use click event of the Create button to identify if I'm in a case of a New Machine or just an update.
For this I will declare a global variable and assign it the value of zero.
If the Create button is clicked, assign this variable the value of 1, and if this is true, assign the default value that was intended to the #TypeID variable.
After the modal closes, re-asign the global variable to zero. This, for the case that another button (Update) is hitted to call the modal.
This is the code:
var global = this;
var wasclicked = 0;
$(document).ready(function () {
document.getElementById("modalbutton").onclick = function () {
global.wasclicked = 1;
};
$('#modal-action-machine').on('hidden.bs.modal', function () {
global.wasclicked = 0;
});
$('#modal-action-machine').on('shown.bs.modal', function () {
if (global.wasclicked == 1) {
var items = "<option value='0'>-- Seleccione Modelo --</option>";
$('#TypeID').html(items);
}
});
With this, the project works as intended.
Thanks for the help!

Auto populate dropdown fields doesn't work

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>

how to call multiple function on each value of select box

here is my code. I want to call showdefault() function on every option value of select box and MaxSize() when value == "Address" and
EnableRangeSearch() when value == "Checkbox". I am enable to perform this. Can any one suggest where i am wrong
$(document).ready(function(){
$("select").change(function(){
if(document.getElementById("data_type").value=="Address"){
//MaxSize() is function defined in function.php page
MaxSize();
}
if(document.getElementById("data_type").value=="Checkbox"){
//EnableRangeSearch() is function defined in function.php page
EnableRangeSearch();
}
});
});
<select class="form-control" name="data_type" id="data_type">
<option value="Text Fields" id="TextFields">Text Fields</option>
<option value="Address" id="Address">Address</option>
<option value="Checkbox">Checkbox</option>
<option value="Currency">Currency</option>
</select>
<?php include 'function.php';
//fields is a class name
$qwerty=new fields;
$qwerty->showdefault();
?>
Try this
$("#data_type").change(function () {
showdefault();
if ($(this).val() == "Address") {
MaxSize();
} else if ($(this).val() == "Checkbox") {
EnableRangeSearch();
}
});
you need define javascript function for showdefault(), MaxSize() and EnableRangeSearch().
First create function for all select options then call showdefault() function in which you call selected option's functions. For example: see below
//this script for sending `id` of dropdown option to results.php page
$('#data_type option').on('click', function(){
$.get('miniresults.php',
{
option: this.id
},
function(data){
$('.show_contain').html(data); //do something with whatever data is returned
});
});
IN home.php
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<link rel="stylesheet" href="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css">
<script src="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"></script>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<form class="form-horizontal" name="apply" id="apply" method="post">
<div class="form-group">
<label class="col-xs-3 control-label">Data type</label>
<div class="col-xs-6">
<select class="form-control" name="data_type" id="data_type">
<option value="Text_Fields" id="TextFields">Text Fields</option>
<option value="Address" id="Address">Address</option>
<option value="Checkbox" id="Checkbox">Checkbox</option>
<option value="Currency" id="Currency">Currency</option>
</select>
</div>
</div>
<div class="form-group">
<label class="col-xs-3 control-label">Field Name</label>
<div class="col-xs-6">
<input type="text" class="form-control" name="FieldName" placeholder="Field Name">
</div>
</div>
<div class="show_contain" id="show_contain">
<div class="form-group">
<label class="col-xs-3 control-label">Display Label</label>
<div class="col-xs-6">
<input type="text" class="form-control" name="DisplayLabel" placeholder="Display Label">
</div>
</div>
</div>
</form>
IN miniresults.php
<?php
class fields
{
public function showdefault()
{
$viewdefault='<div class="form-group"><label class="col-xs-3 control-label">Display Label</label><div class="col-xs-6"><input type="text" class="form-control" name="DisplayLabel" placeholder="Display Label"></div></div><div class="form-group"><label class="col-xs-3 control-label">System Label</label><div class="col-xs-6"><input type="text" class="form-control" name="SystemLabel" placeholder="System Label"></div></div><div class="form-group"><label class="col-xs-3 control-label">Help Text</label><div class="col-xs-6"><input type="text" class="form-control" name="HelpText" placeholder="Help Text"></div></div>';
return $viewdefault;
}
public function get_default_value()
{
$set_default_vals='<div class="form-group"><label class="col-xs-3 control-label">Default Value</label><div class="col-xs-6"><input type="text" class="form-control" name="DefaultValue" placeholder="Default Value"></div></div>';
return $set_default_vals;
}
public function get_msize()
{
$addr="<div class='form-group'><label class='col-xs-3 control-label'>Max Size</label><div class='col-xs-6'><input type='text' class='form-control' name='MaxSize' placeholder='Max Size' value='255'></div></div>";
return $addr;
}
public function get_range()
{
$range="<div class='form-group'><label class='col-xs-3 control-label'>Enable Range Search</label><div class='checkbox col-xs-6'><label><input type='checkbox' class='checkbox' name='EnableRangeSearch' value='Yes' /></label></div></div>";
return $range;
}
}
//this class for different datatypes
class drop_type extends fields
{
function show_Text_Fields()
{
echo $this->showdefault();
echo $this->get_default_value();
echo $this->get_msize();
}
function show_Address()
{
echo $this->showdefault();
echo $this->get_default_value();
echo $this->get_msize();
}
function show_Checkbox()
{
echo $this->showdefault();
echo $this->get_default_value();
}
function show_Currency()
{
echo $this->showdefault();
echo $this->get_default_value();
echo $this->get_range();
}
}
//Object declaration of class drop_type()
$show_drop = new drop_type();
//$_GET['option'] contain `id` of dropdown option
switch($_GET['option']){
//case include name of options in dropdown
case 'TextFields':
echo $show_drop->show_text_fields();
break;
case 'Address':
echo $show_drop->show_Address();
break;
case 'Checkbox':
echo $show_drop->show_Checkbox();
break;
case 'Currency':
echo $show_drop->show_Currency();
break;
default:
//default contain textfields contain
echo $show_drop->show_text_fields();
break;
}
?>

ajax form is not working how it should

hello i been working on a form using ajax but when it comes down to validating a select box
problem 1) every time i leave the job_est value empty the form is still submitted as if it was validated
problem 2) can i use async in ajax
sorry for my writing skills
<script type="text/javascript" src="http://code.jquery.com/jquery-latest.js"></script>
<script type="text/javascript">
$(document).ready(function() {
//if submit button is clicked
$('#submit').click(function () {
//Get the data from all the fields
var name = $('input[name=name]');
var l_name = $('input[name=l_name]');
var phone = $('input[name=phone]');
var email = $('input[name=email]');
var postcode = $('input[name=postcode]');
var house_number = $('input[name=house_number]');
var street = $('input[name=street]');
var job_est = $('select[name=job_est]');
var comment = $('textarea[name=comment]');
//Simple validation to make sure user entered something
//If error found, add hightlight class to the text field
if (name.val()=='') {
name.addClass('hightlight');
return false;
} else name.removeClass('hightlight');
if (l_name.val()=='') {
l_name.addClass('hightlight');
return false;
} else l_name.removeClass('hightlight');
if (phone.val()=='') {
phone.addClass('hightlight');
return false;
} else phone.removeClass('hightlight');
if (email.val()=='') {
email.addClass('hightlight');
return false;
} else email.removeClass('hightlight');
if (postcode.val()=='') {
postcode.addClass('hightlight');
return false;
} else postcode.removeClass('hightlight');
if (house_number.val()=='') {
house_number.addClass('hightlight');
return false;
} else house_number.removeClass('hightlight');
if (street.val()=='') {
street.addClass('hightlight');
return false;
} else street.removeClass('hightlight');
if (job_est.val()=='') {
job_est.addClass('hightlight');
return false;
} else job_est.removeClass('hightlight');
if (comment.val()=='') {
comment.addClass('hightlight');
return false;
} else comment.removeClass('hightlight');
//organize the data properly
var data = 'name=' + name.val() + '&email=' + email.val() + '&phone=' +
phone.val() + '&comment=' + encodeURIComponent(comment.val());
//disabled all the text fields
$('.text').attr('disabled','true');
//show the loading sign
$('.loading').show();
//start the ajax
$.ajax({
//this is the php file that processes the data and send mail
url: "process.php",
//GET method is used
type: "GET",
//pass the data
data: data,
//Do not cache the page
cache: false,
//success
success: function (html) {
//if process.php returned 1/true (send mail success)
if (html==1) {
//hide the form
$('.form').fadeOut('slow');
//show the success message
$('.done').fadeIn('slow');
//if process.php returned 0/false (send mail failed)
} else alert('Sorry, unexpected error. Please try again later.');
}
});
//cancel the submit button default behaviours
return false;
});
});
</script>
<body>
<div class="block">
<div class="done">
<b>Thank you !</b> We have received your message.
</div>
<div class="form">
<form method="post" action="process.php">
<h4><u>Basic Contact Details</u></h4>
<div style="display: inline-block;" class="element">
<label>Name</label><input type="text" name="name"/>
</div>
<div style="display: inline-block;" class="element">
<label>Last Name: </label><input type="text" name="l_name"/>
</div>
<div class="element">
<label>Phone Number</label>
<input type="text" name="phone"/>
</div>
<div class="element">
<label>Email</label>
<input type="text" name="email"/>
</div>
<div style="display: inline-block;" class="element">
<label>Postcode: </label><input type="text" name="postcode" size="10" maxlength="10">
</div>
<div style="display: inline-block;" class="element">
<label>House Number: </label><input type="text" name="house_number" size="3">
</div>
<div style="display: inline-block;" class="element">
<label>Street Name: </label><input type="text" name="street">
</div>
<div style="display: inline-block;" class="element">
<label>County:</label>
<select>
<option name="select">--SELECT--</option>
<option name="bedford">Bedford</option>
<option name="dunstable">Dunstable</option>
<option name="luton">Luton</option>
</select>
</div>
<h4><u>Job Details</u></h4>
<div class="element">
<label>You Would Like To Book A:</label>
<select name="job_est">
<option name="select">--SELECT--</options>
<option name="job">Job</option>
<option name="est">Estimation</option>
</select>
</div>
<br/>
<div class="element">
<label>Service Your Booking:</label>
<select>
<option name="select">--SELECT--</option>
<option name="gardening">Gardening</option>
<option name="landscaping">Landscaping</option>
<option name="painting">Painting & Decorating</option>
<option name="decking">Decking & Fencing</option>
</select>
</div>
<br/>
<div class="element">
<label>Any Additional Information </label>
<textarea name="comment" class="text textarea" /></textarea>
</div>
<div class="element">
<input type="submit" id="submit"/>
<div class="loading"></div>
</div>
</form>
</div>
</div>
<div class="clear"></div>
You should change selectbox's name attribute with value
<select name="job_est">
<option value="select">--SELECT--</options>
<option value="job">Job</option>
<option value="est">Estimation</option>
</select>
and in your javascript, it should be
if (job_est.val() == 'select') {
job_est.addClass('hightlight');
return false;
}

Validate form using jqueryvalidate.js and ckeditor Codeigniter

Hello. I have a form that gets validated by jqueryvalidate.js. I have a drop down menu and the menu will be different when I choose "Library Asset" because I need to choose another drop down menu that is hidden.
The problem is, when I am not choose other menu that is not showing another drop down menu..
the required rules still implemented.. so the form can't be submitted except the one that is showing another drop down menu..
Can someone help me here?
This is my code:
View(Js):
<script type="text/javascript">
function showbook()
{
var domObj1 = document.getElementById('emptybox');
var domObj2 = document.getElementById('showupbox');
if(domObj1.style.display =='none')
{
domObj1.style.display = 'block';
domObj2.style.display = 'none';
}
else
{
domObj1.style.display = 'none';
domObj2.style.display = 'block';
}
}
function closebook()
{
var domObj1 = document.getElementById('emptybox');
var domObj2 = document.getElementById('showupbox');
if(domObj1.style.display =='none')
{
domObj1.style.display = 'block';
domObj2.style.display = 'none';
}
}
function showhidebook()
{
console.log($('#CategoryAdviceSelect').val());
if($('#CategoryAdviceSelect').val() == 1)
{
showbook();
}
else{
closebook();
}
}
My validation rules:
<script>
$().ready(function() {
$("#feedback_form").validate({
ignore: "input:hidden:not(input:hidden.required)",
rules: {
CategoryAdviceSelect:"required",
Subject:"required",
Advice:"required",
BookSelect:"required"
},
messages: {
CategoryAdviceSelect:"Please select one of category advice",
Subject:"This field is required",
Advice:"This field is required",
BookSelect:"This field is required"
},
errorElement: "span",
highlight: function(element) {
$(element).parent().addClass("help-block");
},
unhighlight: function(element) {
$(element).parent().removeClass("help-block");
}
});
});
</script>
And my html view
<div class="row-fluid ">
<div class="box">
<hr>
<div class="paragraph">
<p>For enquiries about our services, write to: helpdesk#library.binus.ac.id.</p>
<p>You may also reach us at our helpdesk number 62-21-5350660. We value your feedback. Please fill in the form below, and help us improve our services.</p>
<p>Talk to me here
<a href = 'ymsgr:sendim?me_lieza93'>
<img src="http://opi.yahoo.com/online?u=me_lieza93&m=g&t=1" border=0>
</a>
</p>
</div>
<!--START FORM-->
<form id="feedback_form" name="feedback_form" action="<?php echo base_url();?>feedback/feedback/insert_to_db" method="post" class="form-horizontal" novalidate="novalidate">
<div class="control-group">
<!--FEEDBACK TYPE-->
<label class="span2 control-label" >Feedback for</label>
<div class="controls with-tooltip">
<select class="input-tooltip span5" tabindex="2" id="CategoryAdviceSelect" name="CategoryAdviceSelect" onchange="showhidebook();" >
<option value="" disabled selected>Choose Your Feedback For..</option>
<?php
for($x = 0 ; $x < count($feedback) ; $x++)
{ ?>
<option value="<?php echo $feedback[$x]['CategoryAdviceId']?>"><?php echo $feedback[$x]['CategoryAdviceName'] ?></option>
<?php
} ?>
</select>
</div>
</div>
<!--SUBJECT-->
<div class="control-group">
<label for="limiter" class="control-label">Subject</label>
<div class="controls">
<input type="text" class="span5" maxlength="50" id="Subject" name="Subject" placeholder="Type Your Feedback Subject.." />
<p class="help-block"></p>
</div>
</div>
<div id="emptybox"></div>
<!--CHOOSE BOOK-->
<div id="showupbox" style="display: none;">
<div class="control-group">
<label class="control-label">Choose Book</label>
<div class="controls">
<select class="chzn-select span5" tabindex="2" id="BookSelect" name="BookSelect">
<option value="" disabled selected>Choose Your Feedback For..</option>
<?php
for($y = 0 ; $y < count($booklist) ; $y++)
{ ?>
<option value="<?php echo $booklist[$y]['bi']?>"><?php echo $booklist[$y]['AssetTitle']?></option>
<?php
} ?>
</select>
</div>
</div>
</div>
<!--ADVICE-->
<div class="control-group">
<label for="limiter" class="control-label" >Suggestion</label>
<div class="controls">
<?php echo $this->ckeditor->editor("Advice",""); ?>;
</div>
</div>
<!--div class="alert alert-success">
<a class="close" data-dismiss="alert">×</a>
<strong>Success!</strong> Thanks for your feedback!
</div-->
<div class="bton1">
<button class="btn btn-primary round" type="submit">Submit</button>
<button class="btn btn-primary round" type="refresh">Reset</button>
</div>
</form>
</div><!--END BOX-->
Finally I can solve this..
<script>
$(document).ready(function() {
for(var name in CKEDITOR.instances) {
CKEDITOR.instances["Advice"].on("instanceReady", function() {
// Set keyup event
this.document.on("keyup", updateValue);
// Set paste event
this.document.on("paste", updateValue);
});
function updateValue() {
CKEDITOR.instances["Advice"].updateElement();
$('textarea').trigger('keyup');
}
}
$("#feedback_form").validate({
ignore: 'input:hidden:not(input:hidden.required)',
rules: {
CategoryAdviceSelect:"required",
Subject:"required",
Advice:"required",
BookSelect:{
required: function(element){
return $("#CategoryAdviceSelect").val()==1;
}
}
},
messages: {
CategoryAdviceSelect:"Please select one of category advice",
Subject:"This field is required",
Advice:"This field is required",
BookSelect:"This field is required",
},
errorElement: "span",
errorPlacement: function (error, element) {
if ($(element).attr('name') == 'Advice') {
$('#cke_Advice').after(error);
} else {
element.after(error);
}
},
highlight: function(element) {
$(element).parent().addClass("help-block");
},
unhighlight: function(element) {
$(element).parent().removeClass("help-block");
}
});
});
</script>

Categories

Resources