How can i store at a time 3 value same textbox? - javascript

<script type="text/javascript">
document.getElementById("subcategory").addEventListener("change", function() {
console.log(this.value);
});
$(function(){
$('.categoryList').click(function(){
console.log($(this).attr("name"));
var cat_id = event.target.value;
var url = "http://localhost:8000/api/getSubcategory/"+cat_id;
$.ajax({
type: "GET",
url: url,
dataType: "JSON",
success: function(res)
{
var html = "";
$.each(res, function (key, value) {
html += "<li class="+'subcategorys'+" value="+key+" name="+value+">"+value+" </li>";
});
$('#subcategory').html($(html).addClass('subcategoryList'));
$('.subcategorys').on('click', function(event) {
console.log($(this).attr("name"));
var subcat_id =event.target.value;
console.log(subcat_id);
});
}
});
});
});
$(document).ready(function() {
$('#subcategory').on('click', function(event) {
var subcat_id =event.target.value;
console.log(subcat_id);
var url = "/api/getSubcategorytwo/"+subcat_id;
$.ajax({
type: "GET",
url: url,
dataType: "JSON",
success: function(res)
{
var html = "";
$.each(res, function (key, value) {
html += "<li value="+key+">"+value+"</option></li>";
});
$("#subcategorytwo").html(html);
}
});
});
$('#subcategorytwo').on('click', function(event) {
var opt_subcat_two =event.target.value;
var opt = $(event.target).text();
console.log(opt,opt_subcat_two);
$( "#fetchvalue" ).replaceWith("<input type='text' class='form-control' name='subcategorytwo' value="+opt_subcat_two+" id='fetchvalue' data-toggle='modal' data-target='#myModal'> "+opt+"</input>");
$('#myModal').modal('hide');
$('.modal-backdrop').remove();
});
});
</script>
<input type="text" class="form-control" name="subcategorytwo" id="fetchvalue" data-toggle="modal" data-target="#myModal" ></input>
<!-- The Modal -->
<div class="modal" id="myModal">
<div class="modal-dialog modal-lg" >
<div class="modal-content">
<!-- Modal Header -->
<div class="modal-header">
<a type="button" class="close" data-dismiss="modal" aria-hidden="true">×</a>
</div>
<div class="modal-body">
<div class="row">
<table class="table table-striped">
<thead>
</thead>
<tbody class="table">
<tr>
<td style="background-color: green">
<div class="col-md-7" >
#foreach($categories as $category)
<option class="categoryList" name="{{$category->category}}" value="{{$category->id}}">{{$category->category}}</option>
#endforeach
</div>
</td>
<td>
<div class="col-md-7">
<ul style="list-style: none" id="subcategory"></ul>
</div>
</td>
<td>
<div class="col-md-7">
<ul style="list-style: none" name="subcategorytwo" id="subcategorytwo" ></ul>
</div>
</td>
</tr>
</tbody>
</table>
</div>
</div>
</div>
</div>
</div>
</div>
Here is javascript code and modal code...I have total 4 table...
category subcategory
subcategory
subcategorytwo
post table
all are connected to a foreign key
Post table structure
When try to save category value, subcategory value, subcategorytwo value error is
How can I store 3 value at a time different place in db
Modal show like this
Modal like this

MySQL is most likely in STRICT mode try to
change the column to allow null:
ALTER TABLE `posts` CHANGE `subcategory2` `subcategory2` varchar NULL
Or try running
SET GLOBAL sql_mode='' or

Related

Submit through a Partial view

