How create an AjaxToolKit control, (rating), from code-behind in C#? - c#

I am creating dinamically controls from code-behind, such as textbox, checkboxlist, radiobuttonlist, etc etc... and adding them in a placeholder inside a repeater, in order to create a dynamic survey from a template-user-made, the questions of the survey I want 'em to be created from code-behind, but if there's any other way for creating dynamically the controls, could you guys guide me with a specific topic or show me a code-example?
I was thinking something like..
AjaxControlToolkit.Rating rateThing = new AjaxControlToolkit.Rating();
rateThing.CurrentRating = 3;
rateThing.MaxRating = 5;
rateThing.StarCssClass = "ratingStar";
rateThing.WaitingStarCssClass = "savedRatingStar";
rateThing.FilledStarCssClass = "filledRatingStar";
rateThing.EmptyStarCssClass = "emptyRatingStar";
rateThing.ID = "rateThing" + IdPregunta.Value;
rateThing.Visible = true;
placeholder.Controls.Add(rateThing);
but it doesn't render ...
P.D. I already added the images the example need in the css to create the stars of the control, tried reading about rating in MS with this rating ajaxtoolkit stuff and with other stuff without success :(
EDITED: Never got figured it out so I choose for an RadioButtonList for creating the control in codebehind then using CSS and JS/JQuery for creating the real pseudocontrol of rating
You could use this as a guide for the codebehind
RadioButtonList rblEscala = new RadioButtonList();
rblEscala.ID = "rblRes" + IdPregunta.Value;
rblEscala.CssClass = "input-sm form-control col-sm-12 star-cb-group";
rblEscala.Style.Add("height", "auto !important;");
for (int i = 5; i >= 1; i--)
{
rblEscala.Items.Add(new ListItem("☆", i.ToString()));
}
rblEscala.RepeatDirection = RepeatDirection.Horizontal;
placeholder.Controls.Add(rblEscala);
In the front use this link as reference: https://codepen.io/anon/pen/PKxQYY

I'll free my code so you can use it, as a base for your custom rating
hehehe
For the CodeBehind try using a PlaceHolder and using this:
RadioButtonList rblEscala = new RadioButtonList();
rblEscala.ID = "rblRes";
rblEscala.CssClass = "star-cb-group";
rblEscala.Style.Add("height", "auto !important;");
for (int i = 5; i >= 1; i--)
{
//rblEscala.Items.Add(new ListItem(i.ToString(), i.ToString()));
rblEscala.Items.Add(new ListItem("☆", i.ToString()));
}
rblEscala.RepeatDirection = RepeatDirection.Horizontal;
placeholder.Controls.Add(rblEscala);
For CSS Use this:
.star-cb-group {
/* remove inline-block whitespace */
font-size: 0;
/* flip the order so we can use the + and ~ combinators */
unicode-bidi: bidi-override;
direction: rtl;
/* the hidden clearer */
}
.star-cb-group tbody {
float: left;
}
.star-cb-group * {
font-size: 2.5rem;
}
.star-cb-group input {
display: none;
background: none;
}
.star-cb-group label {
background: none !important;
padding-left: 5px !important;
height: auto !important;
}
.star-cb-group input + label {
color: #888;
}
.star-cb-group input:checked + label {
color: #e52;
}
For JS/Jquery I added this:
try {
$(".star-cb-group input").change(function () {
//$(this).next().text("★");
var inputs = $(this).parent().parent().children().children("input");
var bandera = false;
inputs.each(function () {
if ($(this).is(':checked') || bandera) {
$(this).next().text("★");
$(this).next().css("color", "#e52");
$(this).next().css("font-weight", "Bold !important");
bandera = true;
} else {
$(this).next().text("☆");
$(this).next().css("color", "#888");
$(this).next().css("font-weight", "normal !important");
}
});
});
} catch (err2) {
console.log(err2);
}

Related

ASP.NET MVC : completed job should go down (Sorting on Front-End page)

Model
public class Jobs
{
public List<string> JobNames { get; set; }
}
Controllers
public class HomeController : Controller
{
public static List<string> sorteddailyreports= new List<string>();
static Jobs jobnames;
public static List<string> dailyreports = new List<string>();
public ActionResult GetJobs()
{
jobnames =new Jobs();
dailyreports = new List<string> { "M2I|0705","FGI|1220","SDI|0100" };
sorteddailyreports=dailyreports.ToList().OrderBy(x=> x.Split('|')[1].Trim()).ToList();
jobnames.JobNames = sorteddailyreports;
return View(jobnames);
}
public static int IsJobRan(string job)
{
int completed = 0;
if (true) //some condition
{
completed = 1;
}
else
{
completed = -1;
}
return completed;
}
}
View
#model WebApplication1.Models.Jobs
<body>
#foreach(string jobdetails in Model.JobNames)
{
string job = jobdetails.Split('|')[0].Trim();
string runtime = jobdetails.Split('|')[1].Trim();
string fruntime = runtime.Substring(0, 2) + ":" + runtime.Substring(2, 2);
if (WebApplication1.Controllers.HomeController.IsJobRan(jobdetails)==1)
{
<tr>
#Html.Label(job)
</tr>
<tr>
#Html.Label(fruntime)
</tr>
}
<br />
}
</body>
I am expecting in view if the method return 1 it means jobs completed then completed job should go down and if the method returns other than 1 the job is sorted on the basis of runtime.
For example: if M2I job runs successfully and returns 1, then the Output which I am expecting in view. Completed Job M2I should go down and other jobs like SDI and FGI are sorted on the basis of runtime.
SDI 0100
FGI 1220
M2I 0705
Code which I am trying but didn't get the desired result
sorteddailyreports = dailyreports.ToList()
.OrderBy(x => x.Split('|')[1].Trim())
.ToList();
Please amend the code, I am new in Asp.net MVC Thanks in advance.
I am trying Generic Move method for moving the Completed List to last on the Front End page.
Add this logic in Controller to move completed list to last index still not able to get sorting on front end. call this method in view still Not sure this Move method is a workable solution for sorting at front end.
public static void Move(List<string> list, int newIndex, int oldIndex)
{
var item = list[oldIndex];
list.RemoveAt(oldIndex);
if (newIndex > oldIndex) newIndex--;
list.Insert(newIndex, item);
}
You can check the Front-end gif picture first.
And the code here.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>css3 dynamic</title>
</head>
<style>
*{
margin: 0;
padding: 0;
box-sizing: border-box;
list-style: none;
font-size: 12px;
}
.box{
width: 600px;
height: 500px;
margin: 100px auto;
}
.skill {
width: 100%;
list-style: none;
}
.skill li {
position: relative;
margin-bottom: 25px;
}
.skill li .expand-box{
width: 100%;
margin-top: 20px;
margin-bottom: 10px;
height: 15px;
border-radius: 3px;
border: 1px solid #092c99;
position: relative;
}
.skill li em:first-child {
position: absolute;
top: -15px;
left: 0;
}
.skill li em:last-child {
position: absolute;
top: -15px;
right: 0;
}
.expand {
height: 13px;
margin: 0;
top: 0;
background: #2187e7;
position: absolute;
border-radius: 3px;
box-shadow: 0px 0px 10px 1px rgba(0, 198, 255, 0.4);
}
</style>
<body>
<div class="box">
<ul class="skill" id="chart"></ul>
</div>
<script src="https://code.jquery.com/jquery-3.6.3.js" integrity="sha256-nQLuAZGRRcILA+6dMBOvcRh5Pe310sBpanc6+QBmyVM=" crossorigin="anonymous"></script>
<script>
$(document).ready(function(){
let listdata = [
{"data1":"Job 1","data2":54},
{"data1":"Job 2","data2":3},
{"data1":"Job 3","data2":12},
{"data1":"Job 4","data2":65},
{"data1":"Job 5","data2":3}
];
const compareData2 = (arrayItemA, arrayItemB) => {
if (arrayItemA.data2 < arrayItemB.data2) {
return 1
}
if (arrayItemA.data2 > arrayItemB.data2) {
return -1
}
return 0
}
const objectComparisonCallback = (arrayItemA, arrayItemB) => {
// first sort by data2
return compareData2(arrayItemA, arrayItemB)
}
listdata.sort(objectComparisonCallback)
loadData(listdata);
var job3 = setInterval(function(){
//find Job3
const index = listdata.findIndex(object => {
return object.data1 === "Job 3";
}); // 👉️ 1
if (index !== -1) {
if(listdata[index].data2< 100){
listdata[index].data2 += 1;
$('#chart').empty();
listdata.sort(objectComparisonCallback);
loadData(listdata);
//clear all the css style about the .animations2
$(".animations"+index).css("width",listdata[index].data2+"%")
}
else{
console.log("Job 3 COMPLETED!");
clearInterval(job3);
}
}
}, 100);
})
function loadData(listdata){
let _html = '';
let len = listdata.length;
if(len > 0){
for(let i = 0; i < len; i++){
_html += '<li>';
_html += '<em>'+listdata[i]['data1']+'</em>';
_html += '<div class="expand-box"><span class="expand animations'+i+'"></span></div>';
_html += '<em>'+listdata[i]['data2']+'%</em>';
_html += '</li>';
let newStyle=document.styleSheets[0];
newStyle.insertRule(
".animations"+i+" { " +
"width: "+listdata[i]['data2']+"%;" +
"-moz-animation:animations"+i+" 0s ease-out;" +
"-webkit-animation:animations"+i+" 0s ease-out;" +
"}", 0);
newStyle.insertRule(
"#keyframes animations"+i+"{ " +
"0% { width: 0; } " +
"100% { width:"+listdata[i]['data2']+" % }" +
"}",0);
$('#chart').html(_html);
}
}else{
$('#chart').html('No Data');
}
}
</script>
</body>
</html>
You should learn the signalr in asp.net core.
The use of Signalr can carry out real-time communication very well, and the background task execution process can be sent to the front-end page through websocket in real time. You can implement the sorting of the front-end pages according to your needs.
Here is a complete sample code, you can refer to the blog to realize your needs.
Communicate the status of a background job with SignalR

How to use web speech API in C#

This is a html file which contains web speech API code. I want convert this to a web service and hope use it as a reference in windows forms application in c#. I have no idea how to do that and if someone can give some instructions to do that it will be grateful.
Thank you!
<!DOCTYPE html>
<meta charset="utf-8">
<title>Voice To Text</title>
<style>
* {
font-family: Verdana, Arial, sans-serif;
}
a:link {
color:#000;
text-decoration: none;
}
a:visited {
color:#000;
}
a:hover {
color:#33F;
}
.button {
background: -webkit-linear-gradient(top,#008dfd 0,#0370ea 100%);
border: 1px solid #076bd2;
border-radius: 3px;
color: #fff;
display: none;
font-size: 13px;
font-weight: bold;
line-height: 1.3;
padding: 8px 25px;
text-align: center;
text-shadow: 1px 1px 1px #076bd2;
letter-spacing: normal;
}
.center {
padding: 10px;
text-align: center;
}
.final {
color: black;
padding-right: 3px;
}
.interim {
color: gray;
}
.info {
font-size: 14px;
text-align: center;
color: #777;
display: none;
}
.right {
float: right;
}
.sidebyside {
display: inline-block;
width: 45%;
min-height: 40px;
text-align: left;
vertical-align: top;
}
#headline {
font-size: 40px;
font-weight: 300;
}
#info {
font-size: 20px;
text-align: center;
color: #777;
visibility: hidden;
}
#results {
font-size: 14px;
font-weight: bold;
border: 1px solid #ddd;
padding: 15px;
text-align: left;
min-height: 150px;
}
#start_button {
border: 0;
background-color:transparent;
padding: 0;
}
</style>
<h1 class="center" id="headline">
<a href="http://dvcs.w3.org/hg/speech-api/raw-file/tip/speechapi.html">
Web Speech API</a> Demonstration</h1>
<div id="info">
<p id="info_start">Click on the microphone icon and begin speaking.</p>
<p id="info_speak_now">Speak now.</p>
<p id="info_no_speech">No speech was detected. You may need to adjust your
<a href="//support.google.com/chrome/bin/answer.py?hl=en&answer=1407892">
microphone settings</a>.</p>
<p id="info_no_microphone" style="display:none">
No microphone was found. Ensure that a microphone is installed and that
<a href="//support.google.com/chrome/bin/answer.py?hl=en&answer=1407892">
microphone settings</a> are configured correctly.</p>
<p id="info_allow">Click the "Allow" button above to enable your microphone.</p>
<p id="info_denied">Permission to use microphone was denied.</p>
<p id="info_blocked">Permission to use microphone is blocked. To change,
go to chrome://settings/contentExceptions#media-stream</p>
<p id="info_upgrade">Web Speech API is not supported by this browser.
Upgrade to Chrome
version 25 or later.</p>
</div>
<div class="right">
<button id="start_button" onclick="startButton(event)">
<img id="start_img" src="mic.gif" alt="Start"></button>
</div>
<div id="results">
<span id="final_span" class="final"></span>
<span id="interim_span" class="interim"></span>
<p>
</div>
<div class="center">
<div class="sidebyside" style="text-align:right">
<button id="copy_button" class="button" onclick="copyButton()">
Copy and Paste</button>
<div id="copy_info" class="info">
Press Control-C to copy text.<br>(Command-C on Mac.)
</div>
</div>
<div class="sidebyside">
<button id="email_button" class="button" onclick="emailButton()">
Create Email</button>
<div id="email_info" class="info">
Text sent to default email application.<br>
(See chrome://settings/handlers to change.)
</div>
</div>
<p>
<div id="div_language">
<select id="select_language" onchange="updateCountry()"></select>
<select id="select_dialect"></select>
</div>
</div>
<script>
var langs =
[['Afrikaans', ['af-ZA']],
['Bahasa Indonesia',['id-ID']],
['Bahasa Melayu', ['ms-MY']],
['Català', ['ca-ES']],
['Čeština', ['cs-CZ']],
['Deutsch', ['de-DE']],
['English', ['en-AU', 'Australia'],
['en-CA', 'Canada'],
['en-IN', 'India'],
['en-NZ', 'New Zealand'],
['en-ZA', 'South Africa'],
['en-GB', 'United Kingdom'],
['en-US', 'United States']],
['Español', ['es-AR', 'Argentina'],
['es-BO', 'Bolivia'],
['es-CL', 'Chile'],
['es-CO', 'Colombia'],
['es-CR', 'Costa Rica'],
['es-EC', 'Ecuador'],
['es-SV', 'El Salvador'],
['es-ES', 'España'],
['es-US', 'Estados Unidos'],
['es-GT', 'Guatemala'],
['es-HN', 'Honduras'],
['es-MX', 'México'],
['es-NI', 'Nicaragua'],
['es-PA', 'Panamá'],
['es-PY', 'Paraguay'],
['es-PE', 'Perú'],
['es-PR', 'Puerto Rico'],
['es-DO', 'República Dominicana'],
['es-UY', 'Uruguay'],
['es-VE', 'Venezuela']],
['Euskara', ['eu-ES']],
['Français', ['fr-FR']],
['Galego', ['gl-ES']],
['Hrvatski', ['hr_HR']],
['IsiZulu', ['zu-ZA']],
['Íslenska', ['is-IS']],
['Italiano', ['it-IT', 'Italia'],
['it-CH', 'Svizzera']],
['Magyar', ['hu-HU']],
['Nederlands', ['nl-NL']],
['Norsk bokmål', ['nb-NO']],
['Polski', ['pl-PL']],
['Português', ['pt-BR', 'Brasil'],
['pt-PT', 'Portugal']],
['Română', ['ro-RO']],
['Slovenčina', ['sk-SK']],
['Suomi', ['fi-FI']],
['Svenska', ['sv-SE']],
['Türkçe', ['tr-TR']],
['български', ['bg-BG']],
['Pусский', ['ru-RU']],
['Српски', ['sr-RS']],
['한국어', ['ko-KR']],
['中文', ['cmn-Hans-CN', '普通话 (中国大陆)'],
['cmn-Hans-HK', '普通话 (香港)'],
['cmn-Hant-TW', '中文 (台灣)'],
['yue-Hant-HK', '粵語 (香港)']],
['日本語', ['ja-JP']],
['Lingua latīna', ['la']]];
for (var i = 0; i < langs.length; i++) {
select_language.options[i] = new Option(langs[i][0], i);
}
select_language.selectedIndex = 6;
updateCountry();
select_dialect.selectedIndex = 6;
showInfo('info_start');
function updateCountry() {
for (var i = select_dialect.options.length - 1; i >= 0; i--) {
select_dialect.remove(i);
}
var list = langs[select_language.selectedIndex];
for (var i = 1; i < list.length; i++) {
select_dialect.options.add(new Option(list[i][1], list[i][0]));
}
select_dialect.style.visibility = list[1].length == 1 ? 'hidden' : 'visible';
}
var create_email = false;
var final_transcript = '';
var recognizing = false;
var ignore_onend;
var start_timestamp;
if (!('webkitSpeechRecognition' in window)) {
upgrade();
} else {
start_button.style.display = 'inline-block';
var recognition = new webkitSpeechRecognition();
recognition.continuous = true;
recognition.interimResults = true;
recognition.onstart = function() {
recognizing = true;
showInfo('info_speak_now');
start_img.src = 'mic-animate.gif';
};
recognition.onerror = function(event) {
if (event.error == 'no-speech') {
start_img.src = 'mic.gif';
showInfo('info_no_speech');
ignore_onend = true;
}
if (event.error == 'audio-capture') {
start_img.src = 'mic.gif';
showInfo('info_no_microphone');
ignore_onend = true;
}
if (event.error == 'not-allowed') {
if (event.timeStamp - start_timestamp < 100) {
showInfo('info_blocked');
} else {
showInfo('info_denied');
}
ignore_onend = true;
}
};
recognition.onend = function() {
recognizing = false;
if (ignore_onend) {
return;
}
start_img.src = 'mic.gif';
if (!final_transcript) {
showInfo('info_start');
return;
}
showInfo('');
if (window.getSelection) {
window.getSelection().removeAllRanges();
var range = document.createRange();
range.selectNode(document.getElementById('final_span'));
window.getSelection().addRange(range);
}
if (create_email) {
create_email = false;
createEmail();
}
};
recognition.onresult = function(event) {
var interim_transcript = '';
for (var i = event.resultIndex; i < event.results.length; ++i) {
if (event.results[i].isFinal) {
final_transcript += event.results[i][0].transcript;
} else {
interim_transcript += event.results[i][0].transcript;
}
}
final_transcript = capitalize(final_transcript);
final_span.innerHTML = linebreak(final_transcript);
interim_span.innerHTML = linebreak(interim_transcript);
if (final_transcript || interim_transcript) {
showButtons('inline-block');
}
};
}
function upgrade() {
start_button.style.visibility = 'hidden';
showInfo('info_upgrade');
}
var two_line = /\n\n/g;
var one_line = /\n/g;
function linebreak(s) {
return s.replace(two_line, '<p></p>').replace(one_line, '<br>');
}
var first_char = /\S/;
function capitalize(s) {
return s.replace(first_char, function(m) { return m.toUpperCase(); });
}
function createEmail() {
var n = final_transcript.indexOf('\n');
if (n < 0 || n >= 80) {
n = 40 + final_transcript.substring(40).indexOf(' ');
}
var subject = encodeURI(final_transcript.substring(0, n));
var body = encodeURI(final_transcript.substring(n + 1));
window.location.href = 'mailto:?subject=' + subject + '&body=' + body;
}
function copyButton() {
if (recognizing) {
recognizing = false;
recognition.stop();
}
copy_button.style.display = 'none';
copy_info.style.display = 'inline-block';
showInfo('');
}
function emailButton() {
if (recognizing) {
create_email = true;
recognizing = false;
recognition.stop();
} else {
createEmail();
}
email_button.style.display = 'none';
email_info.style.display = 'inline-block';
showInfo('');
}
function startButton(event) {
if (recognizing) {
recognition.stop();
return;
}
final_transcript = '';
recognition.lang = select_dialect.value;
recognition.start();
ignore_onend = false;
final_span.innerHTML = '';
interim_span.innerHTML = '';
start_img.src = 'mic-slash.gif';
showInfo('info_allow');
showButtons('none');
start_timestamp = event.timeStamp;
}
function showInfo(s) {
if (s) {
for (var child = info.firstChild; child; child = child.nextSibling) {
if (child.style) {
child.style.display = child.id == s ? 'inline' : 'none';
}
}
info.style.visibility = 'visible';
} else {
info.style.visibility = 'hidden';
}
}
var current_style;
function showButtons(style) {
if (style == current_style) {
return;
}
current_style = style;
copy_button.style.display = style;
email_button.style.display = style;
copy_info.style.display = 'none';
email_info.style.display = 'none';
}
</script>

Hiding two columns of GridView while printing it Asp.net

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

changing font size automatically

I have 3 paragraphs of text on a page...I want to change the font size of the paragraphs after every 3 seconds....is this possible?
What i want is when the page loads para 1 is 10px and para 2 is 8px and then after 3 seconds para 2 is 10px and para 1 is 8px.
I mean like using an update panel or something? js ...any way?
You can use the setInterval method to run a function at an interval:
CSS:
#para1 { font-szie: 10px; }
#para2 { font-szie: 8px; }
#para3 { font-szie: 8px; }
HTML:
<p id="para1">asdf</p>
<p id="para2">asdf</p>
<p id="para3">asdf</p>
Javascript:
window.onload = function(){
var current = 0;
var ids = ['para1', 'para2', 'para3'];
window.setInterval(function(){
current = (current + 1) % 3;
for (var i = 0; i < ids.length; i++) {
document.getElementById(ids[i]).style.fontSize = (i == current ? '10px' : '8px');
}
}, 3000);
};
Try this:
<div>
<p id="p1">Para1 </p>
<p id="p2">Para2 </p>
</div>
$(function() {
var pa1 = 20, pa2 = 8, pa3;
$('#p1').css('fontSize', pa1);
$('#p2').css('fontSize', pa2);
function fstyle() {
pa3 = pa1;
pa1 = pa2;
pa2 = pa3;
$('#p1').css('fontSize', pa1);
$('#p2').css('fontSize', pa2);
}
setInterval(fstyle, 3000);
});

How can I loop through table rows to toggle the display style?

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

Categories

Resources