I have a html table in with razor and I want to send some data from the table to a controller via Javascript.
I tried several different solutions but the data never seems to reach my controller while alerts are being hit. The breakpoints in the controller are never being hit which indicates to me that the data can't reach the controller.
I want the value of #item.PartId and the value of checked to be send to the controller.
<div class="Table">
{
<table id="table1" class="table table-striped TableData">
#{var id = 0;}
#foreach (var item in Model.PieceViewItems)
{
id++;
<tr id="#id">
<td>#id</td>
<td><label>#item.PartDescription</label> <br /> #item.PartId (#item.StatusCode)</td>
<td>#item.Supplier</td>
<td style="width: 100px !important">
#item.TijdOpO3 #if (item.TijdOpO3 == "1")
{<text>dag</text>}
else
{ <text>dagen</text>}
</td>
<td>#item.KeurCode</td>
<td>#item.PromiseDate</td>
<td>#item.WidthAndPartType</td>
<td>
#item.PieceLengthWithUnit <br /> #item.NrOfPieces #if (item.NrOfPieces == 1)
{<text>rol</text> }
else
{ <text>rollen</text>}
</td>
<td>
#if (item.NumberReceived == "0")
{<text>NIEUW</text> }
else
{ #item.NumberReceived}
</td>
<td>#item.VoorraadQty m</td>
<td style="width: 100px !important">
#item.SalesOrderQty m <br /> #item.NrOfSalesOrders #if (item.NrOfSalesOrders == 1)
{<text>order</text>}
else
{<text>orders</text>}
</td>
<td style="width: 100px !important">
#item.StalenOrdersQty m <br /> #item.NrOfStalenOrders #if (item.NrOfStalenOrders == 1)
{<text>order</text>}
else
{<text>orders</text>}
</td>
<td><input type="checkbox" name="IsChecked" onclick="ClickHandle(this)" style="width:30px;height:30px;margin-left:20px;margin-top:20px"> </td>
</tr>
}
</table>
</div>
Javascript
<script type="text/javascript">
$(function ClickHandle() {
$("input[name='IsChecked']").change(function (element) {
var table = document.getElementById("table1");
for (var i = 1; i < table.rows.length; i++) {
var row = table.rows[i];
var lastorder = row.cells[12].firstChild;
var check = lastorder.checked;
if (check) {
var x = document.getElementById("table1").getElementsByTagName("tr");
x[i].style.backgroundColor = "yellow";
}
else {
var x = document.getElementById("table1").getElementsByTagName("tr");
x[i].style.backgroundColor = null;
}
//post item.partid and value of check to controller here.
}
});
});
</script>
Controller
[HttpPost]
public ActionResult PostIsChecked(string partId, string isChecked)
{
Part part = new Part
{
id = partId,
isChecked = isChecked
};
//Do stuff
receipt.UpdateCheckedStatus(part);
}
You can try to put a hidden input into <tr></tr>,and set its value with #item.PartId.Then use ajax to post data to action.Here is a demo:
<div class="Table">
{
<table id="table1" class="table table-striped TableData">
#{var id = 0;}
#foreach (var item in Model.PieceViewItems)
{
id++;
<tr id="#id">
<td>#id</td>
<td><label>#item.PartDescription</label> <br /><input hidden value=#item.PartId/> #item.PartId (#item.StatusCode)</td>
<td>#item.Supplier</td>
<td style="width: 100px !important">
#item.TijdOpO3 #if (item.TijdOpO3 == "1")
{<text>dag</text>}
else
{ <text>dagen</text>}
</td>
<td>#item.KeurCode</td>
<td>#item.PromiseDate</td>
<td>#item.WidthAndPartType</td>
<td>
#item.PieceLengthWithUnit <br /> #item.NrOfPieces #if (item.NrOfPieces == 1)
{<text>rol</text> }
else
{ <text>rollen</text>}
</td>
<td>
#if (item.NumberReceived == "0")
{<text>NIEUW</text> }
else
{ #item.NumberReceived}
</td>
<td>#item.VoorraadQty m</td>
<td style="width: 100px !important">
#item.SalesOrderQty m <br /> #item.NrOfSalesOrders #if (item.NrOfSalesOrders == 1)
{<text>order</text>}
else
{<text>orders</text>}
</td>
<td style="width: 100px !important">
#item.StalenOrdersQty m <br /> #item.NrOfStalenOrders #if (item.NrOfStalenOrders == 1)
{<text>order</text>}
else
{<text>orders</text>}
</td>
<td><input type="checkbox" name="IsChecked" onclick="ClickHandle(this)" style="width:30px;height:30px;margin-left:20px;margin-top:20px"> </td>
</tr>
}
</table>
</div>
js:
$("input[name='IsChecked']").change(function () {
var checked = this.checked;
var PartId = $(this).parent().parent().find("input")[0].value;
$.ajax({
type: "POST",
url: "PostIsChecked",
data: { "isChecked": checked, "partId": PartId},
success: function (data) {
}
});
});
Related
This code below select only one by one checkbox, how can I transform this code so I can select all checkboxes by one click, but I need my variables to stay defined.
$('.checktip').click(function () {
var iduser = $('.iduser').val();
var idtip = $(this).attr('idtip');
var che = $(this).prop('checked');
$.ajax({
url: UrlSettingsDocument.OrgUnits,
data: { iduser: iduser, idtip: idtip, che: che },
type: "POST",
success: function (result) {
if (result.result == "Redirect") {
window.location = result.url;
}
}
});
});
I using this variables for controller where I save this values in database when I check them or unchecked.
Here is my html code
<input type="hidden" value="#ViewBag.iduser" id="iduser" />
<hr />
<table class="table table-striped grid-table">
<tr>
<th>Samp</th>
<th>Id of Book</th>
<th>
//Checkbox for check all *(NOT IMPLEMENTED)*
<input type="checkbox" id="box" name="checkAll" />
</th>
</tr>
#foreach (var item in (IEnumerable<cit.Models.getCheIdTip_Result>)Model)
{
<tr>
<td>#item.idtip</td>
<td>#item.tipname</td>
<td>
#*#Html.CheckBox(item.id.ToString(), item.iduser == ViewBag.iduser ? true : false, new { idtip = item.idtip, #class = "checktip" })*#
<div class="pure-checkbox">
<input type="checkbox" idtip="#item.idtip" class="checktip" checked="#(item.iduser == ViewBag.iduser ? true : false)" name="#item.id.ToString()" id="#item.id.ToString()" />
<label for="#item.id.ToString()"></label>
</div>
</td>
</tr>
}
</table>
Following code should work with your code
$('#box').click(function(){ $('.checktip').prop('checked', true); }};
I am working on a phonebook. In html I have a div #containerAgenda which won't show if there are no added contacts. However, I created the function to delete a row or multiple rows. So if I add and then delete all contacts, I want the div to hide. I am not sure how to set the value to blank or empty so that I can apply the rule .classList.remove in the deleteRow function(I added the way I tried to define the input value as empty). Would you give me any hints? Below is my code:
P.S. I am quite a beginner so I appreciate non-complicated solutions :)
<script>
var persoane =[];
function deseneazaTabel(){
str = "";
for (var i = 0; i < persoane.length; i++){
str += `<tr>
<td>${persoane[i].name}</td>
<td>${persoane[i].telefon}</td>
<td><span class="editButton" onclick="editeaza();">EDIT</span></td>
<td><span class="deleteButton" onclick="deleteRow(${i});">STERGE</span></td>
</tr>`;
}
document.querySelector("table tbody").innerHTML=str;
}
var pers = {};
function adaugaContact(form,event){
event.preventDefault();
var inputs = form.querySelectorAll("input[name]");
for (var i=0; i<inputs.length; i++){
var a = inputs[i].getAttribute("name");
var v = inputs[i].value;
pers[a] = v;
}
persoane.push(pers);
document.querySelector("#containerAgenda").classList.remove("hidden");
deseneazaTabel();
}
function deleteRow (idx){
persoane.splice(idx,1);
if(document.querySelectorAll("input[name]").value === ""){
document.querySelector("#containerAgenda").classList.add("hidden");
}
deseneazaTabel();
}
</script>
<body onload="deseneazaTabel();">
<h1>AGENDA</h1>
<form class="orangeText centerText" onsubmit="adaugaContact(this,event);">
<label for ="name">Nume</label>
<input type="text" name="name" id="name">
<label for="telefon">Telefon</label>
<input type="text" name="telefon" id="telefon">
<br/>
<input type="submit" class="btn" value="ADAUGA CONTACT">
</form>
<div id="containerAgenda" class="orangeText centerText hidden">
<table id="inputs">
<thead>
<tr>
<td>Nume</td>
<td>Telefon</td>
<td></td>
<td></td>
</tr>
</thead>
<tbody>
</tbody>
</table>
</div>
</body>
</html>
What you need is if
(persoane.length === 0) {
document.getElementById('containerAgenda').style.display = 'none';
} else {
document.getElementById('containerAgenda').style.display = 'block';
}
inside deseneazaTabel function
I also added deleteAll functionality which was missing from your question please check demo
var persoane = [];
function deseneazaTabel() {
if (persoane.length === 0) {
document.getElementById('containerAgenda').style.display = 'none';
} else {
document.getElementById('containerAgenda').style.display = 'block';
}
str = "";
for (var i = 0; i < persoane.length; i++) {
str += `<tr>
<td>${persoane[i].name}</td>
<td>${persoane[i].telefon}</td>
<td><span class="editButton" onclick="editeaza();">EDIT</span></td>
<td><span class="deleteButton" onclick="deleteRow(${i});">STERGE</span></td>
</tr>`;
}
document.querySelector("table tbody").innerHTML = str;
}
function DeleteALL() {
persoane = [];
deseneazaTabel();
}
var pers = {};
function adaugaContact(form, event) {
event.preventDefault();
var inputs = form.querySelectorAll("input[name]");
for (var i = 0; i < inputs.length; i++) {
var a = inputs[i].getAttribute("name");
var v = inputs[i].value;
pers[a] = v;
}
persoane.push(pers);
document.querySelector("#containerAgenda").classList.remove("hidden");
deseneazaTabel();
}
function deleteRow(idx) {
persoane.splice(idx, 1);
if (document.querySelectorAll("input[name]").value === "") {
document.querySelector("#containerAgenda").classList.add("hidden");
}
deseneazaTabel();
}
<body onload="deseneazaTabel();">
<h1>AGENDA</h1>
<form class="orangeText centerText" onsubmit="adaugaContact(this,event);">
<label for="name">Nume</label>
<input type="text" name="name" id="name">
<label for="telefon">Telefon</label>
<input type="text" name="telefon" id="telefon">
<br/>
<input type="submit" class="btn" value="ADAUGA CONTACT">
</form>
<input type="submit" class="btn" onClick="DeleteALL()" value="Delete ALL">
<div id="containerAgenda" class="orangeText centerText hidden">
<table id="inputs">
<thead>
<tr>
<td>Nume</td>
<td>Telefon</td>
<td></td>
<td></td>
</tr>
</thead>
<tbody>
</tbody>
</table>
</div>
</body>
</html>
This can help you
function checkIfNoContact() {
if(document.querySelectorAll("tr").length <= 0 ) {
document.querySelector("#containerAgenda").classList.add("hidden");
} else {
document.querySelector("#containerAgenda").classList.remove("hidden");
}
}
You can Use jQuery
It will check if there wasn't any <tr> in <tbody>, then hides div#containerAgenda
I hope it works for you.
if ( $("#containerAgenda tbody").children().length == 0 ) {
$("#containerAgenda").hide();
}
I've a HTML datatable I'm filling data to datatable using knockout js using 'foreach'. Here is my code.
<html>
<head>
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title></title>
<link rel="stylesheet" href="https://cdn.datatables.net/1.10.12 /css/jquery.dataTables.min.css" />
<script src="~/Scripts/jquery-1.7.1.js"></script>
<script src="~/Scripts/knockout-3.4.0.js"></script>
<script src="~/Scripts/knockout.mapping-latest.js"></script>
<script src="https://cdn.datatables.net/1.10.12/js/jquery.dataTables.min.js"></script>
</head>
<body>
<div id="dvMain">
<table style="width: 300%">
<tr>
<td>
<table id="tblmain">
<tr id="trCategory" data-bind="visible: flagCategory">
<td>
<table>
<tr id="InsertUpdateCategory" data-bind="visible: flagInsertCategory">
<td>
<table>
<tr>
<td>Category Name : </td>
<td>
<input type="text" id="txtCategoryName" maxlength="100" data-bind="value: txtCategoryName" />
</td>
</tr>
<tr>
<td>Is Active : </td>
<td>
<input type="checkbox" id="chkIsActiveCategory" data-bind="checked: chkCategoryActive" />
</td>
</tr>
<tr>
<td></td>
<td>
<button id="btnSaveCategory" data-bind="click: SaveCategory">Save</button>
<input type="hidden" id="hdnCategoryId" />
<button id="btnCancelCategory" data-bind="click: CancelCategory">Cancel</button>
</td>
</tr>
</table>
</td>
</tr>
<tr>
<td>
<table style="width: 300%" id="tblCategory">
<thead>
<tr>
<th style="width: 100%">Category Name</th>
<th style="width: 100%">Is Active</th>
<th style="width: 100%">Edit</th>
<th style="visibility: hidden">CategoryId</th>
<th style="visibility: hidden">MgaCode</th>
</tr>
</thead>
<tbody data-bind="foreach: CategoryCollection()">
<tr>
<td data-bind="text: CategoryName"></td>
<td data-bind="text: IsActive"></td>
<td><a id="hrefEditCategory" data-bind="click: function () { ViewModel.EditCategory($data); }">Edit</a></td>
<td data-bind="text: MGACategoryId" style="display: none"></td>
</tr>
</tbody>
</table>
</td>
</tr>
</table>
</td>
</tr>
</table>
</td>
</tr>
</table>
</div>
</body>
<script type="text/javascript">
var SelectedCategory = 0;
var CategoryId = 0;
var row = {
CategoryName: "",
IsActive: false,
MGACategoryId: null,
MGACode: null
};
$(document).ready(function () {
ViewModel = {
CategoryCollection: ko.observableArray(),
flagCategory: ko.observable(true),
flagInsertCategory: ko.observable(false),
EditCategory: ko.observable(),
txtCategoryName: ko.observable(''),
chkCategoryActive: ko.observable(false),
CategoryLink: function () {
this.flagCategory(true);
this.flagApplicationForm(false);
this.flagSubCategory(false);
},
CancelCategory: function () {
this.flagInsertCategory(false);
this.txtCategoryName('');
this.chkCategoryActive(false);
$('#btnSaveCategory').text('Save');
},
EditCategory: function (data) {
debugger;
this.flagInsertCategory(true);
this.txtCategoryName(data.CategoryName);
this.chkCategoryActive(data.IsActive);
CategoryId = data.MGACategoryId;
$('#btnSaveCategory').text('Update');
row = data;
},
SaveCategory: function () {
debugger;
var id = CategoryId;
var name = this.txtCategoryName();
var isactive = this.chkCategoryActive();
if ($('#btnSaveCategory').text() == 'Update') {
row.CategoryName = name;
row.IsActive = isactive;
this.CategoryCollection()
for (var i = 0; i < this.CategoryCollection().length; i++) {
if (this.CategoryCollection()[i].MGACategoryId == row.MGACategoryId) {
this.CategoryCollection()[i].CategoryName=name;
this.CategoryCollection()[i].IsActive=isactive;
}
}
}
else {
row.CategoryName = this.txtCategoryName();
row.IsActive = this.chkCategoryActive();
this.CategoryCollection.push(row);
this.flagInsertCategory(false);
}
},
}
debugger;
$.ajax({
type: "GET",
url: 'Datepicker/GetCategory',
async: false,
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (response) {
debugger;
if (response != null) {
for (var i = 0; i < response.length; i++) {
ViewModel.CategoryCollection().push(response[i]);
}
}
},
error: function (data) {
debugger;
}
});
debugger;
ko.applyBindings(ViewModel);
});
</script>
</html>
I want to update my table using edit link given in table 'tblCategory'. Observable array for tblCategory is CategoryCollection(). Data is binded using JSON data from database. When I clicked on Edit button 'trInsertUpdateCategory' will be shown with filled row data. When I update data in textbox or checkbox and click on update button data is not updated in table. But when I add new data using that textbox and check box data is inserting and showing in table also. But update is not working for me please guide.
Dont know if this is what you are looking for, but there is a problem in your ajax success function.
success: function (response) {
debugger;
if (response != null) {
for (var i = 0; i < response.length; i++) {
ViewModel.CategoryCollection().push(response[i]);
}
}
}
Try changing it to
success: function (response) {
debugger;
if (response != null) {
for (var i = 0; i < response.length; i++) {
ViewModel.CategoryCollection().push(response[i]);
}
ViewModel.CategoryCollection.valueHasMutated();
}
}
Since right now, your observable array wont notify subscribers that its value is changed
How can I get value of checkbox in table? I want use it for in this case in order get parameter. Now, please see html table:
<table id="div_func" class="table table-bordered" style="width: 100%">
<thead>
<tr>
<th>
<input type="checkbox" id="chk_all" /></th>
<th>Name</th>
</tr>
</thead>
<tbody>
<tr>
<td> <input type="checkbox" class="checkbox1" id="chk" name="check[]" value="D01" /></td>
<td>Banana </td>
</tr>
<tr>
<td> <input type="checkbox" class="checkbox1" id="chk" name="check[]" value="D02" /></td>
<td>Orange </td>
</tr>
<tr>
<td> <input type="checkbox" class="checkbox1" id="chk" name="check[]" value="D03" /></td>
<td>Apple </td>
</tr>
</tbody>
</table>
And this is my script , I use for get value in checkbox , then put parameter
function add_funcgroup() {
var func_group = [];
var chk_allow = "";
var table = document.getElementById("div_func");
for (var i = 0; i < table.rows.length; i++) {
if ($('#chk')[i].is(':checked')) {
chk_allow = "True";
}
else {
chk_allow = "False";
}
var group_func = {
GROUP_MOD_ID: id_temp,
FUNCTION_MOD_ID: $('#chk')[i].val(),
ALLOW: chk_allow
};
func_group[i] = group_func;
}
var func_group_temp = {
FUNC_MOD: func_group
};
var DTO = {
'func_group_temp': func_group_temp
};
$.ajax(
{
And it's not working.
What you have done is right, but you are not outputting it to the table!
var table = $("#div_func");
var value_check = "";
for (var i = 1; i < table.rows.length; i++) {
if ($('#chk')[i].is(':checked')) {
value_check += i + ": " + $('#chk')[i].val();
}
}
alert(value_check);
And you aren't appending it, instead saving!
Try to this
$('#div_func tbody tr input:checkbox').each(function() {
if (this.checked) {
//Do something
}
});.
I have a textbox in which the user is allowed to enter alphanumeric input. I also have a plus image which on clicking will have to add the entered text to a multiple select box called "add key num" (shown below). After adding a few inputs to the multiple select box "add key num", the user can click the left arrow to add the final list to the "list key num" select box. I am stuck on the JavaScript for adding the text input from the textbox to the first select box. Please advise.
Here is the code that I have:
<cfparam name="SESSION.stkeynum" default="">
<table border="1" align="center" STYLE="margin-left:120px;" bgcolor="##B0C4DE">
<tr>
<td align="center" >ENTER KEY NUM</td>
<td align="center" ></td>
<td align="center" >ADD KEY NUM</td>
<td align="center" ></td>
<td align="center" >LIST KEY NUM</td>
<td align="center" >AMOUNT</td>
</tr>
<tr>
<td align="center"><input type="text" maxlength ="8" name="vstkeynum" id="vstkeynum" value="" size="15"></td>
<td><img src="../images/plus.jpg" alt="Add Key number" onclick="add_cc(document.myform.vstkeynum.value);"></img></td>
<td nowrap>
<div id="Div1"></div>
<select name="keynumber" size="5" multiple style="width: 175px; display: inline;">
<option value="null"> </option>
</select>
</td>
<td><img src="../images/arrow_right.gif" alt="Add To List" onclick="copySelectedOptions_edit(document.myform.keynumber,document.myform.keynumber_selection);">
<hr>
<img onclick="removeSelectedOptions_edit(document.myform.keynumber_selection);" src="../images/arrow_left.gif" alt="Delete From List">
</td>
<td nowrap>
<select name="keynumber_selection" size="5" multiple style="width: 175px;">
</select>
</td>
<td align="center"><input type="text" maxlength ="8" name="amount" id="amount" value="" size="7"></td>
</tr>
</table>
JavaScript:
<script type="text/javascript">
function add_cc(a) {
// inital load
ajax({
url: 'add_keynum.cfm?vval=' + a,
fillDiv: 'Div1',
showBusy: true
});
document.myform.vstkeynum.value = "";
}
</script>
<script>
function copySelectedOptions_edit(from, to) {
var options = new Object();
if (hasOptions(to)) {
for (var i = 0; i < to.options.length; i++) {
options[to.options[i].value] = to.options[i].text;
}
}
if (!hasOptions(from)) {
return;
}
for (var i = 0; i < from.options.length; i++) {
var o = from.options[i];
if (o.selected) {
if (options[o.value] == null || options[o.value] == "undefined" || options[o.value] != o.text) {
if (!hasOptions(to)) {
var index = 0;
} else {
var index = to.options.length;
}
to.options[index] = new Option(o.text, o.value, false, false);
}
}
}
if ((arguments.length < 3) || (arguments[2] == true)) {
sortSelect(to);
}
from.selectedIndex = -1;
to.selectedIndex = -1;
}
function removeSelectedOptions_edit(from) {
if (!hasOptions(from)) {
return;
}
if (from.type == "select-one") {
from.options[from.selectedIndex] = null;
} else {
for (var i = (from.options.length - 1); i >= 0; i--) {
var o = from.options[i];
if (o.selected) {
from.options[i] = null;
}
}
}
from.selectedIndex = -1;
}
</script>
This is the code in add_keynum.cfm:
<cfif isDefined("vval") >
<cfif trim(vval) neq "">
<cfset SESSION.stkeynum = Listappend(SESSION.stkeynum,vval)>
<cfoutput>#SESSION.stkeynum#</cfoutput>
<cfelse>
<cfif isDefined("session.stkeynum")>
<cfoutput>#SESSION.stkeynum#</cfoutput>
</cfif>
</cfif>
</cfif>