I have a Partial View as a Table, that will be refreshed with a Dropdown Selection in the Main View. This dropdown list includes company names. In the table below information matters pertaining to each company, and for each line of this information there is a drop-down list of all the functions that I can do with this line (like deleting or modifying the information) with a Pop-up Modal.
How can I call a Method in the main Model or Submit something? Or can I create a Partial View with Model in my Case?
Here is my Main View:
#page
#model Fachinformationsdienst_Kundenportal.Pages.Information_listModel
#{
}
<form>
<div class="form-row align-items-center">
<div class="form-group col-md-4">
<label for="inputState">Wählen Sie eine Unternehmen aus</label>
<select id="inputState" class="form-control">
#for (int i = 0; i < Model.companies.Count; i++)
{
<option>#Model.companies[i].FirmenKurzBezeichnung</option>
}
</select>
</div>
<div class="form-group col-md-6">
<input class="form-control" id="myInput" type="text" style="margin-top: 31px;" placeholder="Suche...">
</div>
<div class="form-group col-md-2">
<button type="button" class="btn btn-primary" style="margin-top: 31px;">
<i class="fas fa-plus"></i>
</button>
</div>
</div>
</form>
<div id="fachinfoContainer">
<partial name="_FachinfoPartial" model="#Model.myViewModel" />
</div>
#section Scripts{
<script type="text/javascript">
$(function () {
$("#inputState").change(function () {
var selectcompany = "";
if ($(this).val() != "Wählen Sie die Firma aus...") {
selectcompany = $(this).val();
}
$.ajax({
url: "/Actions/Information-List?handler=fachinfoPartial",
type: "Get",
data: { company: selectcompany },
success: function (result) {
$("#fachinfoContainer").html(""); //clear the fachinfo container.
$("#fachinfoContainer").html(result); //populate the container.
},
error: function (result) {
alert(result);
}
});
});
});
</script>
}
Here is my Partial View
#model Fachinformationsdienst_Kundenportal.Models.MyViewModel
<table class="table table-striped" id="FachinfoTable">
<thead>
<tr>
<th scope="col">Nr.</th>
<th scope="col">Name</th>
<th scope="col">Status</th>
<th scope="col">Letzte Änderung</th>
<th scope="col">Aktuelle Version</th>
<th scope="col">Auftrag</th>
</tr>
</thead>
<tbody id="myTable">
#if (#Model.Fachinfos != null)
{
#for (int i = 0; i < #Model.Fachinfos.Count; i++)
{
<tr>
<th scope="row">#Model.Fachinfos[i].FachinfoNummer</th>
<td>#Model.Fachinfos[i].FachinfoName</td>
<td>#Model.Fachinfos[i].Status</td>
<td>#Model.Fachinfos[i].Datum</td>
<td>#Model.Fachinfos[i].PdfVersion</td>
<td>
<div class="dropdown">
<button type="button" class="btn btn-primary dropdown-toggle" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">
<span class="caret"></span>
</button>
<div class="dropdown-menu" aria-labelledby="dropdownMenuButton">
#for (int c = 0; c < #Model.SelectedCompany.Permissions.Count; c++)
{
if (Model.SelectedCompany.Permissions[c] != Models.Company.Permission.ERSTERFASSEN && Model.SelectedCompany.Permissions[c] != Models.Company.Permission.ABFRAGEN)
{
<a class="dropdown-item" data-toggle="modal" data-number="#Model.Fachinfos[i].FachinfoNummer" data-version="#Model.Fachinfos[i].PdfVersion" data-target="##Model.SelectedCompany.Permissions[c]">#Model.SelectedCompany.Permissions[c]</a>
}
}
</div>
</div>
</td>
</tr>
}
}
</tbody>
</table>
<!-- The Delete Modal -->
<div class="modal fade" id="#Models.Company.Permission.LOESCHEN">
<div class="modal-dialog modal-lg">
<div class="modal-content">
<!-- Modal Header -->
<div class="modal-header">
<h4 class="modal-title">Bestätigen</h4>
<button type="button" class="close" data-dismiss="modal">×</button>
</div>
<!-- Modal body -->
<div class="modal-body">
<span id="deletMessege">Sind Sie sicher, dass Sie diese Fachinformation löschen möchten?</span>
</div>
<!-- Modal footer -->
<div class="modal-footer">
<button id="confirm" type="submit" class="btn btn-primary">Senden</button>
</div>
</div>
</div>
</div>
<script>
$('##Models.Company.Permission.LOESCHEN').on('show.bs.modal', function (event) {
var button = $(event.relatedTarget) // Button that triggered the modal
var fiNumber = button.data('number') // Extract info from data-* attributes
var modal = $(this)
modal.find('.modal-title').text('Fachinfonummer ' + fiNumber)
})
</script>
Here is my main model
using Fachinformationsdienst_Kundenportal.Classes;
using Fachinformationsdienst_Kundenportal.Models;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.RazorPages;
using System.Collections.Generic;
namespace Fachinformationsdienst_Kundenportal.Pages
{
public class Information_listModel : PageModel
{
public List<Company> companies { get; set; }
public List<Fachinfo> fachinfos = new List<Fachinfo>();
public MyViewModel myViewModel = new MyViewModel();
public void OnGet()
{
companies = APIRequester.GetCompanies(User.Identity.Name);
foreach (var company in companies)
{
fachinfos.AddRange(APIRequester.GetFachinfos(company.FirmenKurzBezeichnung));
}
}
public PartialViewResult OnGetFachinfoPartial(string company)
{
//based on the selctedcompany to filter data, then return to the partial view.
companies = APIRequester.GetCompanies(User.Identity.Name);
myViewModel = new MyViewModel()
{
SelectedCompany = companies.Find(r => r.FirmenKurzBezeichnung == company), //get the company object here
Fachinfos = APIRequester.GetFachinfos(company)
};
return Partial("_FachinfoPartial", myViewModel);
}
//Submit this Method from Partial view
public IActionResult onDelete(string fiNumber)
{
return Page();
}
}
}
You can use JQUERY AJAX calls for this
$.ajax({
type: "POST",
url: '/Information_listModel?handler=Ondelete',
contentType: "application/json; charset=utf-8",
dataType: "json"
}).done(function (data) {
console.log(data.result);
})
your method should return type IActionResult

