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!
Related
I have this code that works well but ...
$("#maincategory").change(function () {
$("#ParentId").empty();
$.getJSON("/AdminPanel/Category/GetSubCategory/" + $("#maincategory :selected").val(),
function (data) {
$.each(data,
function () {
$("#ParentId").append('<option value= ' + this.value + '>' + this.text + '</option>');
})
}
)
});
Html code :
<div class="form-group">
<label class="control-label">choose main category</label>
<select class="form-control" id="maincategory" asp-items="ViewBag.maincategory">
</select>
</div>
<div class="form-group">
<label class="control-label">choose first category</label>
<select class="form-control" asp-for="ParentId">
</select>
<span asp-validation-for="ParentId" class="text-danger"></span>
</div>
I want to give maincategory a value And get ParentId automatically from controller ?
I have a new Order page, in this page, user should select the category, then, select the service and then, fill quantity field for the order.
I want create a change, I want to define a function with #if and #else
In this function, let's say if the service is not selected, the quantity field is not displayed
But if it was selected, the quantity field would appear
But I do not know how to define this function.
this is my code:
#extends('user.layouts.master')
#section('site_title', 'New Order')
#section('page_title')
<i class="fa fa-first-order"></i>New Order
#endsection
#section('body')
<div class="row">
<div class="col-md-6 offset-md-3">
#include('user.layouts.flash')
<div class="card">
<div class="card-header d-flex align-items-center">
<h3 class="h4">Submit new order</h3>
</div>
<div class="card-body">
<form action="{{ route('newOrder.store') }}" method="post">
#csrf
<div class="form-group">
<label class="form-control-label"><b>category</b></label>
<select class="form-control" id="category" name="category" required>
<option>Select category</option>
#foreach($categories as $category)
<option value="{{ $category->id }}">{{ $category->name }}</option>
#endforeach
</select>
</div>
<div class="form-group">
<label class="form-control-label"><b>Service</b></label>
<select class="form-control input-lg" id="service" name="service" required>
</select>
</div>
#if ($item->service)
<div class="form-group">
<label for="details" class="control-label">Details</label>
<textarea name="details"
id="details"
rows="5"
style="height: 150px"
class="form-control" readonly></textarea>
<div class="form-group">
<label class="form-control-label"><b>quantity</b></label>
<input class="form-control" name="quantity" id="quantity" required>
</div>
<div class="row">
<div class="col-md-6">
<label style="color: #080B6A"><b>Min:</b><span id="min">0</span></b></label>
</div>
<div class="col-md-6">
<label style="color: #080B6A"><b>Max: </b><span id="max">0</span></b></label>
</div>
</div><br>
<div class="row">
<div class="col-md-6">
<label class="btn btn-success">Total price: <span
id="price">0</span> {{ $general->base_currency }}</label>
</div>
</div><br>
<div class="form-group">
<input type="submit" value="Submit" class="btn btn-primary btn-block">
</div>
</form>
</div>
</div>
</div>
</div>
#endsection
#section('scripts')
<script type="text/javascript">
$(document).ready(function () {
// fetch Service
$(document).on('change', '#category', function () {
var serId = $('option:selected', this).val();
$.ajax({
type: 'POST',
url: '{{ route('get.pack') }}',
data: {id: serId},
success: function (data) {
$('#service').html('');
$('#service').append('<option>Select service</option>');
$.each(data, function (index, value) {
$('#service').append('<option value="' + value.id + '">' + value.name + '</option>');
});
var total = 0;
$('#details').text();
$('#min').text(0);
$('#max').text(0);
$('#price').text(total.toFixed(2))
},
})
});
//package price and quantity
var price = 0;
var quantity = 0;
$(document).on('change', '#service', function () {
var serviceId = $('option:selected', this).val();
if (!isNaN(serviceId)) {
$.ajax({
type: 'POST',
url: '{{ route('get.pack.details') }}',
data: {id: serviceId},
success: function (data) {
$('#details').text(data.details);
$('#min').text(data.min);
$('#max').text(data.max);
price = data.price_per_k;
var total = (price * quantity) / 1000;
$('#price').text(total.toFixed(2))
},
});
} else {
$('#details').text(0);
$('#min').text(0);
$('#max').text(0);
price = 0;
quantity = 0;
var total = 0;
$('#price').text(total.toFixed(2))
}
});
$(document).on('keyup', '#quantity', function () {
quantity = $(this).val();
var total = (price * quantity) / 1000;
$('#price').text(total.toFixed(2))
});
});
</script>
#endsection
you can do this using javascript
// first we hide what we want using style="display:none" and add a calss or attribute to the hidden elements ex: hidden-elements
<div class="form-group hidden-elements" style="display:none">
<label class="form-control-label"><b>quantity</b></label>
<input class="form-control" name="quantity" id="quantity" required>
</div>
// when we change the value of the service
$(document).on('change', '#service', function () {
var serviceId = $('option:selected', this).val();
if (!isNaN(serviceId)) {
// here we show the hidden elements after we choose the service
$('.hidden-elements').show();
$.ajax({
type: 'POST',
url: '{{ route('get.pack.details') }}',
data: {id: serviceId},
success: function (data) {
$('#details').text(data.details);
$('#min').text(data.min);
$('#max').text(data.max);
price = data.price_per_k;
var total = (price * quantity) / 1000;
$('#price').text(total.toFixed(2))
},
});
} else {
$('#details').text(0);
$('#min').text(0);
$('#max').text(0);
price = 0;
quantity = 0;
var total = 0;
$('#price').text(total.toFixed(2))
}
});
This question already has answers here:
jQuery: Conflict with removeData() executing at inadequate times
(3 answers)
Closed 5 years ago.
I have a modal window used to update or add a new object Store.
This modal is called remotely which information is loaded from a GET method constructed in ASP.NET.
Button that calls the modal:
<div class="btn-group" id="modalbutton">
<a id="createEditStoreModal" data-toggle="modal" asp-action="Create"
data-target="#modal-action-store" class="btn btn-primary">
<i class="glyphicon glyphicon-plus"></i> NEW STORE
</a>
</div>
Html of the modal:
#model Application.Models.ApplicationviewModels.StoreIndexData
#using Application.Models
<form asp-action="Create" role="form">
#await Html.PartialAsync("_ModalHeader", new ModalHeader
{ Heading = String.Format("Actualización de Modelo: Tiendas") })
<div asp-validation-summary="ModelOnly" class="text-danger"></div>
<div class="modal-body form-horizontal">
<div class="form-group">
<label asp-for="DepartmentID" class="col-md-2 control-label"></label>
<div class="col-md-10">
<select asp-for="DepartmentID" class="form-control"
asp-items="#(new SelectList(#ViewBag.ListofDepartment,"DepartmentID","DepartmentName"))"></select>
</div>
</div>
<div class="form-group">
<label class="col-md-2 control-label">Distrito</label>
<div class="col-md-10">
<select class="form-control" id="DistrictID" name="DistrictID" asp-for="DistrictID"
asp-items="#(new SelectList(#ViewBag.ListofDistrict,"DistrictID","DistrictName"))"></select>
</div>
</div>
{... more elements}
</div>
</form>
GET Method:
public IActionResult Create(int? id)
{
List<Department> DepartmentList = new List<Department>();
DepartmentList = (from department in _context.Departments
select department).ToList();
DepartmentList.Insert(0, new Department { DepartmentID = 0, DepartmentName = "-- Seleccione Departamento --" });
ViewBag.ListofDepartment = DepartmentList;
StoreIndexData edit = new StoreIndexData();
List<District> ListofDistrict = new List<District>();
ListofDistrict.Insert(0, new District { DistrictID = 0, DistrictName = "-- PRUEBA --" });
ViewBag.ListofDistrict = ListofDistrict;
return PartialView("~/Views/Shared/Stores/_Create.cshtml");
}
The problem:
I have the following jQuery which asigns a value to DistrictID once the modal opens:
<script type="text/javascript">
var wasclicked = 0;
var $this = this;
$(document).ready(function () {
document.getElementById("modalbutton").onclick = function () {
//is AddNew Store button is hitted, this var = 1
wasclicked = 1;
};
$('#modal-action-store').on('hidden.bs.modal', function () {
//global.wasclicked = 0;
wasclicked = 0;
$(this).removeData('bs.modal');
});
$('#modal-action-store').on('shown.bs.modal', function (e) {
console.log($('#DistrictID').length);
//if wasclicked equals 1 that means we are in the AddNew Store scenario.
if (wasclicked == 1) {
//a default value is sent to District dropdownlist
var items = "<option value='0'>-- Seleccione Distrito --</option>";
$('#DistrictID').html(items);
};
});
});
</script>
The problem right now is that after this line jQuery is executed, the value that was assigned to DistrictID gets overwritten by :
ViewBag.ListofDistrict = ListofDistrict; //"-- PRUEBA --"
And this line is lost:
var items = "<option value='0'>-- Seleccione Distrito --</option>";
What I suspect is that the information coming from the Controller overwrites any result from jQuery over the in the modal.
After debugging I have identified three diferent moments:
Moment 1: First time we open the modal
The modal hasn't opened yet and the jQuery executes
For this reason it does not identify DistrictID
The result from the GET Action fills the modal's inputs.
Moment 2 - Part 1: Second time we open the modal
This time the modal opens before the jQuery is executed
The DistrictID has the value from the GET Method before we assign the value from jQuery
Moment 2 - Part 2: When the value from jQuery is assigned
The value from jQuery is assigned to DistrictID
This value will be overwritten by the result of the GET Action
Question:
Can anyone explain or help me understand what might be causing this? What else can I do to identify the reason behind this?
Try to replace your code:
var items = "<option value='0'>-- Seleccione Distrito --</option>";
$('#DistrictID').html(items);
by
var items = "<option value='0'>-- Seleccione Distrito --</option>";
var currentItems = $('#DistrictID').html();
$('#DistrictID').html(items + currentItems)
Hope this helps you :)
Trying moving the assigning of html to districtID from your main view to the document.ready of modal popUp view.
#model Application.Models.ApplicationviewModels.StoreIndexData
#using Application.Models
<form asp-action="Create" role="form">
#await Html.PartialAsync("_ModalHeader", new ModalHeader
{ Heading = String.Format("Actualización de Modelo: Tiendas") })
<div asp-validation-summary="ModelOnly" class="text-danger"></div>
<div class="modal-body form-horizontal">
<div class="form-group">
<label asp-for="DepartmentID" class="col-md-2 control-label"></label>
<div class="col-md-10">
<select asp-for="DepartmentID" class="form-control"
asp-items="#(new SelectList(#ViewBag.ListofDepartment,"DepartmentID","DepartmentName"))"></select>
</div>
</div>
<div class="form-group">
<label class="col-md-2 control-label">Distrito</label>
<div class="col-md-10">
<select class="form-control" id="DistrictID" name="DistrictID" asp-for="DistrictID"
asp-items="#(new SelectList(#ViewBag.ListofDistrict,"DistrictID","DistrictName"))"></select>
</div>
</div>
{... more elements}
</div>
</form>
<script type="text/javascript">
$(document).ready(function () {
//if wasclicked equals 1 that means we are in the AddNew Store scenario.
if (wasclicked == 1) {
//a default value is sent to District dropdownlist
var items = "<option value='0'>-- Seleccione Distrito --</option>";
$('#DistrictID').html(items);
}
});
</script>
PS: Default option can be also be used. refer the below code.
<div class="form-group">
<label class="col-md-2 control-label">Distrito</label>
<div class="col-md-10">
<select class="form-control" id="DistrictID" name="DistrictID" asp-for="DistrictID" asp-items="#(new SelectList(#ViewBag.ListofDistrict,"DistrictID","DistrictName"))">
<option value='0'>-- Seleccione Distrito --</option>
</select>
</div>
</div>
I have a simple modal popup that edits an item retrieved from the back end. The for has several input and select controls. The input form controls work properly but the select controls are not pre-populated as intended.
The basic architecture of my functions as follows:
function BootboxEditItem(id) {
$.ajax({
// Load back end data
})
.done(function(data) {
var itemData = data;
$.ajax({
// Load form template for modal
url: '/modal/item/edit-item.html',
......
})
.success: function (data) ({
var box = bootbox.confirm({
// Set up bootbox buttons;
},
callback: function(result){
// Post edited data back to the server
}
)};
box.on("shown.bs.modal", function(e) {
// Populate the modal here using data from the backend.
// This is where the problem lies!
})
box.modal("show");
});
}
Below is the full JavaScript code:
function BootboxEditItem(id) {
var itemDao = '';
$.ajax({
type: "GET",
contentType: "application/json",
url: "/api/item/edit/" + id,
dataType: "json",
cache: false
})
.done(function (data) {
itemDao = data;
$.ajax({
type: "GET",
url: '/modal/item/item-edit-form.html',
success: function (data) {
console.log(itemDao);
var box = bootbox.confirm({
message: data,
title: "Edit Item: [" + itemDao.item.sysId + "]",
buttons: {
cancel: {
label: "Cancel",
className: "btn-danger btn-fixed-width-100"
},
confirm: {
label: "Save",
className: "btn-success btn-fixed-width-100"
}
},
callback: function (result) {
}
});
box.on("shown.bs.modal", function(e) {
console.log(e.currentTarget);
var selectItemLevel = document.getElementById('editItemLevel');
console.log(selectItemLevel);
$(selectItemLevel).empty();
$.each(itemDao.itemLevels, function (key, index) {
var opt = document.createElement('option');
opt.value = index;
opt.innerHTML = 'Level ' + index;
selectItemLevel.appendChild(opt);
});
$(e.currentTarget).find('select[name="editItemLevel"]').val(selectItemLevel);
$(e.currentTarget).find('input[name="editIdentifier"]').val(itemDao.item.identifier);
$(e.currentTarget).find('textarea[name="editItemValue"]').val(itemDao.item.itemValue);
});
box.modal('show');
}
});
});
}
Here is the code for the HTML file:
<form id="editItem" action="/api/items/save" method="post">
<input type="hidden" name="artifactId" id="artifactId" value="" />
<input type="hidden" name="editId" id="editId" value="" />
<input type="hidden" name="editSysId" id="editSysId" value="" />
<input type="hidden" name="editSortIndex" id="editSortIndex" value="" />
<div class="row">
<div class="col-sm-6">
<div class="form-group">
<label for="editItemLevel">Item level:</label>
<select class="form-control" id="editItemLevel" name="editItemLevel"></select>
</div>
</div>
<div class="col-sm-6">
<div class="form-group">
<label for="editItemClass">Item class:</label>
<select class="form-control" id="editItemClass" name="editItemClass" onchange="itemEditClassChange();"></select>
</div>
</div>
</div>
<div class="row" id="editRequirementRow">
<div class="col-sm-6">
<div class="form-group">
<label for="editItemType">Requirement type:</label>
<select class="form-control" id="editItemType" name="editItemType"></select>
</div>
</div>
<div class="col-sm-6">
<div class="form-group">
<label for="createIdentTemplate">Identifier prefix:</label>
<select class="form-control" id="editIdentTemplate" name="editIdentTemplate" onchange="itemEditIdentTemplateChange();"></select>
</div>
</div>
</div>
<div class="row">
<div class="col-sm-6">
<div class="form-group">
<label for="createMediaType">Media type:</label>
<select class="form-control" id="editMediaType" name="editMediaType"></select>
</div>
</div>
<div class="col-sm-6" id="editIdentField">
<div class="form-group">
<label for="editIdentifier">Identifier:</label>
<input type="text" class="form-control" id="editIdentifier" name="editIdentifier" />
</div>
</div>
</div>
<div class="form-group">
<label for="editItemValue">Item details:</label>
<textarea class="form-control" rows="5" cols="50" id="editItemValue" name="editItemValue"></textarea>
</div>
And here is the output intended for one of the SELECT controls as printed by console.log();
<select class="form-control" id="editItemLevel" name="editItemLevel">
<option value="1">Level 1</option>
<option value="2">Level 2</option>
<option value="3">Level 3</option>
<option value="4">Level 4</option>
<option value="5">Level 5</option>
<option value="6">Level 6</option>
<option value="7">Level 7</option>
<option value="8">Level 8</option>
<option value="9">Level 9</option>
<option value="10">Level 10</option>
It seems your each loop is not properly appending the <option></option>.If you have chrome developer tools and you know how to use it, put a breakpoint in this function and make sure the select options are being created and added to the DOM:
$.each(itemDao.itemLevels, function (key, index) {
var opt = document.createElement('option');
opt.value = index;
opt.innerHTML = 'Level ' + index;
selectItemLevel.appendChild(opt); //breakpoint here
});
Also, since you are already using jQuery, you could add them to the DOM like this:
$.each(itemDao.itemLevels, function (key, index) {
$(selectItemLevel).append('<option value="'+index+'">Level '+index+'</option>');
});
Thanks to #nilerafetr24, but the problem was not about appending properly. Rather it was about how to get hold of the SELECT control before being shown.
Certainly, the following doesn't work document.getElementById('editItemLevel'), but the following works $(e.currentTarget).find('select[name="editItemLevel"])'.
So, my final solution is to rewrite the loop thus; after combining with the solution suggested by #nilerafetr24 which seems more efficient:
$.each(itemDao.itemLevels, function (key, index) {
$(e.currentTarget).find('select[name="editItemLevel"]).append('<option=value="'+index'">Level '+index+'</option');
});
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;
}
?>