I would like to toggle the display row for a table in javascript. How do I do this?
<script type="text/javascript" language="javascript">
function vehicleSelected() {
var autoSelect = document.getElementById('vehicleSelect');
var strAuto = autoSelect.options[autoSelect.selectedIndex].value;
var rowAuto = document.getElementById(strAuto);
for (var i = 4; i < tableList.rows.length; i++) {
//I am not sure how to access the id for comparison to rowAuto
if (//table row == strAuto) {
rowAuto.style.display = '';
} else {
rowAuto.style.display = 'none';
}
}
}
</script>
<table id="tableList">
<tr id="optionA"><td>Display Row A</td></tr>
<tr id="optionB"><td>Display Row B</td></tr>
<tr id="optionC"><td>Display Row C</td></tr>
<tr id="optionD"><td>Display Row D</td></tr>
</table>
First, consider jquery. It's a big help for things like this.
Second, if you're not going to use jquery, then what you want to do is something like this:
function vehicleSelected() {
var autoSelect = document.getElementById('vehicleSelect');
var strAuto = autoSelect.options[autoSelect.selectedIndex].value;
var rows = document.getElementById('tableList').getElementsByClassName('TR');
for (var i = 0; i < rows.length; i++) {
rows[i].style.display='none'; // note: better to use a css class here
}
var selectedRow = document.getElementById(strAuto); // assuming that the values are the same as the row Id's.
selectedRow.style.display = ''; // again, better to use a Css style.
}
You could do it easily with jQuery:
function vehicleSelected() {
var autoSelect = //...
var strAuto = //...
$("#tableList tr").hide().filter("#" + strAuto).show();
}
If I correctry understood you, this should help you.
var table = document.getElementById('tableList');
for(var i=0; i<table.rows.length; i++){
if (table.rows[i].attributes["id"].nodeValue == strAuto) {
table.rows[i].style.display = '';
} else {
table.rows[i].style.display = 'none';
}
}
Related
While coding an assignment I've come to need to transfer data from the code-behind to the view so that I can parse that data with Javascript and build some HTML with it, and I've decided to use asp:HiddenField to that end.
However, it seems something goes wrong, since I get the error "The name "HiddenFieldData" does not exist in the current context".
I assume that I'm somehow not linking the view to the model correctly.
Perhaps it's because I'm using a model that is not the appropriate cshtml.cs, but one that is "given" to the view via the controller.
Truth be told, this is my first time with ASP.NET so it's very likely the problem is somewhere here.
The code in question, I've marked the trouble spots with '>>>>':
Controller -
public class saveController : Controller
{
// GET: Save
public ActionResult SaveRoute()
{
saveModel model = new saveModel();
Model given >>>> return View(model);
}
}
Model -
public class saveModel
{
private DataMiner miner;
public saveModel(string ip = "127.0.0.1", int port = 5400, int duration = 10, int interval = 1000)
{
// Initialize miner
miner = new DataMiner(ip, port, duration, interval);
}
public void SaveRoute()
{
// Mine and retrieve data
miner.Mine();
double[][] data = miner.GetData();
int lines = data.GetLength(0);
int cols = data.GetLength(1);
string[] str_data = new string[lines];
for (int i = 0; i < lines; ++i)
{
// Turn double data into strings to write
str_data[i] = data[i].ToString();
}
// Write to file
System.IO.File.WriteAllLines(#"file1.txt", str_data);
// Write values to HiddenField
string values = String.Join(" ", str_data);
Error here >>>> HiddenFieldData.Value = values;
// Call JS function to load at
ScriptManager.RegisterStartupScript(this, GetType(), "showDataMined", "showDataMined();", true);
}
}
View -
#model RESTful_Flight_Simulator.Models.saveModel
#{
ViewBag.Title = "SaveRoute";
}
<html>
<head>
<asp:ScriptManager ID="ScriptManager1" runat="server" EnablePageMethods="true" />
<script type="text/javascript" language="javascript">
function showDataMined()
{
var body = document.body
var tbl = document.createElement('table');
tbl.style.width = '100px';
tbl.style.border = '1px solid black';
for (var i = 0; i < 3; i++)
{
var tr = tbl.insertRow();
for (var j = 0; j < 2; j++)
{
if (i == 2 && j == 1) { break; }
else
{
var td = tr.insertCell();
td.appendChild(document.createTextNode('Cell'));
td.style.border = '1px solid black';
if (i == 1 && j == 1) {
td.setAttribute('rowSpan', '2');
}
}
}
}
// Build title for table
var title = document.createElement('h3');
title.innerHTML = "Data mined:";
// Finally, append title and table to body
body.appendChild(document.createElement('hr'));
body.appendChild(title);
body.appendChild(tbl);
}
</script>
</head>
<body>
HiddenField >>>> <asp:HiddenField id="HiddenFieldData" runat="server" value="" />
<h2>Saving route...</h2>
</body>
</html>
Thanks ahead for any help!
I have a view with 1700 records. I want to paginate them using ajax to make page load lighter. I am able to do paging and bring set of new records everytime based on the page selected.
The Problem
I am showing only 10 indexes in page-bottom, the page selected as well as 4 to the left and 5 to the right. Now I need CurrentPage value which I send everytime from jQuery/ajax to controller which I get as a ajax data parameter. The problem is in getting back Current page value persistent to view when the next page index I select. I always get the old value and not the last selected page value. I have even used ViewBag instead of tempData but no success.
View Code:
#model IEnumerable<UrCompedDAL.DBModels.SlotMachineModel>
<div class="my-properties">
<table id="tbl_slots" class="table no-margin" data-search="true" data-pagination="false">
<tbody class="orgTbody">
#foreach (var item in Model)
{
<tr>
//Code for Slot list
</tr>
}
</tbody>
</table>
<ul class="paging">
#{
int i = 1;
int pg = Convert.ToInt32(TempData["Current"]);
if (i > 0 || i == ViewBag.PageSize)
{
<li>
<<
</li>
}
if (pg < 6)
{
for (i = 1; i < 11; i++)
{
<li>
#i
</li>
}
}
else
{
for (i = pg - 4; i < pg; i++)
{
<li>
#i
</li>
}
for (i = pg; i < pg + 6; i++)
{
<li>
#i
</li>
}
}
if (i > 1 || i < ViewBag.PageSize)
{
<li>
>>
</li>
}
}
</ul>
</div>
<script>
$(document).ready(function () {
$('.lipaging').click(function () {
$("#loadingDiv").show();
$(this).addClass('active');
var pageThis = $(this).text();
var current = #TempData["Current"];
if (pageThis == '>>') {
pageThis = current +1;
}
if (pageThis == '<<') {
pageThis = current -1;
}
$.ajax({
type: 'get',
url: '#Url.Action("Index", "Game_SlotMachine")',
data: {
CurrentPage: pageThis
}
}).done(function (data) {
var startIndex = data.indexOf("<tbody");
var endIndex = data.indexOf("</tbody>");
var html = data.substring(startIndex, endIndex + 8);
$('#tbl_slots').html('');
$('#tbl_slots').html(html);
setTimeout(function () {
filter();
}, 300);
$("#loadingDiv").hide();
});
});
Controller Code:
public ActionResult Index(int id = 0, int CurrentPage = 1)
{
List<SlotMachineModel> slotmodel = new List<SlotMachineModel>();
slotmodel = UrCompedDAL.DataAccessor.Instance.GameAccessor.GetAllSlotMachines().ToList();
ViewBag.PageSize = slotmodel.Count / 10;
TempData["Current"] = CurrentPage;
slotmodel = slotmodel.Skip((CurrentPage - 1) * 10).Take(10).ToList();
return View(slotmodel);
}
Please help.
Pack your model IEnumerable<UrCompedDAL.DBModels.SlotMachineModel> into other model and set your model as a property of new model. Pass this new model as a model for your view. You will be able to pass as many data from controller as you like.
The issue is that you're re-creating the whole view, but only updating the table from the result
var html = data.substring(startIndex, endIndex + 8);
$('#tbl_slots').html('');
$('#tbl_slots').html(html);
(you should also reconsider how you extract the table from the view and use a partial instead).
None of the ajax/2nd+ rendering of the paging ul is used and is "thrown away" each time.
You can either overwrite your ul in the same way as the table or update the paging element via javascript (probably the former).
Reusing the whole view (rather than a partialview), you'd get something like:
}).done(function (data) {
var html = $("<div/>").html(data);
$('#tbl_slots').html(html.find("#tbl_slots").html());
$('ul.paging').html(html.find("ul.paging").html());
Design Code
<tr id="DEPB" runat="server"></tr>
<tr id="DEPB" runat="server"></tr>
<tr id="DEPB" runat="server"></tr>
Behind Code
string Test = ddlExim.SelectedItem.Text.Substring(3);
txtEximDesc.Text = ddlExim.SelectedItem.Text.Substring(3);
string[] Demo = ddlExim.SelectedValue.Split(',');
try
{
DBK.Style.Add("display", "none");
DEPB.Style.Add("display", "none");
EPCG.Style.Add("display", "none");
NFEI.Style.Add("display", "none");
for (int i = 0; i < 3; i++)
{
if (Demo[i] == "DEPB")
{
Demo[i].Style.Add("display", "table-row");
}
else if (Demo[i] == "EPCG")
{
EPCG.Style.Add("display", "table-row");
}
else if (Demo[i] == "DBK")
{
DBK.Style.Add("display", "table-row");
}
else if (Demo[i] == ".")
{
NFEI.Style.Add("display", "table-row");
}
}
}
catch (Exception ex)
{
string Message = ex.Message;
}
i want to replace DEPB,EPCG,DBK with Demo[i] like below but getting error: "String doesnt contain a defnition for style".
Demo[i].Style.Add("display", "table-row");
Mark runat="server" to the table element inside which these tablerows are present ("tbl" in my example) and then try the following code.
for (int i = 0; i < Demo.Length; i++)
{
(tbl.FindControl(Demo[i]) as HtmlTableRow).Style.Add("display", "table-row");
}
Of course you need to add the following namespace.
using System.Web.UI.HtmlControls;
Hope this helps.
Demo is an array of string, hence Demo[i] is a string and string doesn't have property Style. This line look like an outlier compared to other if's content :
Demo[i].Style.Add("display", "table-row");
I guess it should be as follow instead :
DEPB.Style.Add("display", "table-row");
Try to cat Demo[i] to webcontrol
function printform() {
var printContent = document.getElementById("<%= PrintPanelID.ClientID %>");
var windowUrl = "about:blank";
var uniqueName = new Date();
var windowName = "Print" + uniqueName.getTime();
var printWindow = window.open(windowUrl, windowName, "left=50000,top=50000,width=0,height=0");
printWindow.document.write(printContent.innerHTML);
printWindow.document.close();
printWindow.focus();
printWindow.print();
printWindow.close();
}
function HidColumn() {
// col_num = document.getElementById("Button").value;
rows = document.getElementById("<%= GV1.ClientID %>").rows;
for (i = 0; i < rows.length; i++) {
rows[i].cells[8].style.display = "none";
}
for (j = 0; j < rows.length; j++) {
rows[j].cells[9].style.display = "none";
}
}
// change logic to suit taste
function clicked() {
var b = HidColumn();
if (b)
printform()
return b;
}
<asp:ImageButton ID="ImageButton2" runat="server" ImageAlign="Right" ImageUrl="images/printer.jpg"
Style="margin-left: 5px; margin-right: 15px" OnClick="ImageButton2_Click" Width="36px"
OnClientClick="return clicked()" Visible="false" />
However nothing is happening when i click the ImageButton
This line doesn't make sense: var b = HidColumn();
The function HidColumn doesn't return anything.
AS I said that I agree with the steve answer and you should modify your function HidColumn to return either true or false.
One more point i would like to mention that if you return false from clicked() Then postback will not happen otherwise it will call ImageButton2_Click event on server.
function HidColumn() {
// col_num = document.getElementById("Button").value;
rows = document.getElementById("<%= GV1.ClientID %>").rows;
for (i = 0; i < rows.length; i++) {
rows[i].cells[8].style.display = "none";
}
for (j = 0; j < rows.length; j++) {
rows[j].cells[9].style.display = "none";
}
if(someCondition)return true;
else return false;
}
UPDATE:-
you have set the control visibility to False , hence the control will not be rendered.
Hence you cannot get the Element in javascript because there will be no HTML for that control.
if you want hide the control just use Javascript :-
<asp:somecontrol id="ctrl" style="display:none" />
simply put your hide column code in a print function like this:
function PrintPage() {
rows = document.getElementById("<%= Gv1.ClientID %>").rows;
for (i = 0; i < rows.length; i++) {
rows[i].cells[8].style.display = "none";
rows[i].cells[9].style.display = "none";
}
var printContent = document.getElementById('<%= pnlDtls.ClientID %>');
var printWindow = window.open("All Records", "Print Panel", 'left=50000,top=50000,width=0,height=0');
printWindow.document.write(printContent.innerHTML);
printWindow.document.close();
printWindow.focus();
printWindow.print();
}
I have created a web form in which I have take certain fields like Name, Age and two radio button list (Required and ID). I want to enable disable certain fields on the value of one radiobutton list "Required". The "Required" Radiobuttonlist has two items, "YES", "NO". If I select yes, then certain fields should get enabled disabled and vice versa.
I am able to disable the texboxes, however I am not able to disable a radiobutton list "ID" which has to list items in it as taxId and PAN. I have used the following code for it
function EnableDisableID() {
if (document.getElementById("<%=rdID.ClientID %>") != null) {
var IDList = document.getElementById('<%= rdID.ClientID %>');
var isOpenID;
if (IDList != null) {
var openSubID = IDList.getElementsByTagName("input");
for (var i = 0; i < openSubID.length; i++) {
if (openSubID[i].checked) {
openSubID = openSubID[i].value;
}
}
}
if (openSubID == 'true') {
document.getElementById('<%=fbo1RadioButtonList.ClientID %>').disabled = false;
document.getElementById('<%=txtFbo1TaxId.ClientID %>').disabled = false;
}
if (isOpenSubAccount == 'false') {
alert("Printing..." + isOpenSubAccount);
document.getElementById('<%=fbo1RadioButtonList.ClientID %>').disabled = true;
document.getElementById('<%=txtFbo1TaxId.ClientID %>').disabled = true;
}
}
}
I am able to disable the FBO1TaxId, however, I am not able to disable the radiobutton list "fbo1RadioButtonList". How will I achieve it. do I have to treat its value individually?
I got the answer. I played with my code just a bit and came to a solution below:
function EnableDisableTaxID() {
if (document.getElementById("<%=rdOpeningSubAccount.ClientID %>") != null) {
var openSubAccountList = document.getElementById('<%= rdOpeningSubAccount.ClientID %>');
var rdFbo1TaxId = document.getElementById('<%=fbo1RadioButtonList.ClientID %>');
var rdFBO1Items = rdFbo1TaxId.getElementsByTagName('input');
var isOpenSubAccount;
if (openSubAccountList != null) {
var openSubAccount = openSubAccountList.getElementsByTagName("input");
for (var i = 0; i < openSubAccount.length; i++) {
if (openSubAccount[i].checked) {
isOpenSubAccount = openSubAccount[i].value;
}
}
}
if (isOpenSubAccount == 'true') {
for (var i = 0; i < rdFBO1Items.length; i++) {
rdFBO1Items[i].disabled = false;
}
document.getElementById('<%=txtFbo1TaxId.ClientID %>').disabled = false;
}
if (isOpenSubAccount == 'false') {
for (var i = 0; i < rdFBO1Items.length; i++) {
rdFBO1Items[i].disabled = true;
}
document.getElementById('<%=txtFbo1TaxId.ClientID %>').disabled = true;
}
}
}
You will have to loop over the radio buttons and disable each one. If your buttons are in a form, and you have a reference to the form, then you can use the common name for the buttons to get a collection. Loop over the collection and set each button's disabled property.
If you might either enable or disable the buttons, you can use a condition to set the value, something like:
var rbuttons = form.radioName;
var disabled = true; // disables buttons, set to false to enable
for (var i=0, iLen=rbuttons.length; i<iLen; i++) {
rbuttons[i].disabled = disabled;
}
To enable the buttons, set the disabled variable to false.