Dynamic dependent dropdown laravel - javascript

So, basically I want to create a dynamic dropdown on my form.
1 sasaran has many indikators, so what i want is, when i clicked 1 of the sasaran, indikator's dropdown will show up the indikator that belongs to that sasaran.
here's my view:
<div class="form-group col-md-5">
<label for="sasaran_id">Sasaran</label>
<select id="sasaran_id"
class="selectpicker form-control #error ('sasaran_id') is-invalid #enderror"
name="sasaran_id">
<option selected disabled>--silahkan pilih sasaran berikut--</option>
#foreach ($sasaran_id as $datasasaran)
<option value="{{ $datasasaran->id }}">{{$datasasaran->sasaran}}</option>
#endforeach
</select>
#error('sasaran_id')
<div class="invalid-feedback">
{{ $message }}
</div>
#enderror
</div>
<div id="indikatorSection">
<div class="form-row align-items-end ml-2 indikator">
<div class="form-group col-md-5">
<label for="indikator_id">Indikator</label>
<select id="indikator_id"
class="form-control #error ('indikator_id') is-invalid #enderror"
name="indikator_id[]">
<option selected disabled>--silahkan pilih indikator berikut--</option>
#foreach ($indikator_id as $dataindikator)
<option value="{{ $dataindikator->id }}">{{$dataindikator->indikator}}</option>
#endforeach
</select>
#error('indikator_id')
<div class="invalid-feedback">
{{ $message }}
</div>
#enderror
</div>
<div class="form-group col-md-1">
<label for="target_kinerja">Target</label>
<input type="number" name="target_kinerja[]"
class="form-control #error('target_kinerja') is-invalid #enderror"
id="target_kinerja" placeholder="" value="{{old('target_kinerja')}}">
#error('target_kinerja')
<div class="invalid-feedback">
{{ $message }}
</div>
#enderror
</div>
<div class="form-group col-md-1">
<button type="button" id="tambahIndikator" class="btn btn-primary"> Tambah </button>
</div>
</div>
</div>
js
<script>
$(document).ready(function () {
$('select[name=sasaran_id]').change(function() {
var url = '{{ url('sasaran') }}' + $(this).val() + '/indikator';
$.get(url, function(data) {
var select = $('form select[name=indikator_id[]]');
select.empty();
$.each(data,function(key, value) {
select.append('<option value=' + value.id + '>' + value.indikator + '</option>');
});
});
});
});
</script>
indikatorModel
public function sasaran()
{
return $this->belongsTo('App\ModelPerencanaan\SasaranModel');
}
sasaranModel
public function indikator()
{
return $this->hasMany('App\ModelPerencanaan\IndikatorModel','sasaran_id');
}
routes
Route::get('sasaran/{sasaran_id}/indikator', 'UnitKerja\Perencanaan\RabController#cariIndikator');
controller
public function cariIndikator($sasaran_id)
{
$sasaran = SasaranModel::find($sasaran_id);
return $sasaran->indikator()->select('id', 'indikator')->get();
}
it works well when i tried the url on route.. but it seems my js didnt work :/ is there something i miss?

Ahh i found the answer myself.. so basically after debugging the javascript i found that i cant select name with array so, what i need to put is [name="indikator[]"]. then the code change as below:
<script>
$(document).ready(function () {
$('select[name=sasaran_id]').change(function() {
var url = '{{ url('sasaran') }}' + '/' + $(this).val() + '/indikator';
console.log(url);
$.get(url, function(data) {
var select = $('form select[name="indikator_id[]"]');
select.empty();
$.each(data,function(key, value) {
select.append('<option value=' + value.id + '>' + value.indikator + '</option>');
});
});
});
});
</script>

Related

Selected Item in Without using the method "change" in dropdown list in Jquery and Asp.Net Core?

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 ?

Button click function not working in jQuery

