create a new function - javascript

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

Related

Dependent select menu in Jquery Ajax

I want to create a form so that when the user selects the State, the office box will show the number of offices in that State, when the user selects the specific City will show the number of offices in that City and when the user selects the Hometown, the number of offices in that Home Town will only show in the select box. Please see the attached picture for a better understanding. I am completely new in this field so I can't do.
This is my HTML code
<div class="row">
<div class="col-md-3 mb-3">
<label for="" class="col-form-label">State</label>
<select name="" id="" class="form-control"></select>
</div>
<div class="col-md-3 mb-3">
<label for="" class="col-form-label">City</label>
<select name="" id="" class="form-control"></select>
</div>
<div class="col-md-3 mb-3">
<label for="" class="col-form-label">Home Town</label>
<select name="" id="" class="form-control"></select>
</div>
<div class="col-md-3 mb-3">
<label for="" class="col-form-label">Office</label>
<select name="" id="" class="form-control"></select>
</div>
</div>
This is jquery code
$(document).ready(function () {
$('#division-dd').on('change', function () {
var idDivision = this.value;
$("#office-dd").html('');
$.ajax({
url: "{{url('get-division-offices')}}",
type: "POST",
data: {
division_id: idDivision,
_token: '{{csrf_token()}}'
},
dataType: 'json',
success: function (result) {
$('#office-dd').html('<option value="">Select City</option>');
$.each(result.division_offices, function (key, value) {
$("#office-dd").append('<option value="' + value
.id + '">' + value.office_name + '</option>');
});
$('#office-dd').html('<option value="">Select Hometown</option>');
}
});
});
$('#distric-dd').on('click', function () {
var idDivisionOffice = this.value;
$("#office-dd").html('');
$.ajax({
url: "{{url('get-distric-offices')}}",
type: "POST",
data: {
distric_id: idDivisionOffice,
_token: '{{csrf_token()}}'
},
dataType: 'json',
success: function (res) {
$('#office-dd').html('<option value="">Select Hometown</option>');
$.each(res.distric_offices, function (key, value) {
$("#office-dd").append('<option value="' + value
.id + '">' + value.office_name + '</option>');
});
}
});
});
});

PHP laravel and JQuery AJAX append form input

