how to call a selected select value with ajax and javascript? - javascript

I have a product update modal which is contains MainCategory, Category, SubCategory , ChildCategory . So I have script which calls other Category, SubCategory , ChildCategory with ajax when the new MainCategory selected.
But it's an update modal so when i just open the modal, there are only curreny values in those selects. But there are not other Category, SubCategory , ChildCategory values in those selects. I need those values so user can select another one.
I allready think about to call those Category, SubCategory , ChildCategory on the back-end and send it to front-end with view model but i dont wanna send lots of query to my database. Am i able to do that or not ? if i am able to do then how ?
HTML
<div class="col">
<label asp-for="#productUpdate.MainCategoryID" class="control-label">Ana Kategorisi</label>
<select asp-for="#productUpdate.MainCategoryID" class="form-control" data-width="100%" id="drpMainCatc" name="MainCategoryID" required>
#if (productUpdate.MainCategoryID != null)
{
<option value="#productUpdate.MainCategoryID" selected disabled hidden>#productUpdate.MainCategory.MainCategoryName</option>
#foreach (var mainCategory in Model.MainCategoriesForDropdownList)
{
<option value="#mainCategory.MainCategoryID">#mainCategory.MainCategoryName</option>
}
}
else
{
<option value="">Seçiniz</option>
#foreach (var mainCategory in Model.MainCategoriesForDropdownList)
{
<option value="#mainCategory.MainCategoryID">#mainCategory.MainCategoryName</option>
}
}
</select>
<span asp-validation-for="#productUpdate.MainCategoryID" class="text-danger"></span>
</div>
<div class="col">
<label asp-for="#productUpdate.CategoryID" class="control-label">Kategorisi</label>
<select asp-for="#productUpdate.CategoryID" class="form-control" data-width="100%" id="drpCatc" name="CategoryID" required>
#if (productUpdate.CategoryID != null)
{
<option selected="selected" value="#productUpdate.CategoryID">#productUpdate.Category.CategoryName</option>
}
else
{
<option value="">Seçiniz</option>
}
</select>
<span asp-validation-for="#productUpdate.CategoryID" class="text-danger"></span>
</div>
<div class="col">
<label asp-for="#productUpdate.SubCategoryID" class="control-label">Alt Kategorisi</label>
<select asp-for="#productUpdate.SubCategoryID" class="form-control" data-width="100%" id="drpSubCatc" name="SubCategoryID" required>
#if (productUpdate.SubCategoryID != null)
{
<option selected="selected" value="#productUpdate.SubCategoryID">#productUpdate.SubCategory.SubCategoryName</option>
}
else
{
<option value="">Seçiniz</option>
}
</select>
<span asp-validation-for="#productUpdate.SubCategoryID" class="text-danger"></span>
</div>
<div class="col">
<label asp-for="#productUpdate.ChildCategoryID" class="control-label">2.Alt Kategorisi</label>
<select asp-for="#productUpdate.ChildCategoryID" class="form-control" data-width="100%" id="drpChildCatc" name="ChildCategoryID" required>
#if (productUpdate.ChildCategoryID != null)
{
<option selected="selected" value="#productUpdate.ChildCategoryID">#productUpdate.ChildCategory.ChildCategoryName</option>
}
else
{
<option value="">Seçiniz</option>
}
</select>
<span asp-validation-for="#productUpdate.ChildCategoryID" class="text-danger"></span>
</div>
And Javascript with Ajax Call :
<script>
$("#drpMainCatc").change(function () {
var self = $(this);
var catItems = "";
$.ajax({
url: '/Company/GetCategories/?id=' + self.val(),
type: "GET",
dataType: "json",
success: function (data) {
catItems += "<option value='" + "0" + "' disabled selected >" + "Seçiniz" + "</option>";
$.each(data, function (index, item) {
catItems += "<option value='" + item.categoryID + "'>" + item.categoryName + "</option>";
});
$("#drpCatc").html(catItems);
$("#drpCatc").val($('#categoryID').val());
console.log($("#drpCatc").val($('#categoryID').val()));
},
error: function (xhr, ajaxOptions, thrownError) {
showError('Kategoriler yüklenirken hata oluştu, tekrar deneyiniz.')
}
});
$("#drpSubCatc").empty();
$("#drpChildCatc").empty();
});
$("#drpCatc").change(function () {
var self = $(this);
var subCatItems = "";
$.ajax({
url: '/Company/GetSubCategories/?id=' + self.val(),
type: "GET",
dataType: "json",
success: function (data) {
subCatItems += "<option value='" + "0" + "' disabled selected >" + "Seçiniz" + "</option>";
$.each(data, function (index, item) {
subCatItems += "<option value='" + item.subCategoryID + "'>" + item.subCategoryName + "</option>";
});
$("#drpSubCatc").html(subCatItems);
$("#drpSubCatc").val($('#subCategoryID').val());
},
error: function (xhr, ajaxOptions, thrownError) {
showError('1. Alt Kategoriler yüklenirken hata oluştu, tekrar deneyiniz.')
},
}); $("#drpChildCatc").empty();
});
$("#drpSubCatc").change(function () {
var self = $(this);
var childCatItems = "";
$.ajax({
url: '/Company/GetChildCategories/?id=' + self.val(),
type: "GET",
dataType: "json",
success: function (data) {
childCatItems += "<option value='" + "0" + "' disabled selected >" + "Seçiniz" + "</option>";
$.each(data, function (index, item) {
childCatItems += "<option value='" + item.childCategoryID + "'>" + item.childCategoryName + "</option>";
});
$("#drpChildCatc").html(childCatItems);
$("#drpChildCatc").val($('#childCategoryID').val());
},
error: function (xhr, ajaxOptions, thrownError) {
showError('2. Alt Kategoriler yüklenirken hata oluştu, tekrar deneyiniz.')
},
});
});
</script>

