I'm trying to display a bunch of divs that are rendered to look like vertical and horizontal lines. While the code technically works, it doesn't work consistently. On the first page load, only one line may show, and on the next an entirely different one may show, or they'll all show. I'm testing this on IE8 and IE9 with the same problem, and am a bit lost at this point.
I'm using ScriptManager.RegisterStartupScript(this, GetType(), "linesCode", script, false); to register the script, but it does the same thing using the old RegisterStartupScript(key, string) method.
Code that is being registered, pulled from the browsers' "View Source":
<script type="text/javascript">
$(document).ready(function () {
drawLineVertical('MainContent_1_ClauseRowDefaultTable', 'MainContent_3_AddRowTable', 2, 30);
drawLineHorizontal('MainContent_1_ClauseRowDefaultTable', 'MainContent_2_ConditionRowTable', 2, 40);
drawLineHorizontal('MainContent_1_ClauseRowDefaultTable', 'MainContent_3_AddRowTable', 2, 30);
});
</script>
Code that is being processed (most of this was found in an old blog post):
function drawLineVertical(id1, id2, wid, offset) {
var obj1 = document.getElementById(id1);
var obj2 = document.getElementById(id2);
var obj1Pos = GetCoordinates(obj1);
var obj2Pos = GetCoordinates(obj2);
var id = 'line_' + new Date().getTime();
var line = "<div id=\"" + id + "\" class=\"line\"></div>";
$('body').append(line);
$('#' + id).css({
left: obj1Pos.x,
top: obj1Pos.y,
height: ((obj2Pos.y - obj1Pos.y) + offset),
width: wid,
position: 'absolute',
background: '#c2c5d1',
backgroundcolor: '#c2c5d1'
});
}
function drawLineHorizontal(id1, id2, h, offset) {
var obj1 = document.getElementById(id1);
var obj2 = document.getElementById(id2);
var obj1Pos = GetCoordinates(obj1);
var obj2Pos = GetCoordinates(obj2);
var id = 'line_' + new Date().getTime();
var line = "<div id=\"" + id + "\" class=\"line\"></div>";
$('body').append(line);
$('#' + id).css({
left: obj1Pos.x,
top: (obj2Pos.y + offset),
height: h,
width: obj2Pos.x - obj1Pos.x,
position: 'absolute',
background: '#c2c5d1',
backgroundcolor: '#c2c5d1'
});
}
function GetCoordinates(obj) {
var pos = {};
pos.x = obj.offsetLeft;
pos.y = obj.offsetTop;
while (obj.offsetParent) {
pos.x = pos.x + obj.offsetParent.offsetLeft;
pos.y = pos.y + obj.offsetParent.offsetTop;
if (obj == document.getElementsByTagName("body")[0]) {
break;
}
else {
obj = obj.offsetParent;
}
}
return pos;
}
Any input is greatly appreciated.
Related
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);
}
ok what im trying to do here is the following
private void addgsc()
{
if (File.Exists(hud))
{
{
string s = " itemDef\n\r"
+ "{"
+ " name \"zombiecounter\"\n\r"
+ " rect 100 70 0 0 HORIZONTAL_ALIGN_CENTER VERTICAL_ALIGN_BOTTOM\n\r "
+ " textscale .5\n\r"
+ " textstyle ITEM_TEXTSTYLE_SHADOWED\n\r"
+ " textfont UI_FONT_OBJECTIVE\n\r"
+ " textalign ITEM_ALIGN_CENTER\n\r"
+ " forecolor 1 0 0 1\n\r"
+ " exp text (\"Zombies Left: \" + dvarInt(\"zombie_counter\"))\n\r"
+ " visible when (dvarInt(\"zombie_counter\") > 0);\n\r"
+ "decoration\n\r"
+ "} ";
string file = hud;
List<string> lines = new List<string>(System.IO.File.ReadAllLines(file));
int index = lines.FindLastIndex(item => item.Contains("playerscores"));
if (index != -1)
{
lines.Insert(index + 1, s);//""
}
System.IO.File.WriteAllLines(file, lines);
MessageBox.Show("done");
}
}
and im looking for a line in a code like this
itemDef
{
name "playerscores"
rect 0 0 100 0
ownerdraw CG_COMPETITIVE_MODE_SCORES
visible 1
}
but what i want to do is find player scores then find the last } at the end and add it there because currently its adding it right under player scores but im not sure how i can get it to go to find that and then find the closest } one of those and add it under neath that so its in a new block not added into the player score one so would want something like the following
image 1
I'm a bit unclear of the desired output, so the below code may be more than what you need but should get you on the right track. Please forgive syntax errors.
EDIT: I reread the question a few times, and think this is what you are looking for.
var allLinesInFile = System.IO.File.ReadAllLines(file);
var isPlayerScore = false;
var linesToWrite = new List<string>();
var linesToAdd = new List<string> {
"itemDef\n\r",
"{",
" name \"zombiecounter\"\n\r",
//and so on
"}"
};
foreach (var line in allLinesInFile)
{
linesToWrite.Add(line);
if (line.IndexOf("playerscores", StringComparison.OrdinalIgnoreCase) >= 0)
{
//starting of data detected.
isPlayerScore = true;
}
else if (isPlayerScore == true && line.IndexOf("}") >= 0)
{
//end of data detected
isPlayerScore = false;
linesToWrite.AddRange(linesToAdd);
}
}
System.IO.File.WriteAllLines(file, linesToWrite);
MessageBox.Show("done");
Hopefully someone can help. I have a list of objects that i get from the DB.
I would like to on load, only add the first ten in the list to a CheckBoxlist. Then with the Next_click I would like to add the next ten and so on. If the user clicks Prev, I would like to add the previous 10. So essentially it is paging through a CheckBoxlist.
This is how i have tried it and didn't succeed, it doesn't throw any errors. Just doesn't do what i want it to do. I hope its possible.
On page load these are declared:
QuestionHandler quest = null;
protected List<QuestionView> questions = null;
int countP1 = 0;
int countP2 = 10;
This is the binddata method:
CheckBoxList1.Items.Clear();
questions = quest.GetQuestions();
List<string> display = new List<string>();
int c = 0;
foreach (QuestionView qsD in questions)
{
if (countP1.ToString().All(char.IsDigit) && countP2.ToString().All(char.IsDigit))
{
if (c >= countP1 && c <= countP2)
{
display.Add(qsD.QuestionID.ToString());
}
c++;
}
}
questions = null;
questions = new List<QuestionView>();
foreach(string s in display)
{
QuestionView q = new QuestionView();
q = quest.GetSelectQ(s);
questions.Add(q);
}
Then to add it to the checkboxlist(dont worry about the long string, its a premade table):
foreach (QuestionView qs in questions)
{
ListItem item1 = new ListItem();
item1.Text = "<table class=\"table\" style=\"border: 3px solid #8AC007;\"><tr><td>Title: </td><td width=\"300px\">" + qs.Title + "</td><td>|</td><td>Marks: </td><td width=\"300px\">" + qs.Mark + "</td><td>|</td><td>Type: </td><td width=\"300px\">" + qs.TypeID + "</td></tr><tr><td>Subject:</td><td>" + qs.SubjectID + "</td><td>|</td><td>Topic: </td><td>" + qs.TopicID + "</td><td>|</td><td>Rating: </td><td></td></tr></table>";
item1.Value = qs.QuestionID.ToString();
CheckBoxList1.Items.Add(item1);
}
The next click:
protected void btnNext_Click(object sender, EventArgs e)
{
countP1 = countP1 + 10;
countP2 = countP2 + 10;
BindData();
}
The prev click:
protected void btnPrev_Click(object sender, EventArgs e)
{
countP1 = countP1 - 10;
countP2 = countP2 - 10;
BindData();
}
Hopefully someone understands what i mean and can help, thank you in advance, feel free to ask me questions about this if you need to.
This is all in an update-panel.
Finally, this is how the checkboxlist looks when displayed:
You can use LINQ and the methods Take and Skip
const int size = 10; // How many questions you want to be returned.
public IEnumerable<QuestionView> GetQuestions(int page)
{
return questions.Skip(size * page).Take(size);
}
This will look at your QuestionView list, skip over 10 records * the page count, and then take the next 10 elements.
You may want to add some additional logic to ensure that the next set of elements requested does not exceed the QuestionView list limit.
From your comments:
For simplicity, you can put the method inside the class you're working with and can invoke it in the DataBinding method (Where you have the following code):
CheckBoxList1.Items.Clear();
questions = quest.GetQuestions();
var pagedQuestions = GetQuestions(1); // Make use of the new method.
For best practice, you should separate this out and put it somewhere that is related to the QuestionView. You could also put it as an extension to Question View (Extension method).
After the help from Darren this is the final code to make it work:
The bind data method to load up the page:
CheckBoxList1.Items.Clear();
questions = quest.GetQuestions();
int count = 0;
foreach (QuestionView qs in questions)
{
if(count<10) //stop it from displaying more than 10 on the first page
{
ListItem item1 = new ListItem();
item1.Text = "<table class=\"table\" style=\"border: 3px solid #8AC007;\"><tr><td>Title: </td><td width=\"300px\">" + qs.Title + "</td><td>|</td><td>Marks: </td><td width=\"300px\">" + qs.Mark + "</td><td>|</td><td>Type: </td><td width=\"300px\">" + qs.TypeID + "</td></tr><tr><td>Subject:</td><td>" + qs.SubjectID + "</td><td>|</td><td>Topic: </td><td>" + qs.TopicID + "</td><td>|</td><td>Rating: </td><td></td></tr></table>";
item1.Value = qs.QuestionID.ToString();
CheckBoxList1.Items.Add(item1);
}
count++;
}
The next click:
countP1++;
CheckBoxList1.Items.Clear();
questions = quest.GetQuestions();
var pagedQuestions = GetQuestions(countP1);
foreach (QuestionView qs in pagedQuestions)
{
ListItem item1 = new ListItem();
item1.Text = "<table class=\"table\" style=\"border: 3px solid #8AC007;\"><tr><td>Title: </td><td width=\"300px\">" + qs.Title + "</td><td>|</td><td>Marks: </td><td width=\"300px\">" + qs.Mark + "</td><td>|</td><td>Type: </td><td width=\"300px\">" + qs.TypeID + "</td></tr><tr><td>Subject:</td><td>" + qs.SubjectID + "</td><td>|</td><td>Topic: </td><td>" + qs.TopicID + "</td><td>|</td><td>Rating: </td><td></td></tr></table>";
item1.Value = qs.QuestionID.ToString();
CheckBoxList1.Items.Add(item1);
}
The prev click:
countP1--;
CheckBoxList1.Items.Clear();
questions = quest.GetQuestions();
var pagedQuestions = GetQuestions(countP1);
foreach (QuestionView qs in pagedQuestions)
{
ListItem item1 = new ListItem();
item1.Text = "<table class=\"table\" style=\"border: 3px solid #8AC007;\"><tr><td>Title: </td><td width=\"300px\">" + qs.Title + "</td><td>|</td><td>Marks: </td><td width=\"300px\">" + qs.Mark + "</td><td>|</td><td>Type: </td><td width=\"300px\">" + qs.TypeID + "</td></tr><tr><td>Subject:</td><td>" + qs.SubjectID + "</td><td>|</td><td>Topic: </td><td>" + qs.TopicID + "</td><td>|</td><td>Rating: </td><td></td></tr></table>";
item1.Value = qs.QuestionID.ToString();
CheckBoxList1.Items.Add(item1);
}
The count variable is initiated as 0 when the page loads.
I have some table & i need to calculate Column values.In my scenario i need to calculate Total Item Price 99 + 55 = 154 to Sub Total Row.In here my SubTotal Calculation not working.
My Code(part of my Table Creation)
$option.each(function () {
if ($(this).prop('selected')) {
var txtId = 'txtQty' + i;
var lblId = 'lblQty' + i;
var row = $('<tr><td>' + $(this).text() + '</td><td>' + $(this).attr('RetailPrice') + '</td><td>' + $(this).attr('WholesalePrice') + '</td><td>' + '<input type="text" id="' + txtId + '">' + '</td><td> <button type="button" class="btn btn-warning btn-xs btncalc">Calculate</button></td><td class="tot"><label for="tempprice" id="' + lblId + '"></label></td><td><img id="imgdel" src="../../Images/delete.png" alt="" onclick="deleteclick(this)" title="Delete" /></td></tr>');
table.append(row);
i++;
}
});
var row2 = $('<tr><td>' + "SubTotal" + '</td><td></td><td></td><td></td><td></td></tr>');
table.append(row2);
$('#product-load-tbl').append(table);
});
Calculation Part
$('.btncalc').live('click', function () {
debugger;
var row = $(this).parents("tr:first");
var rowval = $(row).find("td:eq(1)").html();
var inpval = $(row).find("td:eq(3) input").val();
if (inpval != null || inpval != 0) {
var result = (rowval * inpval);
}
else {
var result = 0;
}
$(row).find("td:eq(5)").html(result);
var lstrow = $(this).parents("tr:last"); // this sub total calculation not working
$.each($('.tot'), function (element) {
$(lastrow).find("td:eq(5)").html(element);
});
})
You can change this:
$.each($('.tot'), function (element) {
$(lastrow).find("td:eq(5)").html(element);
});
to this:
var total = 0; // intialise a var with value 0
$('.tot').each(function (i, element) { // loop the selected item in each row
total += +$(this).text(); // cast the string to integer and add it to total
});
$(lastrow).find("td:eq(5)").text(total); // then at last place the total
Short demo
And for a short note:
.live() is now removed from the latest jQuery versions, so if you are using version 1.7+ then you can move your code to .on() method to delegate the event. Syntax is something like this for event delegation:
$(static_parent).on(event, selector, callback);
$(static_parent) is the element which was available when the relative dom is ready and it was available at that time before appending any dynamic dom element in the page.
so in your case:
$('table_ID/Class').on('click', '.btncalc', function(){
//...all the stuff with .live goes here
});
I am using JQPlot to plot a chart on a page. I am plotting Line chart with marker points.
I want to change the color of the marker points.
I need each marker point to be in different color. Is it possible?
Thank you all in advance for your response.
Here is my code :
//In order to use keyboard highlight of the coordinates please click somewhere inside the Result frame.
$(document).ready(function() {
// Some simple loops to build up data arrays.
var cosPoints = [];
for (var i = 0; i < 2 * Math.PI; i += 2) {
cosPoints.push([i, Math.cos(i)]);
}
var plot3 = $.jqplot('chart', [cosPoints], {
cursor: {
show: true,
showTooltip: true,
showTooltipGridPosition: true,
// showTooltipDataPosition: false,
showTooltipUnitPosition: false,
useAxesFormatters: false,
// showVerticalLine : true,
followMouse: true
},
title: 'Line Style Options',
// Series options are specified as an array of objects, one object
seriesDefaults: {
markerRenderer: $.jqplot.MarkerRenderer,
markerOptions: {
color: 'red'
}
}
});
$('#chart').bind('jqplotDataClick', function(ev, seriesIndex, pointIndex, data) {
alert(data);
});
var counter = -1; //to start from the very first on first next click, on prev click it will start from last -- and this is how we want it
$('#buttonPrev').bind("click", function() {
counter--;
DoSomeThing(plot3);
});
$('#buttonNext').bind("click", function() {
counter++;
DoSomeThing(plot3);
});
$(document).keydown(function(e) {
if (e.keyCode == 37) {
$('#buttonPrev').click();
}
else if (e.keyCode == 39) {
$('#buttonNext').click();
}
});
function GetColors() {
var colors = ["red","blue","red","blue"];
return colors;
}
function DoSomeThing(plot) {
// *** highlight point in plot ***
//console.log(" sth "+ plot.series[0].data[1][1]);
var seriesIndex = 0; //0 as we have just one series
var data = plot.series[seriesIndex].data;
if (counter >= data.length) counter = 0;
else if (counter < 0) counter = data.length - 1;
var pointIndex = counter;
var x = plot.axes.xaxis.series_u2p(data[pointIndex][0]);
var y = plot.axes.yaxis.series_u2p(data[pointIndex][1]);
console.log("x= " + x + " y= " + y);
var r = 5;
var drawingCanvas = $(".jqplot-highlight-canvas")[0]; //$(".jqplot-series-canvas")[0];
var context = drawingCanvas.getContext('2d');
context.clearRect(0, 0, drawingCanvas.width, drawingCanvas.height); //plot.replot();
context.strokeStyle = "#000000";
context.fillStyle = "#FFFF00";
context.beginPath();
context.arc(x, y, r, 0, Math.PI * 2, true);
context.closePath();
context.stroke();
context.fill();
}
});
I'm not sure you can specify multiple colors for a single serie.
Either you can divide your serie into several series (ex. 4 series if you have a serie of 4 elements), and use seriesColors : myColorTab to specify different color for each series (thus for each of your elements) :
var myColorTab = new Array("#FF0000", "#384763", "#AA4312");
var plot3 = $.jqplot('chart(, [cos1, cos2, cos3], {
seriesColors : myColorTab
}
Please see working example here
P.S. : You can change the surely not-optimal way to push datas into cos1, cos2 and cos3.
EDIT
In order to change markerpoints back color, you can specify a color for each series :
series: [
{markerRenderer: $.jqplot.MarkerRenderer,
markerOptions: { color: 'red' }
},
{markerRenderer: $.jqplot.MarkerRenderer,
markerOptions: { color: 'blue' }
},
{markerRenderer: $.jqplot.MarkerRenderer,
markerOptions: { color: 'green' }
}
]
Please see edited JsFiddle here
Just Add seriesColors: ['#FFC526', '#C0504D', '#4BACC6', '#8064A2', '#9BBB59', '#F79646', '#948A54', '#4000E3'], above seriesDefaults in your code
I also needed to have different colored markers, and making separate series for each color really the way to go for me, so i made this pointRenderer:
$.jqplot.PointRenderer = function(){
$.jqplot.LineRenderer.call(this);
};
$.jqplot.PointRenderer.prototype = Object.create($.jqplot.LineRenderer.prototype);
$.jqplot.PointRenderer.prototype.constructor = $.jqplot.PointRenderer;
// called with scope of a series
$.jqplot.PointRenderer.prototype.init = function(options, plot) {
options = options || {};
this.renderer.markerOptionsEditor = false;
$.jqplot.LineRenderer.prototype.init.apply(this, arguments);
this._type = 'point';
}
// called within scope of series.
$.jqplot.PointRenderer.prototype.draw = function(ctx, gd, options, plot) {
var i;
// get a copy of the options, so we don't modify the original object.
var opts = $.extend(true, {}, options);
var markerOptions = opts.markerOptions;
ctx.save();
if (gd.length) {
// draw the markers
for (i=0; i<gd.length; i++) {
if (gd[i][0] != null && gd[i][1] != null) {
if (this.renderer.markerOptionsEditor) {
markerOptions = $.extend(true, {}, opts.markerOptions);
markerOptions = this.renderer.markerOptionsEditor.call(plot, this.data[i], markerOptions);
}
this.markerRenderer.draw(gd[i][0], gd[i][1], ctx, markerOptions);
}
}
}
ctx.restore();
};
The draw function is a stripped down version of the LineRenderer draw function, add the missing pieces from that function.