Hey guys I am just wondering how I can append a view within Laravel to my page using AJAX.
How can I append just input nema="result" and insert data into the database with laravel.
Error: [HTTP/1.1 422 Unprocessable Entity 323ms]
My blad file
<form id="repeater_form" class="row" action="{{route('agreement.store')}}" method="post" enctype="multipart/form-data">
#csrf
<div class="col-sm-3 form-group">
<label>Year</label>
<select class="form-control select2" name="year" >
<option value="">--select--</option>
#foreach ($years as $key => $value)
<option value="{{ $key }}">{{ $value }}</option>
#endforeach
</select>
</div>
<div class="form-group">
<label>target</label>
<input type="text" name="target" id="target" class="form-control" />
</div>
<div id="repeater">
<div class="repeater-heading" align="right">
<button type="button" class="btn btn-primary repeater-add-btn">Add More Skill</button>
</div>
<div class="clearfix"></div>
<div class="items" data-group="programming_languages">
<div class="item-content">
<div class="form-group">
<div class="row">
<input type="text" name="result[]" id="result" class="form-control" required />
<div class="col-md-3" style="margin-top:24px;" align="center">
<button id="remove-btn" class="btn btn-danger" onclick="$(this).parents('.items').remove()">Remove</button>
</div>
</div>
</div>
</div>
</div>
</div>
<div class="col-sm-12 form-group">
<button name="insert" type="submit" class="btn btn-primary"><i class="fa fa-save"></i> Submit</button>
backe
</div>
</form>
Js File
<script>
$(document).ready(function(){
$("#repeater").createRepeater();
$('#repeater_form').on('submit', function(event){
event.preventDefault();
$.ajax({
url: '{{route('agreement.store')}}',
method:"POST",
data:$(this).serialize(),
success:function(data)
{
$('#repeater_form')[0].reset();
$("#repeater").createRepeater();
$('#success_result').html(data);
}
});
});
});
</script>
I am new in laravel Here what am I doing I am going to insert a simple form value into database. Now, what happen when I click on submit button it is not insert data. I have no idea about that. So, How can I do this? Please help me.
Thank You.
My Contoroller
public function store(CreateAgreement $request)
{
$agreements = new Agreement;
$agreements->target = $request->target;
$agreements->result = $request->result;
$agreements->years()->attach(request('year'));
$agreements->save();
return redirect()->route('agreement.index');
}
CreateAgreement Request
public function rules()
{
return [
'year' => ['required'],
'code' => ['required'],
'target' => ['required'],
'result' => ['required'],
];
}
Repeater js
jQuery.fn.extend({
createRepeater: function () {
var addItem = function (items, key) {
var itemContent = items;
var group = itemContent.data("group");
var item = itemContent;
var input = item.find('input,select');
input.each(function (index, el) {
var attrName = $(el).data('name');
var skipName = $(el).data('skip-name');
if (skipName != true) {
$(el).attr("name", group + "[" + key + "]" + attrName);
} else {
if (attrName != 'undefined') {
$(el).attr("name", attrName);
}
}
})
var itemClone = items;
/* Handling remove btn */
var removeButton = itemClone.find('.remove-btn');
if (key == 0) {
removeButton.attr('disabled', true);
} else {
removeButton.attr('disabled', false);
}
$("<div class='items'>" + itemClone.html() + "<div/>").appendTo(repeater);
};
/* find elements */
var repeater = this;
var items = repeater.find(".items");
var key = 0;
var addButton = repeater.find('.repeater-add-btn');
var newItem = items;
if (key == 0) {
items.remove();
addItem(newItem, key);
}
/* handle click and add items */
addButton.on("click", function () {
key++;
addItem(newItem, key);
});
}
});

how to push multivalues from many element with same class or id in ajax