So I'm developing a website for a medical clinic and they asked me to add a button beneath every doctor to make an appointment.
this is what i have for the doctors section
for (var i = 0; i < 3; i++) {
$('#get_medicos').append(
'<div class="col-md-3 dummy">' +
'<div class="text-box">' +
'<img src="assets/images/corpo-clinico/' + medico[i].ficheiro + '" alt="" class="img-responsive"/>' +
'<div class="clearfix"></div>' +
'<div class="text-box white padding-3">' +
'<h5 class="less-mar1 text-blue">' + medico[i].nome +'</h5>' +
'<p>' + medico[i].especialidade + '</p>' +
'<a id="marcar" type="button" class="btn btn-primary">Marcar consulta</a>' +
'</div>' +
'</div>' +
'</div>'
);
}
The then code for the click function (that doesn't work):
$('#marcar').click(function() {
var offset = $('#marcacao').offset();
$('html, body').animate({
scrollTop: offset.top-100,
scrollLeft: offset.left
}, 1000);
$('#marcacao-consulta').find('#especialidade-marcacao option[id="default"]').text(medico[i].especialidade);
$('#marcacao-consulta').find('#corpo-clinico option[id="default"]').text(medico[i].nome);
console.log('test');
});
This is all inside a $(document).ready(function() {}); and what should do is when i click that button beneath the doctor, should go up to the form and fill the doctor's name and specialty... but it seems it's not working for some reason... this is a copy of other click functions in the code, but they seem to work fine.
HTML form:
<div id="marcacao-consulta" data-target="#marcacao-consulta">
<div class="row">
<div class="col-md-6 col-lg-6 col-sm-12">
<div class="section">
<label class="field select prepend-icon">
<select id="especialidade-marcacao" class="gui-input">
<option id="especialiade-default" value="default">Escolha a especialidade</option>
<?
$query = $dbHandle->prepare("
SELECT `especialidade`
FROM `especialidade`
ORDER BY `especialidade` ASC
");
$query->execute();
if ($query->rowCount() > 0) {
while ($row = $query->fetch(PDO::FETCH_ASSOC)) { ?>
<option value="<?=$row["especialidade"]; ?>"><?=$row["especialidade"]; ?></option>
<? }
} else { ?>
<option value="">Nenhum resultado</option>
<? }
?>
</select>
<span class="field-icon"><i class="fas fa-heartbeat"></i></span>
</label>
</div>
</div>
<div class="col-md-6 col-lg-6 col-sm-12">
<div class="section">
<label class="field select prepend-icon">
<select id="corpo-clinico-marcacao" class="gui-input">
<option id="corpo-clinico-default" value="default">Escolha o médico</option>
<?
$query = $dbHandle->prepare("
SELECT `nome`
FROM `medico`
ORDER BY `nome` ASC
");
$query->execute();
if ($query->rowCount() > 0) {
while ($row = $query->fetch(PDO::FETCH_ASSOC)) { ?>
<option value="<?=$row["nome"]; ?>"><?=$row["nome"]; ?></option>
<? }
} else { ?>
<option value="">Nenhum resultado</option>
<? }
?>
</select>
<span class="field-icon"><i class="fas fa-user-md"></i></span>
</label>
</div>
</div>
<div class="col-md-12 col-lg-12 col-sm-12">
<div class="section">
<label class="field prepend-icon">
<input id="nome" class="gui-input" type="text" placeholder="Nome Completo">
<span class="field-icon"><i class="fas fa-user"></i></span>
</label>
</div>
<div class="section">
<label class="field prepend-icon">
<input id="email" class="gui-input" type="text" placeholder="Endereço de correio eletrónico">
<span class="field-icon"><i class="fas fa-envelope"></i></span>
</label>
</div>
<div class="section">
<label class="field prepend-icon">
<input id="telefone" class="gui-input" type="text" placeholder="Telefone/Télemovel">
<span class="field-icon"><i class="fas fa-phone-square"></i></span>
</label>
</div>
<div class="section">
<label class="field prepend-icon">
<input id="tipo" class="gui-input" type="text" value="consulta" disabled>
</label>
</div>
</div>
</div>
</div>
You have to add the element and register the event for the element. Here is the fiddle which works for you
https://jsfiddle.net/0q3kpyfv/
Your sample HTML
<div id="get_medicos">
</div>
Sample jquery code
Notice I have added the data-val attribute to the added anchor tag which will help you to get the information and perform the logic based on which button is clicked. you can pass dynamic data to data-val attribute and use it in click event.
$(document).ready(function() {
var sampleString = "";
var medico = [{'especialidade':'speciality 0','nome':'Doctor 0'},{'especialidade':'speciality 1','nome':'Doctor 1'},{'especialidade':'speciality 2','nome':'Doctor 2'}]
for (var i = 0; i < 3; i++) {
var doctorData = medico[i];
$('#get_medicos').append(
'<div class="col-md-3 dummy">' +
'<div class="text-box">' +
'<img src="assets/images/corpo-clinico/' + medico[i].especialidade + '" alt="" class="img-responsive"/>' +
'<div class="clearfix"></div>' +
'<div class="text-box white padding-3">' +
'<h5 class="less-mar1 text-blue">' + medico[i].nome +'</h5>' +
'<p>' + medico[i].especialidade + '</p>' +
'<a id="marcar" data-doctor-especialiadade="'+medico[i].especialidade+'" data-doctor-nome="'+medico[i].nome+'" type="button" class="btn btn-primary">Marcar consulta'+i+'</a>' +
'</div>' +
'</div>' +
'</div>'
);
};
$('#get_medicos').on('click','a',function(event){
var elementClicked = event.target;
var doctorEspecialiadade = $(elementClicked).data('doctor-especialiadade');
var doctorName = $(elementClicked).data('doctor-nome');
$('#marcacao-consulta').find('#especialidade-marcacao option[id="default"]').text(doctorEspecialiadade);
$('#marcacao-consulta').find('#corpo-clinico option[id="default"]').text(doctorName);
})
});
if you create the button after your event, you could have problem so, use the delegate version of click:
$('div').on('click', 'a', (function()....
and better put an id on the ancestor div:
'<div class="text-box white padding-3" id="mydiv"'
:
$('#mydiv').on('click', 'a', (function()....
another thing, with the loop you will have same id more time in your html??its no good.
so you'll have to rebuild your program logic...and bind the event with the right button (use a common class) it will be better than an id
If you bind the event to the parent element, and filter by the children, you can listen to any new elements that are added, doesn't matter how many.
<div class="container"></div>
<button class="js-add-new">Add new</button>
const $addNew = $('.js-add-new')
const $container = $('.container')
let count = 0
$addNew.on("click", () => {
count += 1
$container.append(`
<div>
<button>log me ${count}</button>
</div>
`)
})
$container.on("click", "button", (event) => {
console.log(event.currentTarget)
})
A working example: https://codepen.io/alexmccabe/pen/jOrXZxj?editors=1111
The button click is working. Here is a fiddle showing it does:
https://jsfiddle.net/bradberkobien/qL4m10y6/3/
There must be an issue with the code that comes before the console.log("test") line within the click. I would use the debugger to help you with that.

create a new function

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))
}
});

Save multiple dynamically added file in mongoose

I'm using Ajax to add (and remove) multiple fields in a form, and then submitting them to mongoose to save them. Unfortunatelly I'm able to retrieve and save only 1 array, missing completely the dinamically added ones.
HTML: Here's a form with a form-group visible, where I inizialise the array using name attributes,and a form-group template that I dinamically populate with Ajax
<form id="productAdd" class="form-horizontal" method="post" enctype="multipart/form-data" action="?_csrf={{csrfToken}}">
<section class="panel">
<div class="panel-body">
<div class="form-group" data-option-index="1">
<label class="col-md-3 control-label" for="optionType">Type</label>
<div class="col-md-1">
<select class="form-control" name="options[0][optionType]">
<option value="grams">Gr.</option>
</select>
</div>
<label class="col-md-1 control-label" for="value">Value</label>
<div class="col-md-1">
<input type="text" class="form-control" name="options[0][optionValue]">
</div>
<label class="col-md-1 control-label" for="price">Price</label>
<div class="col-md-1">
<input type="text" class="form-control" name="options[0][optionPrice]">
</div>
<div class="col-md-1">
<button type="button" class="btn btn-default addButton"><i class="fa fa-plus"></i></button>
</div>
</div>
<div class="form-group hide" id="optionTemplate">
<label class="col-md-3 control-label" for="optionType">Type</label>
<div class="col-md-1">
<select class="form-control" name="optionType">
<option value="grams">Gr.</option>
</select>
</div>
<label class="col-md-1 control-label" for="value">Value</label>
<div class="col-md-1">
<input type="text" class="form-control" name="optionValue">
</div>
<label class="col-md-1 control-label" for="price">Price</label>
<div class="col-md-1">
<input type="text" class="form-control" name="optionPrice">
</div>
<div class="col-md-1">
<button type="button" class="btn btn-default removeButton"><i class="fa fa-minus"></i></button>
</div>
</div>
</div>
<footer class="panel-footer">
<div class="row">
<div class="col-sm-9 col-sm-offset-3">
<input type="hidden" name="_csrf" value="{{csrfToken}}">
<button class="btn btn-primary">Submit</button>
<button type="reset" class="btn btn-default">Reset</button>
</div>
</div>
</footer>
</section>
</form>
AJAX: I use this to add rows or remove them, each with 3 inputs. Before submitting the form I use .serialize() to get the arrays by their names
$(document).ready(function() {
var optionIndex = $(".form-group[data-option-index]").length;
$('#productAdd').submit(function(e) { // add product submit function
e.preventDefault();
$(this).ajaxSubmit({
contentType: 'application/json',
data: $('form[name="productAdd"]').serialize(),
error: function(xhr) {
console.log('Error: ' + xhr.status + ' ---- ' + xhr.responseText);
},
success: function(response) {
if (typeof response.redirect === 'string')
window.location = response.redirect;
}
});
return false;
})
// Add button click handler
.on('click', '.addButton', function() {
optionIndex++;
var $template = $('#optionTemplate'),
$clone = $template
.clone()
.removeClass('hide')
.removeAttr('id')
.attr('data-option-index', optionIndex)
.insertBefore($template);
// Update the name attributes
$clone
.find('[name="optionType"]').attr('name', 'options[' + optionIndex + '].optionType').end()
.find('[name="optionValue"]').attr('name', 'options[' + optionIndex + '].optionValue').end()
.find('[name="optionPrice"]').attr('name', 'options[' + optionIndex + '].optionPrice').end();
})
// Remove button click handler
.on('click', '.removeButton', function() {
var $row = $(this).parents('.form-group'),
index = $row.attr('data-option-index');
// Remove fields
$row.find('[name="options[' + index + '].title"]').remove();
$row.find('[name="options[' + index + '].isbn"]').remove();
$row.find('[name="options[' + index + '].price"]').remove();
// Remove element containing the fields
$row.remove();
});
});
NODEJS: Here's my nodejs route, I use multer for managing file upload. I've a foreach should manage the inputs from the form, but it just see the first element.
router.post('/shop/products/add', [isLoggedIn, multer({dest: './public/images/products/'}).single('productPhoto')], function(req, res, next) {
var newProduct = new Product();
newProduct.imagePath = req.file.filename;
newProduct.title = req.body.title;
newProduct.description = req.body.description;
newProduct.price = req.body.price;
newProduct.save()
.then(function (product) {
console.log(req.body.options);
req.body.options.forEach(function (option) {
var newOption = new ProductOption();
newOption.type = option.optionType;
newOption.value = option.optionValue;
newOption.price = option.optionPrice;
newOption.product = product;
newOption.save();
});
})
.then(function (options) {
req.flash('success', 'Product uploaded correctly.');
res.send({redirect: '/user/shop/products/add'});
})
.catch(function (err) {
console.log('Error ' + err.code + ': ', err.message);
res.status(500).send('Failed to save the newAddress to DB: ' + err);
});
});
It was a simple mistake, I named the fields dinamically added, differently from the static ones.
this code
.find('[name="optionType"]').attr('name', 'options[' + optionIndex + '].optionType').end()
should be like this
.find('[name="optionType"]').attr('name', 'options[' + optionIndex + '][optionType]').end()

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!

Categories

Resources