Related

Fill textbox with corresponding data of dropdown RestAPI Sharepoint Online

The working code below loads option values of dropdown id REG returned from the RestAPI call.
I would like to take the value of Title and fill its corresponding family value (returned in the same RestAPI call) into the textbox id Family with on change javascript event. Please advice.
<script>
SP.SOD.executeFunc('sp.js', 'SP.ClientContext', getAR);
var jresult;
function getAR() {
$.ajax({
url: _spPageContextInfo.webAbsoluteUrl + "/_api/web/lists/GetByTitle('List_Name')/items?$Select=Title,Family",
type: "GET",
headers: {"accept": "application / json;odata = verbose",},
success: function(data) {
jresult = data.d.jresult;
var options = "";
for(var i = 0; i < jresult.length; i++){
options = options + "<option value='" + jresult[i].Title + "'>" + jresult[i].Title + "</option>";
}
$("#REG").append(options);
},
error: function(error) {alert(JSON.stringify(error));}
});
}
function fillFamily() {
var x = document.getElementById("REG").value;
$( "Family" ).val( x.Family );
}
</script>
<select id="REG" name="REG" class="custom-select" required="required" onchange="fillFamily()"></select>
<input type="text" id="Family" name="Family">
I have updated your code, you could have a try. Corrected the error in your code.
<script>
$(function(){
getAR()
})
var jresult;
function getAR() {
$.ajax({
url: _spPageContextInfo.webAbsoluteUrl + "/_api/web/lists/GetByTitle('2/23')/items?$Select=Title",
type: "GET",
headers: {"accept": "application / json;odata = verbose",},
success: function(data) {
jresult = data.d.results;
var options = "";
for(var i = 0; i < jresult.length; i++){
options = options + "<option value='" + jresult[i].Title + "'>" + jresult[i].Title + "</option>";
}
$("#REG").append(options);
},
error: function(error) {alert(JSON.stringify(error));}
});
}
function fillFamily() {
var x = document.getElementById("REG").value;
$( "#Family" ).val( x );
}
</script>
<select id="REG" name="REG" class="custom-select" required="required" onchange="fillFamily()"></select>
<input type="text" id="Family" name="Family">
Updated:
<script>
$(function(){
getAR()
})
var jresult;
function getAR() {
$.ajax({
url: _spPageContextInfo.webAbsoluteUrl + "/_api/web/lists/GetByTitle('2/23')/items?$Select=Title,Family",
type: "GET",
headers: {"accept": "application / json;odata = verbose",},
success: function(data) {
jresult = data.d.results;
var options = "";
for(var i = 0; i < jresult.length; i++){
options = options + "<option value='" + jresult[i].Title + "'Family="+jresult[i].Family+">" + jresult[i].Title + "</option>";
}
$("#REG").append(options);
},
error: function(error) {alert(JSON.stringify(error));}
});
}
function fillFamily() {
var val=$("#REG").find("option:selected").attr("Family");
$( "#Family" ).val( val );
}
</script>
<select id="REG" name="REG" class="custom-select" required="required" onchange="fillFamily()"></select>
<input type="text" id="Family" name="Family">