I have created a form , that user can append the additional column that need to that form, for example I have column name in the form , if people want to add more column name , they just press the add button , and then select element for the column name and it will be added, so it will have 2 select element with same class, but the problem is , I dont know how to send the data with ajax so django views that can get the data.Every time that I try to print the result , it will print as [] which means: failed to push the data
here's the code
html
<div class="row mt">
<div class="col-lg-12">
<div class="form-panel">
<form class="form-horizontal style-form" action="#">
<div class="form-group">
<label class="control-label col-md-3">Database Name</label>
<div class="col-md-4">
<div class="input-group bootstrap-timepicker">
<div class="btn-group">
<select id = "tableselect" style="width:425px;background-color:white;height:30px;font-color:red;text-align-last:center;">
<!-- <li></li> -->
{% for table in obj2 %}
<option value = "{{table}}" >{{ table }}</option>
{% endfor %}
<!-- <li>Dropdown link</li> -->
</option>
</select>
</div>
</div>
</div>
</div>
<div class="form-group">
<label class="control-label col-md-3">Table Name</label>
<div class="col-md-4">
<div class="input-group bootstrap-timepicker">
<div class="btn-group">
<select id="dataselect" style="width:425px;background-color:white;height:30px;font-color:red;text-align-last:center;">
</select>
</div>
</div>
</div>
</div>
<div class="form-group">
<button class="btn btn-theme" onclick="return appendBox()">Add</button>
<label class="control-label col-md-3">Column Name</label>
<div class="col-md-4" id ="test">
<div class="btn-group">
<select class = "columnselect" style="width:425px;background-color:white;height:30px;font-color:red;text-align-last:center;">
</select>
</div>
</div>
</div>
<div class="form-group">
<button class="btn btn-theme" onclick=" return appendFilterBox()">Add</button>
<label class="control-label col-md-3">Filter</label>
<div class="col-md-4" id="filtbox">
<div class="input-group bootstrap-timepicker">
<div class="btn-group">
<select class="conditionselect" style="width:150px;background-color:white;height:30px;font-size:15px;text-align-last:center;">
</select>
<select class="operator" style="width:120px;background-color:white;height:30px;font-size:15px;text-align-last:center;">
<option> > </option>
<option> < </option>
<option> ≥ </option>
<option> ≤ </option>
<option> = </option>
</select>
<input class="parameter" type="text" style="width:150px;background-color:white;height:30px;font-size:15px;text-align-last:center;">
</input>
</div>
</div>
</div>
</div>
<div class="form-group">
<div class="col-md-4" id="showquery">
<div class="input-group bootstrap-timepicker">
<div class="btn-group">
<button id="result" class="btn btn-theme" type="submit" style="height:30px;width:100px;" onclick="return showQuery()">Show</button>
<button id="export" class="btn btn-theme" type="Export" style="height:30px;width:100px;" onclick="return ExportFile()">Export</button>
</div>
</div>
</div>
</div>
<div id="query_result">
</div>
</form>
script to append the box
<script>
function appendBox()
{
$('#test').append('<select class = "columnselect" style="width:425px;background-color:white;height:30px;font-color:red;text-align-last:center;"></select>')
return false
}
</script>
<script>
function appendFilterBox()
{
$('#filtbox').append('<select class="columnselect" style="width:125px;background-color:white;height:30px;font-size:15px;text-align-last:center;margin-top:5px;margin-right:2px"></select><select class="operator" style="width:125px;background-color:white;height:3 0px;font-size:15px;text-align-last:center;margin-top:5px;margin-right:3px"><option> > </option><option> < </option><option> ≥ </option><option> ≤ </option><option> = </option></select><input type="text" class="parameter" style="width:150px;background-color:white;height:30px;font-size:15px;"></input>')
return false
}
</script>
Ajax to send the data
<script>
$(document).ready(function() {
$("#result").click(function () {
var urls = "{% url 'polls:load-query' %}";
var table = $('#dataselect').val();
data = {
'name' : [],
'table': table,
'condition': []
};
$('#column-name .columnselect').each((idx, el) => data.name.push($(el).val()));
$('#filtbox .input-group').each((idx, el) => {
condition = {
'column' : $(el).find('.conditionselect').val(),
'operator' : $(el).find('.operator').val(),
'value' : $(el).find('.parameter').val()
};
data.condition.push(condition);
});
$.ajax({
url: urls,
data: data,
success: function(data) {
$("#query_result").html(data);
},
error: function(data)
{
alert("error occured");
}
});
});
});
</script>
is this the correct way to send multivalues with ajax? it seems the data didnt send properly when django want to get the data..
heres the view if you guys curious
def list_all_data(request):
import cx_Oracle
dsn_tns = cx_Oracle.makedsn('', '', sid='') #ip port and user and password i hide it for privacy
conn = cx_Oracle.connect(user=r'', password='', dsn=dsn_tns)
c = conn.cursor()
print(request.GET.getlist('condition'))
data_name = request.GET.get('name',1)
table_name = request.GET.get('table',1)
column = request.GET.get('condition', {}).get('column', 1)
print(column)
operator = request.GET.get('condition', {}).get('operator', 1)
print(operator)
value = request.GET.get('condition', {}).get('value', 1)
print(value)
c.execute("select "+data_name+" from "+table_name+" where "+column + operator+"'"+value+"'")
c.rowfactory = makeDictFactory(c)
columnalldata = []
columnallname = []
for rowDict in c:
columnalldata.append(rowDict[data_name])
columnallname.append(data_name)
context = {
'obj4' : columnalldata,
'column_name' : columnallname
}
return render(request,'query_result.html',context)

Dynamic dependent dropdown laravel

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>

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