Select gets double options after submit form modal

I got a problem with a bootstrap modal form and dynamic select options.
When I open the modal, there is an input and two select options.
One select is populating the second after a user check an option from
the first select.
On the first load, the select options are working ok.
When I submit the form (with Save button) and I reopen the modal, the first select gets the correct options but the second got double options.
When I reload the page everything gets back to normal until I submit the form again.
$(document).ready(function () {
var table = $('table.setting-groups');
var table_permissions = $('table.settings-groups-permissions');
var table_permissions_edit = $('table.settings-groups-permissions-edit');
var permissions = [];
var dataArray = [];
$('#addGroupModal').on('shown.bs.modal', function (e) {
$('select#permission_category').each(function () {
var $select = $(this);
$select.empty().append('<option></option>');
$.ajax({
url: $select.attr('data-source')
}).then(function (options) {
options.map(function (option) {
var $option = $('<option>');
$option
.val(option[$select.attr('data-valueKey')])
.text(option[$select.attr('data-displayKey')]);
$select.append($option);
});
});
});
$('select#permission_category').change(function () {
var category = $('select#permission_category').val();
if (category !== '') {
$('select#permission_category_description').each(function () {
var $select = $(this);
$select.empty().append('<option></option>');
$.ajax({
url: $select.attr('data-source'),
data: {category: category}
}).then(function (options) {
options.map(function (option) {
var $option = $('<option>');
$option
.val(option[$select.attr('data-valueKey')])
.text(option[$select.attr('data-displayKey')]);
$select.append($option);
});
});
});
} else {
$('select#permission_category_description')[0].empty();
}
});
$('select#permission_category_description').change(function () {
var category = $('select#permission_category').val();
var description = $('select#permission_category_description').val();
var check = $.inArray(description, permissions) > -1;
if (!check) {
permissions.push(description);
table_permissions.DataTable().row.add({
"category": category,
"description": description
}).draw();
}
});
// Save permissions
$('form#add-group').submit(function (e) {
$('#savebtn').button('loading');
e.preventDefault();
var form = $(this);
// Push table data (permissions) to form for submit
$('<input>').attr({
type: 'hidden',
id: 'permissions',
name: 'permissions',
value: permissions
}).appendTo(form);
$.ajax({
url: form.attr('action'),
type: form.attr('method'),
data: new FormData(this),
dataType: 'json',
processData: false,
contentType: false,
success: function (data) {
$('#addGroupModal').modal('toggle');
swal(
'Επιβεβαίωση Καταχώριση',
'Η ομάδα δικαιωμάτων καταχωρήθηκε επιτυχώς',
'success'
).then(function () {
permissions = [];
dataArray = [];
form[0].reset();
$('select#permission_category_description').empty();
table_permissions.DataTable().destroy();
table.DataTable().ajax.reload();
});
},
error: function (data) {
swal(
'Αποτυχία Καταχώρισης',
data.responseText,
'error'
)
}
});
});
// Remove row when you click X
table_permissions.on('click', '.delete', function () {
table_permissions.DataTable().row('.selected').remove().draw(false);
});
});
$('#addGroupModal').on('hide.bs.modal', function (e) {
// Clean forms / select / datatables / arrays on modal close
$('select#permission_category_description').empty();
$('form')[0].reset();
table_permissions.DataTable().destroy();
permissions = [];
dataArray = [];
});
$('#editGroupModal').on('shown.bs.modal', function (e) {
var id = $(e.relatedTarget).data('id');
$.post('../../custom/json/groups.php?view', {id: id}, function (arr) {
$('input#group_name').val(arr.description);
// Get existing permissions from groups
dataArray = arr.data.map(function (value) {
return value.description;
});
});
$('select#permission_category_edit').each(function () {
var $select = $(this);
$select.empty().append('<option></option>');
$.ajax({
url: $select.attr('data-source')
}).then(function (options) {
options.map(function (option) {
var $option = $('<option>');
$option
.val(option[$select.attr('data-valueKey')])
.text(option[$select.attr('data-displayKey')]);
$select.append($option);
});
});
});
$('select#permission_category_edit').change(function () {
var category = $('select#permission_category_edit').val();
if (category !== '') {
$('select#permission_category_description_edit').each(function () {
var $select = $(this);
$select.empty().append('<option></option>');
$.ajax({
url: $select.attr('data-source'),
data: {category: category}
}).then(function (options) {
options.map(function (option) {
var $option = $('<option>');
$option
.val(option[$select.attr('data-valueKey')])
.text(option[$select.attr('data-displayKey')]);
$select.append($option);
});
});
});
} else {
$('select#permission_category_description_edit')[0].empty();
}
});
$('select#permission_category_description_edit').change(function () {
var category = $('select#permission_category_edit').val();
var description = $('select#permission_category_description_edit').val();
permissions = dataArray;
var check = $.inArray(description, permissions) > -1;
if (!check) {
permissions.push(description);
table_permissions_edit.DataTable().row.add({
"category": category,
"description": description
}).draw();
}
});
var settingGroupsPermissionsEdit = {
"destroy": true,
"processing": true,
"deferRender": true,
"responsive": true,
"select": true ,
"searching": false,
"paging": false,
"info": false,
"ordering": false,
"language": {
"url": "/custom/js/data-tables/Greek.json"
},
"ajax": "../../custom/json/groups.php?view&id=" + id,
"dataSrc": "data",
"columns": [
{data: "category", className: "text-center"},
{data: "description", className: "text-center"},
{
data: null, className: "text-center btn-actions", render: function (data, type, row) {
return '<a data-id="' + data.description + '" class="danger p-0 delete"><i class="ft-x font-medium-3 mr-2"></i></a>';
}
}
]
};
$('table.settings-groups-permissions-edit').DataTable($.extend(true, {}, settingGroupsPermissionsEdit, {}));
// Save permissions
$('form#edit-group').submit(function (e) {
$('#editbtn').button('loading');
e.preventDefault();
var form = $(this);
// Push table data (permissions) to form for submit
$('<input>').attr({
type: 'hidden',
id: 'permissions',
name: 'permissions',
value: permissions
}).appendTo(form);
$.ajax({
url: form.attr('action') + '&id=' + id,
type: form.attr('method'),
data: new FormData(this),
dataType: 'json',
processData: false,
contentType: false,
success: function (data) {
$('#editGroupModal').modal('toggle');
swal(
'Επιβεβαίωση Ενημέρωσης',
'Η ομάδα δικαιωμάτων ενημερώθηκε επιτυχώς',
'success'
).then(function () {
permissions = [];
dataArray = [];
form[0].reset();
$('select#permission_category_description_edit').empty();
table_permissions_edit.DataTable().destroy();
table.DataTable().ajax.reload();
});
},
error: function (data) {
swal(
'Αποτυχία Ενημέρωσης',
data.responseText,
'error'
)
}
});
});
// Remove row when you click X
table_permissions_edit.on('click', '.delete', function () {
var row_desc = table_permissions_edit.DataTable().rows('.selected').data().pluck('description')[0];
permissions = remove(permissions, row_desc); // remove element from posted permissions array
table_permissions_edit.DataTable().row('.selected').remove().draw();
});
});
$('#editGroupModal').on('hide.bs.modal', function (e) {
// Clean forms / select / datatables / arrays on modal close
$('select#permission_category_description_edit').empty();
$('form')[0].reset();
table_permissions_edit.DataTable().destroy();
permissions = [];
dataArray = [];
});
// Delete group
table.on('click', '.swal-delete', function () {
var id = $(this).data('id');
swal({
title: 'Διαγραφή',
text: 'Είστε σίγουρος/η οτι θέλετε να διαγράψετε την ομάδα δικαιωμάτων;',
type: 'warning',
showCancelButton: true,
confirmButtonColor: '#0CC27E',
cancelButtonColor: '#FF586B',
confirmButtonText: 'Ναι',
cancelButtonText: 'Όχι'
}).then(function (isConfirm) {
if (isConfirm) {
$.post("../../custom/json/groups.php?delete", {id: id}, function (data) {
swal(
'Επιβεβαίωση Διαγραφής',
'Η ομάδα δικαιωμάτων διαγράφηκε επιτυχώς',
'success'
).then(function () {
table.DataTable().ajax.reload();
});
});
}
}).catch(swal.noop);
});
// Remove element from an array
function remove(array, value) {
return array.filter(function (element) {
return element !== value;
});
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<!-- BEGIN ADD GROUP MODAL-->
<div class="modal fade text-left" id="addGroupModal" role="dialog" aria-labelledby="addGroupModal" style="display: none;" aria-hidden="true">
<div class="modal-dialog modal-lg" role="document">
<div class="modal-content">
<form id="add-group" action="/custom/json/groups.php?add" method="post" class="form form-horizontal" autocomplete="off" enctype="multipart/form-data">
<div class="modal-header bg-medi white">
<h4 class="modal-title" id="addGroupModal"><i class="ft-list font-medium-3 mr-2"></i> Προσθήκη Νέας Ομάδας</h4>
</div>
<div class="modal-body mt-1">
<fieldset class="form-group floating-label-form-group row">
<label class="col-md-4 label-control mt-1" for="group_name">Όνομα Ομάδας: </label>
<div class="col-md-5">
<input type="text" id="group_name" class="form-control" name="group_name">
</div>
</fieldset>
<fieldset class="form-group floating-label-form-group row">
<label class="col-md-4 label-control" for="permission_category">Κατηγορία</label>
<div class="col-md-5">
<select id="permission_category" name="permission_category" class="form-control"
data-source="/custom/json/groups.php?permission-category"
data-valueKey="category"
data-displayKey="category">
</select>
</div>
</fieldset>
<fieldset class="form-group floating-label-form-group row">
<label class="col-md-4 label-control" for="permission_category_description">Πρόσβαση</label>
<div class="col-md-5">
<select id="permission_category_description" name="permission_category_description" class="form-control"
data-source="/custom/json/groups.php?permission-description"
data-valueKey="description"
data-displayKey="description">
</select>
</div>
</fieldset>
<div class="table-responsive">
<table class="table table-condensed table-bordered table-sm base-style table-hover full-width settings-groups-permissions">
<thead class="bg-medi text-white text-center">
<tr>
<th>Κατηγορία</th>
<th>Πρόσβαση</th>
<th></th>
</tr>
</thead>
</table>
</div>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-secondary" data-dismiss="modal">Κλείσιμο</button>
<button type="submit" class="btn btn-medi white" id="savebtn" data-loading-text="Αποθήκευση...">Αποθήκευση</button>
</div>
</form>
</div>
</div>
</div>
<!-- END ADD GROUP MODAL-->
<!-- BEGIN EDIT GROUP MODAL-->
<div class="modal fade text-left" id="editGroupModal" role="dialog" aria-labelledby="editGroupModal" style="display: none;" aria-hidden="true">
<div class="modal-dialog modal-lg" role="document">
<div class="modal-content">
<form id="edit-group" action="/custom/json/groups.php?edit" method="post" class="form form-horizontal" autocomplete="off" enctype="multipart/form-data">
<div class="modal-header bg-medi white">
<h4 class="modal-title" id="editGroupModal"><i class="ft-list font-medium-3 mr-2"></i> Επεξεργασία Ομάδας</h4>
</div>
<div class="modal-body mt-1">
<fieldset class="form-group floating-label-form-group row">
<label class="col-md-4 label-control mt-1" for="group_name">Όνομα Ομάδας: </label>
<div class="col-md-5">
<input type="text" id="group_name" class="form-control" name="group_name" disabled>
</div>
</fieldset>
<fieldset class="form-group floating-label-form-group row">
<label class="col-md-4 label-control" for="permission_category_edit">Κατηγορία</label>
<div class="col-md-5">
<select id="permission_category_edit" name="permission_category" class="form-control"
data-source="/custom/json/groups.php?permission-category"
data-valueKey="category"
data-displayKey="category">
</select>
</div>
</fieldset>
<fieldset class="form-group floating-label-form-group row">
<label class="col-md-4 label-control" for="permission_category_description_edit">Πρόσβαση</label>
<div class="col-md-5">
<select id="permission_category_description_edit" name="permission_category_description" class="form-control"
data-source="/custom/json/groups.php?permission-description"
data-valueKey="description"
data-displayKey="description">
</select>
</div>
</fieldset>
<div class="table-responsive">
<table class="table table-condensed table-bordered table-sm base-style table-hover full-width settings-groups-permissions-edit">
<thead class="bg-medi text-white text-center">
<tr>
<th>Κατηγορία</th>
<th>Πρόσβαση</th>
<th></th>
</tr>
</thead>
</table>
</div>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-secondary" data-dismiss="modal">Κλείσιμο</button>
<button type="submit" class="btn btn-medi white" id="editbtn" data-loading-text="Αποθήκευση...">Αποθήκευση</button>
</div>
</form>
</div>
</div>
</div>
<!-- END EDIT GROUP MODAL-->
Any suggestions ? I can't find where is the issue that causes js to run twice on select populate options.
Thank you in advance
UPDATE: The 2nd select option is doubled on modal show not on form submit.
Because you bind $('select#permission_category').change inside $('#addGroupModal').on('shown.bs.modal' handler so each time your modal show, it will bind $('select#permission_category').change another time. That's why when you open the modal second time, the 2nd select option is doubled and will be tripled on third time...
You can solve it by:
Option 1: Move $('select#permission_category').change to be outside of $('#addGroupModal').on('shown.bs.modal' handler.
Option 2: Remove $('select#permission_category') change handler using .off() when closing modal or before bind it in $('#addGroupModal').on('shown.bs.modal' handler.
Option 3: Create all options first then use .html() instead of .append() to set the html contents of select (this still bind change multiple time but the options is not multipled)

Transferring data from the js script to the controller

In the view (Index.cshtml) I have a button, when I click on that, the script that in the selectedItems writes the data is triggered. how are selectedItems transferred to the controller?
Button:
<form method="post" asp-action="Delete">
<button type="submit" onclick="SelectedCheckbox()" class="btn-group col-md-2 col-md-offset-0">Remove</button>
</form>
JS:
function SelectedCheckbox() {
var selectedItems = new Array();
$("input[id='check']:checked").each(function () { selectedItems.push($(this).val()); });
}
Controller (Users):
[HttpPost]
public async Task<ActionResult> Delete(string[] selectedUsers)
{
...
return RedirectToAction("Index");
}
I tried to use ajax, but something does not work out:
function SelectedCheckbox()
{
$.ajax({
url: "/Users",
contentType: "application/json",
method: "POST",
data: { parameters: parameters },
success: function (data) {
var data = new Array();
$("input[id='check']:checked").each(function () { data.push($(this).val()); });
alert(data.result);
},
error: function (data) { alert(data.responseText); }
})
}
#model IEnumerable<Task1.Models.User>
#{
ViewBag.Title = "Список пользователей";
}
<script src="//code.jquery.com/jquery-1.11.3.min.js"></script>
<div class="btn-toolbar nl container col-md-12" role="toolbar" aria-label="Menu">
<form method="post" asp-action="Delete">
<button type="submit" onclick="SelectedCheckbox()" name="delete" id="delete" class="btn-group col-md-2 col-md-offset-0">Remove</button>
</form>
<form method="post" asp-controller="Account" asp-action="LogOff">
<button type="submit" class="col-md-2 col-md-offset-3 " role="group" aria-label="LogOff" />LogOff</button>
</form>
</div>
<form asp-action="Delete">
<div class="nl">
<table class="table table-striped table-bordered ">
<tbody class="table-responsive ">
<tr><th><input type="checkbox" class="all" data-id="d1" title="Выбрать все"></th><th>Login</th><th>Date of registration</th><th>Date Last Login</th><th>Block disabled</th></tr>
#foreach (var user in Model)
{
<tr>
<td>
<input type="checkbox" name="selectedUsers"
id="#user.Id" value="#user.Id"
class="styled">
</td>
<td>#user.UserName</td>
<td>#user.DateOfRegistration</td>
<td>#user.DateLastLogin</td>
<td>#user.LockoutEnabled</td>
</tr>
}
</tbody>
</table>
</div>
</form>
<script type="text/javascript">
function SelectedCheckbox() {
var selectedItems = new Array();
$("input[id='check']:checked").each(function () { selectedItems.push($(this).val()); });
alert(selectedItems);
return (selectedItems);
}
</script>
I need to pass the value of the selected Item from the script in the method of removing the controller

jQuery autocomplete() submits form, but no values have been sent

I have a page with one with one link "COUNTRY", by hitting this link, under it appear some other links, which are group of countries. There is also one of the links called "Individual", by hitting that link appears one autocomplete field, where the user can start typing and choose one country.
I want by choosing the country to change some of the hidden fields values and than to submit the form.
The form submission works, but unfortunately there are no POST fields sent.
Here is the HTML & JS code:
<form method="POST" action="" accept-charset="UTF-8" id="news_search_form">
<input name="_token" type="hidden" value="tAB6ZU6sNafRUNBLiPyhiuCbEDQVGD4waxNbT3Yk">
<div class="row threelinks">
<div class="col-xs-12 col-sm-12 col-md-3">
<a href="javascript:;" class="btn_filter_category" data-href="country">
<div class="links_new link_hover">COUNTRY</div>
</a>
<input type="hidden" id="select_country" name="select_country" value="214">
<input type="hidden" id="filter_country" name="filter_country" value="0">
</div>
</div>
<div class="row " style="margin-top: 5px; display: none;" id="country_filters">
<div class="col-md-12">
<div class="owl-carousel col-md-12">
<div class="item">
<div class="top_sub_link">
Top 4
</div>
</div>
<div class="item">
<div class="top_sub_link">
EU
</div>
</div>
<div class="item">
<div class="top_sub_link">
Top 8
</div>
</div>
<div class="item">
<div class="top_sub_link">
Non EU
</div>
</div>
<div class="item">
<div class="top_sub_link">
Individual <i class="fa fa-pencil"></i>
<input type="text" class="form-control input-lg" id="individual_country" name="individual_country" style="font-size: 11px; text-align: center; display: none;"/>
<div id="no-result" style="display: none;">No results found</div>
</div>
</div>
<div class="item">
<div class="top_sub_link">
Reset
</div>
</div>
<div class="owl-nav"></div>
</div>
</div>
</div>
</form>
<script>
var filters = ['country'];
$(document).ready(function() {
$('a.btn_filter_category').on('click', function() {
var filter = $(this).attr('data-href');
show_filter(filter + '_filters');
unselect_filters();
$(this).find('.links_new.link_hover').removeClass('link_hover').addClass('link_hover_selected');
});
$(".filter_link").on('click', function() {
var filter = $(this).attr('data-href');
var value = $(this).attr('data-value');
$('#filter_' + filter).val(value);
$('#select_' + filter).val(0);
$("#news_search_form").submit();
});
$(".individual_link").on('click', function() {
var filter = $(this).attr('data-href');
$(this).remove();
$('#individual_' + filter).show();
});
});
$(function () {
var filter = 'country';
var url = "{{ url('country/search/'.$lang) }}";
$("#individual_" + filter).autocomplete({
source: function(request, response) {
$.ajax({
url: url,
dataType: "json",
type: "GET",
data: {
name: request.term
},
success: function(data){
response( $.map( data, function( item ) {
// alert(item.label);
return {
label: item.name,
value: item.value // EDIT
}
}));
}
})
},
select: function(event, ui) {
$('#filter_' + filter).val(0);
$('#select_' + filter).val(ui.item.value);
$("#news_search_form").submit();
}
});
});
function unselect_filters() {
$('div.links_new').each(function(i, obj) {
$(this).removeClass('link_hover').removeClass('link_hover_selected').addClass('link_hover');
});
}
function show_filter(selected_class) {
var arrayLength = filters.length;
for (var i = 0; i < arrayLength; i++) {
var class_name = filters[i] + '_filters';
if(selected_class != class_name) $('#'+ class_name).hide();
else $('#'+ class_name).show();
}
}
function reset_filter(filter) {
$('#filter_' + filter).val(0);
$('#select_' + filter).val(0);
$("#news_search_form").submit();
}
</script>
i found the solution.
The autocomplete submit form is working fine. Unfortunately there was some redirect after the submit, which was causing and empty POST array.

Using ajax to check radiobutton by Id in ASP.Net MVC

I saw a code that checks the radio button by value, but how do I do this by id? My current scenario is that I'm populating a table by appending html codes using ajax. I'm looping the prices of a certain item while building the html table. After that, I need to check the radio button of a price where default flag is equal to 'Y'.
Here's my if statement that checks the radiobutton by value only, this is not working yet as my radiobutton values are null, only the id and name has value:
if (item.defaultflag == 'Y')
$('#divItemPrice').find(':radio[name=rbDefaultPrice][value="iPrice_' + item.channelid + '"]').prop('checked', true);
else
$('#divItemPrice').find(':radio[name=rbDefaultPrice][value="iPrice_' + item.channelid + '"]').prop('checked', false);
Complete code:
$.ajax({
url: '/Item/RetrievePrice',
type: 'POST',
dataType: 'json',
data: JSON.stringify(json),
contentType: 'application/json; charset=utf-8',
cache: false,
async: true,
success: function (data) {
var trHTML = "";
debugger;
trHTML = '<tbody id="dbBody2">';
$.each(data, function (i, item) {
trHTML += '<tr><td class="hidden">' + item.itemid + '</td>' +
'<td style="width:20px"><label><input type="radio" name="rbDefaultPrice" id = "iPrice_' + item.itemid + '" /></label></td>' +
'<td>' + item.itemprice + '</td>' +
'<td>' + ToJavaScriptDate(item.startdate) + '</td>' +
'<td>' + ToJavaScriptDate(item.enddate) + '</td>' +
'</tr>';
//How do I check the radiobutton by id?
if (item.defaultflag == 'Y')
$('#divItemPrice').find(':radio[name=rbDefaultPrice][value="iPrice_' + item.itemid + '"]').prop('checked', true);
else
$('#divItemPrice').find(':radio[name=rbDefaultPrice][value="iPrice_' + item.itemid + '"]').prop('checked', false);
});
trHTML += '</tbody>';
$("#tblItemPrice tbody").remove();
$('#tblItemPrice').append(trHTML);
},
error: function (xhr, ajaxOptions, thrownError) {
alert("Error! " + xhr.status);
}
});
View (modal part)
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal">×</button>
<h4 class="modal-title">Modal Header</h4>
</div>
<div class="modal-body">
<div id="divItemPrice" class="" style="border: 0px solid green; ">
<table id="tblItemPrice" onclick="gettabledata('tblItemPrice', '0,2,3,4', 'itemPriceId,itemPrice,strtDt,endDt')" class="table table-hover table-bordered table-striped bootgrid-table" aria-busy="false" padding-left:10px;">
<thead>
<tr class="inner-table-head">
<th class="hidden">
#Html.DisplayNameFor(model => model.itemPriceId)
</th>
<th>
Price
</th>
<th>
Start Date
</th>
<th>
End Date
</th>
</tr>
</thead>
<tbody id="bodyToAppend">
</tbody>
</table>
</div>
<div class="form-group">
<div class="row form-row">
<span class="form-item">
#Html.HiddenFor(m => m.itemPriceId)
#Html.LabelFor(m => m.itemPrice, new { #class = "lbl-width" })
#Html.TextBoxFor(m => m.itemPrice, new { #class = "form-control input-sm" })
</span>
</div>
<div class="row form-row">
<span class="form-item ">
#Html.LabelFor(m => m.strtDt, new { #class = "lbl-width" })
#Html.TextBoxFor(m => m.strtDt, new { #class = "form-control input-sm", #Value = "" })
</span>
</div>
<div class="row form-row">
<span class="form-item ">
#Html.LabelFor(m => m.endDt, new { #class = "lbl-width" })
#Html.TextBoxFor(m => m.endDt, new { #class = "form-control input-sm", #Value = "" })
</span>
</div>
<div class="row form-row maintenance-btn">
<div class="btn-group">
<input type="submit" id="btnSavePrice" value="Save" class="btn btn-theme btn-sm" formmethod="post" />
<input type="submit" id="btnUpdatePrice" value="Update" class="btn btn-theme btn-sm" formmethod="post" style="display:none" />
#*<input type="submit" id="btnCancelPrice" value="Cancel" class="btn btn-theme btn-sm" />*#
</div>
</div>
</div>
</div>
<div class="modal-footer">
<button id="closeModal" type="button" class="btn btn-default" data-dismiss="modal">Close</button>
</div>
</div>
The code in your if/else block cannot work because its attempting to .find() and element in the DOM which does not even exist yet (you have not added it). And even if you did add the <tr> to the DOM in each iteration it would result in poor performance (searching the whole table in each iteration).
A simple way to solve this (and much easier to debug the html your generating) is to create a hidden template that is cloned and added in each iteration. I also assume that you want to add the value of itemprice as the value attribute of the radio button so that you can get the value of the selected radio button using var price = $('input[name="rbDefaultPrice"]').val();
<table id="template" style="display:none;">
<tr>
<td>
<label>
<input type="radio" name="rbDefaultPrice" class="radio" />
<span class="price"></span>
</label>
</td>
<td class="startdate"></td>
<td class="enddate"></td>
</tr>
</table>
Then in the .each() loop, clone the template, update its values and append it to the DOM
var tbody = $('#tblItemPrice tbody');
....
success: function (data) {
tbody.empty() // remove existing rows
$.each(data, function (i, item) {
// clone the template row
var row = $('#template').clone().find('tr');
// update properties
var radio = row.find('.radio');
radio.val(item.itemprice);
if (item.defaultflag == 'Y') {
radio.prop('checked', true);
}
row.find('.price').text(item.itemprice);
row.find('.startdate').text(....
// add the row to the DOM
tbody.append(row);
});
}
Side note: Its not clear what your ToJavaScriptDate() function is doing, but I suggest you just pass the correctly formatted value to client so you can just use row.find('.startdate').text(item.startdate); etc

Categories