Dependent dropdown using json

I am currently working on a dynamic dependent dropdown. I want a sidebar with each dropdown list depends on the one above it, so you based on what your selection is, the right data will show on the next selection. It should be Country -> Years -> Terms -> Movies. I don't know why my data won't retrieve data from the json file. I am new to programming so Any help would be greatly appreciated.
The Json file(moviessimple.js) format is like this:
{
"term": "2020W",
"Year": 2018,
"link": "https://www.imdb.com/title/tt6342440",
"title": "Funan",
"country": "France"
},
{
"term": "2020W",
"Year": 2017,
"link": "https://www.imdb.com/title/tt6516966",
"title": "And Then They Came for Us",
"country": "United States"
},
{
"term": "2020W",
"Year": 2019,
"link": "https://www.imdb.com/title/tt6751668",
"title": "Parasite",
"country": "South Korea"
},
Right now, my HTML file:
<!DOCTYPE html>
<html>
<head>
<title>Test2</title>
<script src="CountryPoints.js" type="text/javascript"></script>
<script src="moviessimple.js"></script>
</head>
<body>
<br /><br />
<div class="container">
<div>
<select name="country" id="country" class="form-control input-lg">
<option value="">Select country</option>
</select>
<br /><br />
<select name="Year" id="Year" class="form-control input-lg">
<option value="">Select year</option>
</select>
<br /><br />
<select name="title" id="title" class="form-control input-lg">
<option value="">Select movies</option>
</select>
</div>
</div>
<script>
$(document).ready(function(){
load_json_data('country');
function load_json_data(country, Year)
{
var html_code = '';
$.getJSON('moviessimple.js', function(data){
html_code += '<option value="">Select '+country+'</option>';
$.each(data, function(key, value){
if(country == 'country')
{
if(value.Year == '')
{
html_code += '<option value="'+value.country+'">'+value.title+'</option>';
}
}
else
{
if(value.Year == Year)
{
html_code += '<option value="'+value.country+'">'+value.title+'</option>';
}
}
});
$('#'+country).html(html_code);
});
}
$(document).on('change', '#country', function(){
var country_id = $(this).val();
if(country_id != '')
{
load_json_data('Year', country_id);
}
else
{
$('#Year').html('<option value="">Select year</option>');
$('#title').html('<option value="">Select movies</option>');
}
});
$(document).on('change', '#Year', function(){
var Year_id = $(this).val();
if(Year_id != '')
{
load_json_data('title', Year_id);
}
else
{
$('#title').html('<option value="">Select movies</option>');
}
});
});
</script>
</body>
</html>
you only need to get the data from server once, save it to global variable then update the dropdown from other function
var movieData = [];
var html_code = '';
load_json_data('country');
function load_json_data(country, Year) {
/*
// to apply in your page
$.getJSON('moviessimple.js', function (data) {
movieData = data;
$.each(movieData, function (index, value) {
html_code +=
'<option value="' + value.country + '">' + value.country + '</option>';
});
});
// and remove lines block below
*/
movieData = [
{
term: '2020W',
Year: 2018,
link: 'https://www.imdb.com/title/tt6342440',
title: 'Funan',
country: 'France',
},
{
term: '2020W',
Year: 2017,
link: 'https://www.imdb.com/title/tt6516966',
title: 'And Then They Came for Us',
country: 'United States',
},
{
term: '2020W',
Year: 2019,
link: 'https://www.imdb.com/title/tt6751668',
title: 'Parasite',
country: 'South Korea',
},
];
$.each(movieData, function (index, value) {
html_code +=
'<option value="' + value.country + '">' + value.country + '</option>';
});
$('#country').append(html_code);
}
function updateDropdown(country, year, title) {
if (!year) {
html_code = '<option value="">Select year</option>';
$.each(movieData, function (index, value) {
if (value.country == country) {
html_code +=
'<option value="' + value.Year + '">' + value.Year + '</option>';
}
});
// update year dropdown
$('#Year').html(html_code);
$('#title').html('<option value="">Select movies</option>');
} else {
html_code = '<option value="">Select movies</option>';
$.each(movieData, function (index, value) {
if (value.country == country) {
html_code +=
'<option value="' + value.title + '">' + value.title + '</option>';
}
});
// update year dropdown
$('#title').html(html_code);
}
}
$('#country, #Year, #title').on('change', function () {
if (this.id == 'country') {
// reset year and title
$('#Year').prop('selectedIndex', 0);
$('#title').prop('selectedIndex', 0);
}
if (this.id == 'title') {
console.log('The title is: ' + $(this).val());
} else {
var country = $('#country').val();
var year = $('#Year').val();
var title = $('#title').val();
updateDropdown(country, year, title);
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="container">
<div>
<select name="country" id="country" class="form-control input-lg">
<option value="">Select country</option>
</select>
<br /><br />
<select name="Year" id="Year" class="form-control input-lg">
<option value="">Select year</option>
</select>
<br /><br />
<select name="title" id="title" class="form-control input-lg">
<option value="">Select movies</option>
</select>
</div>
</div>

Why when i debug my value option tag html is undefined?

I've tried debugging the following error for several hours with no solution JS is still undefined but id parameter in controller has a value. Please help. I need it.
This html code when i debug, the value is undefined, why the value is undefined?
<select id="cmbTipe" class="form-control">
<option value="-1">Select Jenis</option>
<option value="undefined">undefined</option>
<option value="undefined">undefined</option>
</select>
My Controller
namespace PerhitunganKeuntunganParkir.Controllers{
public class ParkirController : Controller
{
private readonly JenisKendaraanRepository _jeniskendaraanRepository = null;
private readonly TipeKendaraanRepository _tipekendaraanRepository = null;
private readonly ParkirContext _context = null;
//Dependency Injection
public ParkirController(JenisKendaraanRepository jenisKendaraanRepository, TipeKendaraanRepository tipeKendaraanRepository, ParkirContext context)
{
_jeniskendaraanRepository = jenisKendaraanRepository;
_tipekendaraanRepository = tipeKendaraanRepository;
_context = context;
}
public async Task<ViewResult> GetAllJenis()
{
ViewBag.Jenis = await _jeniskendaraanRepository.GetJenisKendaraan();
return View();
}
public IActionResult LoadTipeC(int jenisId)
{
return Json(_context.TipeKendaraan.Where(s=>s.JenisKendaraanId ==
jenisId).Select(s=> new TipeKendaraanModel{
Id = s.Id,
Tipe=s.Tipe
}).ToList());
}
My View
In HTML my cascading dropdown the value is undefined, why does this happen? The JavaScript is working but the value is undefined in HTML
#{
ViewData["Title"] = "Input Form";
#model JenisKendaraanModel
<div class="container">
<form method="post" asp-action="GetAllJenis" asp-controller="Parkir">
<div class="form-group">
<label asp-for="Jenis"></label>
<select id="cmbJenis" class="form-control">
<option value="-1">Select Jenis</option>
#foreach (var jenis in ViewBag.Jenis)
{
<option value="#jenis.Id">#jenis.Jenis</option>
}
</select>
<span asp-validation-for="Jenis" class="text-danger"></span>
</div>
<div class="form-group">
<select id="cmbTipe" class="form-control">
</select>
</div>
<script src="~/lib/jquery/jquery.js" type="text/javascript"></script>
<script type="text/javascript">
$(document).ready(function () {
$('#cmbJenis').on('change', function () {
var jenisId = $('#cmbJenis option:selected').val();
$.ajax({
type: 'GET',
data: { jenisId: jenisId },
url: '#Url.Action("LoadTipeC","Parkir")',
success: function (result) {
//var tipe = JSON.parse(result);
var s = '<option value="-1">Select tipe</option>';
for (var i = 0; i < result.length; i++) {
s += '<option value="' + result[i].Id + '">' + result[i].Tipe + '</option>';
}
$('#cmbTipe').html(s);
}
});
});
});
</script>
</form>
</div>
After my test, I found that your problem may lie in your Js.
Try to change your code:
for (var i = 0; i < result.length; i++)
{
s += '<option value="' + result[i].Id + '">' + result[i].Tipe + '</option>';
}
To
for (var i = 0; i < result.length; i++)
{
s += '<option value="' + result[i].id + '">' + result[i].tipe + '</option>';
}
id and tipe the first letter should be lowercase.

Filter dropdown options by selected option value

I'm trying to make a dropdown option filter by another selected options value on dropdwon change event.
I'm trying do with this jquery but nothing happens.
$(function() {
var options = $("#selectAmount").html();
$("#currencyList").change(function(e) {
var text = $("#selectLang :selected").val();
$("#selectAmount").html(options);
if (text == "Select Amount") return;
$('#selectAmount :not([value^="' + text.substr(0, 3) + '"])').remove();
});
});
And The HTML + PHP
<select class="custom-select" id="selectLang">
<option selected disabled>Select Your Country </option>
<?php foreach($countries as $country): ?>
<option value="<?php echo $country['country_id']; ?> ">
<?php echo $country['country_name']; ?> </option>
<?php endforeach; ?>
</select>
<select name="currency" id="currencyList" class="custom-select">
<option selected disabled>Select Currency </option>
<?php foreach($currencies as $currency): ?>
<option value="<?php echo $currency['currency_id']; ?> ">
<?php echo $currency['currency_name']; ?> </option>
<?php endforeach; ?>
</select>
</div>
<div class="form-group">
<label for="amount">Custom Amount</label>
<div class="input-group">
<div class="input-group-prepend"> <span class="input-group-text">$</span>
</div>
View Plans
<select class="custom-select" id="selectAmount">
<option>Select Amount</option>
</select>
And The Full Jquery which I used for filtering
$(document).ready(function() {
// ------------------ [ Country dropdown Change Event ] --------------
$("#selectLang").change(function() {
var countryId = $(this).val();
$("#selectFrame").fadeIn('slow');
$.ajax({
url: 'vendor/filter/process-controller.php',
type: 'POST',
data: {
langId: countryId
},
dataType: "JSON",
success: function(result) {
var items = "";
$("#selectFrame").empty();
$("#selectCode").empty();
$("#selectFrame").append(
"<option selected disabled> Select Operator </option>");
$("#selectCode").append(
"<input type='text' class='form-control form-control-md' id='selectCode' value=''>");
$.each(result, function(i, item) {
$("#selectFrame").append("<option value='" + item
.operator_id + "'>" + item.operator_name +
"</option>");
});
$.ajax({
url: 'vendor/filter/process-controller.php',
type: 'POST',
data: {
framId: countryId
},
dataType: 'JSON',
success: function(result) {
var code = "";
$("#selectCode").empty();
$.each(result, function(i, code) {
$('#selectCode').val(code.code);
});
$.ajax({
url: 'vendor/filter/process-controller.php',
type: 'POST',
data: {
cuId: countryId
},
dataType: 'JSON',
success: function(result) {
var amount = "";
$("#selectAmount").empty();
$.each(result, function(i, amount) {
$("#selectAmount").append("<option value='" + amount
.country_id + "'>" + amount.amount_name +
"</option>");
});
}
});
}
});
}
});
});
$("#currencyList").change(function() {
var currencyId = $(this).val();
$(this).fadeIn();$.ajax({
url: 'vendor/filter/process-controller.php',
type: 'POST',
data: {
amId: currencyId
},
dataType: 'JSON',
success: function(result) {
var amount = "";
$("#selectAmount").empty();
$.each(result, function(i, amount) {
$("#selectAmount").append("<option>" + amount.amount_name +
"</option>");
});
}
});
});
$(function() {
var options = $("#selectAmount").html();
$("#currencyList").change(function(e) {
var text = $("#selectLang :selected").val();
$("#selectAmount").html(options);
if (text == "Select Amount") return;
$('#selectAmount :not([value^="' + text.substr(0, 3) + '"])').remove();
});
});
});
Everything Works fine but when I select currency dropdown, The amount dropdown resets and shows all the value by currency id from database.
Screenshot 1 Screenshot 2
So, Now I exactly wanting to do removing the extra dropdowns by filtering with the value of Country dropdown.
Please kindly help to complete this...
Edit:
Again I tried this simple script
$("#currencyList").change(function() {
var sel = $("#currencyList :selected").val();
$("#selectAmount option[value!= '"+ sel + "' ]").remove();
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<select id="currencyList">
<option>Select Currency</option>
<option value="1"> Bitcoin </option>
<option value="2"> Ethereum </option>
<option value="3"> Litecoin </option>
</select>
<select id="selectAmount">
<option>Select Amount</option>
<option value="1"> 0.0001 BTC </option>
<option value="2"> 0.005 ETH </option>
<option value="3"> 0.5 LTC </option>
</select>
Now this Code works like a charm but if I I use this script to
$("#currencyList").change(function() {
var sel = $("#selectLang :selected").val();
$("#selectAmount option[value!= '"+ sel + "' ]").remove();
});
track the change of #currencyList and filter by the selected option value of #selectLang the code don't works....
Have any solution please...?
I have solved the problem.
The mistake was in the jquery is that I had used filter query in the below of OnChange function
$("#currencyList").change(function() {
var currencyId = $(this).val();
$(this).fadeIn();$.ajax({
url: 'vendor/filter/process-controller.php',
type: 'POST',
data: {
amId: currencyId
},
dataType: 'JSON',
success: function(result) {
var amount = "";
$("#selectAmount").empty();
$.each(result, function(i, amount) {
$("#selectAmount").append("<option>" + amount.amount_name +
"</option>");
});
}
});
});
$(function() {
var sel = $("#selectLang").find(':selected').val();
$("#selectAmount option[value!= '"+ sel + "' ]").remove();
});
});
});
Recently, I have understood the actual problem and fixed it by adding the the filter query into the Onchange SUCCESS result function ... Like This -
$("#currencyList").change(function() {
var currencyId = $(this).val();
$(this).fadeIn();
$.ajax({
url: 'vendor/filter/process-controller.php',
type: 'POST',
data: {
amId: currencyId
},
dataType: 'JSON',
success: function(result) {
var amount = "";
$("#selectAmount").empty();
$.each(result, function(i, amount) {
$("#selectAmount").append("<option value='" + amount
.country_id + "'>" + amount.amount_name +
"</option>");
});
var sel = $("#selectLang").find(':selected').val();
$("#selectAmount option[value!= '"+ sel + "' ]").remove();
}
});
});

How to get data from dynamic elements that added to the html page?

In below I write form part of my html page.
<form method="post" enctype="multipart/form-data">
<div>
<label>Brand Name:</label>
<input type="text" asp-for="#Model.Name">
</div>
<div id="divCategory">
</div>
<button type="button" id="btnAddCategory">Add Category</button>
<button>Create new Brand</button>
</form>
and I have two js and jquery function that add a select to divCategory. Whith this select I can add some categories.
function countMyCategories() {
if (typeof countMyCategories.counter == 'undefined') {
countMyCategories.counter = -1;
}
return ++countMyCategories.counter;
}
$(document).ready(function () {
$('#btnAddCategory').on('click', function () {
var catId = countMyCategories();
$('#divCategory').append(
'<select id="selectCategory' + catId + '" asp
for="##Model.CatBrands[' + catId + '].CatId" class="mt-3 form-control
form-control-sm">' +
'<option>---Select---</option>' +
'</select>'
);
$.ajax('/API/GetCats')
.done(function (categories) {
for (var i = 0; i < categories.length; i++) {
$('#selectCategory' + catId).append(
'<option value="' + categories[i].id + '">' +
categories[i].name + '</option>'
)
}
});
});
});
When I click the "Add Category" button one select tag added to the div by id="divCategory", but problem is that when I click "Create New Brand" button, I don't get data from these selects in server, actually CatBrands is null but I got name. I get something like that:
{name = "LG", catBrands = null}
CatBrands is null because you can't dynamically add data from the server in this manner. When the page renders, you need everything you want rendered by asp in the html.
<form method="post" enctype="multipart/form-data">
<div>
<label>Brand Name:</label>
<input type="text" asp-for="#Model.Name">
</div>
<div id="divCategory">
<select id="selectCategory asp-code-goes-here>
<option>---Select---</option>
</select>
</div>
<button type="button" id="btnAddCategory">Add Category</button>
<button>Create new Brand</button>
</form>
I've made a terible mistake. I should change my function like this
$(document).ready(function () {
$('#btnAddCategory').on('click', function () {
var catId = countMyCategories();
$('#divCategory').append(
'<select id="selectCategory' + catId + '"
name = "CatBrands[' + catId + '].CatId" class="mt-3 form-control
form-control-sm">' +
'<option>---Select---</option>' +
'</select>'
);
$.ajax('/API/GetCats')
.done(function (categories) {
for (var i = 0; i < categories.length; i++) {
$('#selectCategory' + catId).append(
'<option value="' + categories[i].id + '">' +
categories[i].name + '</option>'
)
}
});
});
});

Categories