Display number characters left to reach maxlength of a telerik:RadTextBox - asp.net

My asp .net web application requires a telerik:RadTextBox that can accept 160 characters max. Every time a character is entered into this textbox, I want the number of remaining characters that i can type to be displayed near this textbox as a label.Can anyone tell me which event should i make use of and provide javascript code to implement this?

I have done something similar to this with a series of user controls that have text boxes in them. I would recommend using the onkey up and onkey down events to increase/lower your counter.
This is the javascript that we use.
<script type="text/javascript" language="Javascript">
//Character count script!
function textCounter(field, countfield, maxlimit) {
if (countfield == null) { return; }
if (field.value.length > maxlimit)
field.value = field.value.substring(0, maxlimit) + " Characters Remaining";
else
countfield.value = maxlimit - field.value.length + " Characters Remaining";
}
</script>
Here is something similar to the text box with the counter field below it.
<telerik:RadTextBox ID="txtTextBox" runat="server" />
<input readonly="readonly" enableviewstate ="false" type="text" runat="server" id="charCount" size="25" name="charCount" tabindex="-1" value=""
style="border: solid 0px white; display:none; background: white; font-size: 11px; color: #FF0000; text-align: right; float:right" />
The attributes are added onLoad if there is a maxlength for the textbox.
txtTextBox.Attributes.Item("onblur") = charCount.ClientID + ".style.display='none';"
txtTextBox.Attributes.Item("onfocus") = charCount.ClientID + ".style.display='block';"
txtTextBox.Attributes.Item("onkeyup") = "textCounter(this, " + charCount.ClientID + "," + myMaxLength.ToString + ");"
txtTextBox.Attributes.Item("onkeydown") = "textCounter(this, " + charCount.ClientID + "," + myMaxLength.ToString + ");"
When all this is combined it will shoe up the counter if you have set a max limit on it, only when that text box has focus. Once the focus is gone the script onblur hides the text box again. The counter is fired on the onkeyup and onkeydown so the count will stay accurate. It will count backwards to 0 and once it reaches 0 the user will not be able to enter more text.

here are some hints on your questions:
In order to count the number of characters and exclude line breaks, you can use the following:
<telerik:RadTextBox ID="RTB1" runat="server" TextMode="MultiLine" ClientEvents-OnKeyPress="KeyPress" />
<script type="text/javascript">
function KeyPress(sender, args)
{
var text;
if ($telerik.isIE || args.get_domEvent().rawEvent.keyCode == 0 || args.get_domEvent().rawEvent.keyCode == 13) // 13 : Enter key
{
text = escape(sender.get_value() + args.get_keyCharacter());
}
else
{
text = escape(sender.get_value());
}
while (text.indexOf("%0D%0A") != -1) // IE
{
text = text.replace("%0D%0A", " ");
}
while (text.indexOf("%0A") != -1)
{
text = text.replace("%0A", " ");
}
while (text.indexOf("%0D") != -1)
{
text = text.replace("%0D", " ");
}
var calculatedLength = unescape(text).length;
if (args.get_domEvent().rawEvent.keyCode == 8 && calculatedLength > 0) // 8 : backspace
{
calculatedLength -= 1;
}
document.title = calculatedLength;
}
</script>
This way you can do this.
Even you can check http://www.telerik.com/community/forums/aspnet-ajax/input/counting-characters.aspx for more details.
Thanks,

Use the onFocus client side event:
Eg.
textBox1.Attributes.Add("onFocus", "Counter('textBox1','LabelID',160)");
<script>
function Counter(textboxID, LabelID, MaxCharacters) {
var count = MaxCharacters - document.getElementById(textboxID).value.length;
document.getElementById(LabelID).innerHTML = count;
}
</script>

Related

Making a button that shows or hides multiple images in a random location

I have a problem when I am making the website for one gallery.
I made the code for the button that can show and hide multiple images.
I intend to make the button can place several images in randomly.
I write the code that can function for only one image.
Please tell me the code that functions as a button to place multiple images in a random location.
Users can hide images by pressing the button.
And when users press the button again, it places the images in another random location.
const btn = document.querySelector("button");
const height = document.documentElement.clientHeight;
const width = document.documentElement.clientWidth;
const box = document.getElementById("color");
btn.addEventListener("click", () => {
let randY = Math.floor((Math.random() * height) + 1);
let randX = Math.floor((Math.random() * width) + 1);
box.style.top = randY + "px";
box.style.right = randX + "px";
});
function showhide() {
var x = document.querySelectorAll("#color");
var i;
for (i = 0; i < x.length; i++) {
if (x[i].style.display === "block") {
x[i].style.display = "none";
} else {
x[i].style.display =
"block";
}
}
}
body {
height: 500px;
}
.random {
position: absolute;
}
<button onclick="showhide()" value="Zeige Features" id="button">click me</button>
<img id="color" style="display: none;" class="random" src="http://lorempixel.com/200/200/">
<img id="color" style="display: none;" class="random" src="http://lorempixel.com/200/200/">
You're doing the correct thing in showHide() when using querySelectorAll. You are then able to get all images.
You should never have elements with the same ids. They should be unique. So querySelectorAll("#color") works, but it's now how you should do. Do a querySelector on "img.random" instead.
getElementById only returns a single element, not like querySelectorAll. So you need to use querySelectorAll('img.random').
This might be beyond your knowledge, I don't think you should add the images in HTML, but in javascript code.
a) Add all image paths in an array: ['https://image.com/image.png', ...]
b) Add a single img element. <img id="template" class="random">
c) In javascript code, clone that element for each image path in the array. You can use cloneNode for this.
d) Randomize each position for each element, just like you have done now.
e) Add each element to the DOM through appendChild. Have a unique div that you append to. Be sure to clear it every time second time you hit the button.
f) Solve all bugs along the way. :P
The problem
The main issue here is that you're using getElementById to query #color
const box = document.getElementById("color");
Since getElementById only returns one element (but you have two in your DOM) and the style only applies to one element. That's why you're seeing only one element is randomly moving and the other just stay in the same place.
A side note here, id should be unique in a DOM.
You're in fact using the correct API for the job in the showhide function
var x = document.querySelectorAll("#color");
The fix:
To fix this, you need to query all images by their classname (as suggested in the side note, don't use id for the job)
const boxes = document.querySelectorAll(".random");
Now we have a node list, as you do in the showhide function, we need to loop thru it, I'm not using a for loop here, instead, a forEach loop, it's just more terser and a modern addition to the JS
// Since boxes are not array, we need to covert it to array so we can use that handy `.forEach` here:
Array.from(boxes).forEach(box => {
box.style.top = Math.floor((Math.random() * height) + 1) + "px";
box.style.right = Math.floor((Math.random() * width) + 1) + "px";
})
Now, this should fix your issue. See the complete code below.
const btn = document.querySelector("button");
const height = document.documentElement.clientHeight;
const width = document.documentElement.clientWidth;
const boxes = document.querySelectorAll(".random");
btn.addEventListener("click", () => {
Array.from(boxes).forEach(box => {
box.style.top = Math.floor((Math.random() * height) + 1) + "px";
box.style.right = Math.floor((Math.random() * width) + 1) + "px";
})
});
function showhide() {
var x = document.querySelectorAll(".random");
var i;
for (i = 0; i < x.length; i++) {
if (x[i].style.display === "block") {
x[i].style.display = "none";
} else {
x[i].style.display =
"block";
}
}
}
body {
height: 500px;
}
.random {
position: absolute;
}
<button onclick="showhide()" value="Zeige Features" id="button">click me</button>
<img id="color" style="display: none;" class="random" src="http://lorempixel.com/200/200/">
<img id="color" style="display: none;" class="random" src="http://lorempixel.com/100/100/">

How do if I want to make a randomize colors but with a couple set I've made with onload methode while randomizing of an occcur?

Hy, I want to make different colors every single time the page has called or opened and with the couple set I've made at the table with the different personalisation of rows color. How do I make it true ??? This line of the CSS code I've try to achieves to make some goals :
I do try with the Math methode to get random some colors but I'd stuck with it. because it won't personalisation of couple set of colors. See the code I've made with javascript at the below this :
---------------------------------------------------------- GS -----------------------------------------------------------------
function randomColor(customColorsArray, takenColorsArray) {
var text = "",
colors = ["orange", "yellow", "red", "maroon"];
if (customColorsArray && takenColorsArray) {
var text = "["+colors+"]";
}
else if (!customColorsArray && !takenColorsArray) {
text += colors[Math.floor(Math.random() * colors.length)];
}
else {
text += customColorsArray[Math.floor(Math.random() * customColorsArray.length)];
};
return text;
}
function personalRandomColor(e, customColor1, customColor2, customColor3, customColor4) {
var text = "";
if (!customColor1) {
if (e == "orange") {text += "white";}
else if (e == "red") {text += "blue";}
else if (e == "yellow") {text += "magenta";}
else if (e == "maroon") {text += "almond";};
} else {
if (e == "orange") {text += customColor1;}
else if (e == "yellow") {text += customColor2;}
else if (e == "red") {text += customColor3;}
else if (e == "maroon") {text += customColor4;};
};
return text;
}
function showTable() {
var s = SpreadsheetApp,
ss = s.getActiveSpreadsheet(),
sss = ss.getSheets(),
Html = HtmlService.createHtmlOutput(result)
.setSandboxMode(HtmlService.SandboxMode.IFRAME)
.setWidth(545)
.setHeight(500),
customColorsArrays = randomColor('passingClass', 'takenColor'),
randomFirstColor = 'yellow',
skipFirstColor = customColorsArrays.replace('yellow,', ''),
randomSecondColor = randomColor(toString(skipFirstColors)),
result = "<head>
<style type='text/css'>
.gridview {
display: inline-block;
border-collapse: collapse;
margin: 0px 4px 4px 0;
box-shadow: 3px 3px 4px #bbb;
}
.gridview, .gridview td {
margin: 0;
border: 1px solid #cccccc;
}
.gridview tr:nth-child(even) {
background-color: "+randomFirstColor+";
}
.gridview tr:nth-child(odd) {
background-color: "+randomSecondColor+";
}
.gridview td {
font-weight: normal;
text-align: left;
vertical-align: middle;
}
.gridview td {
padding: 4px 10px 5px 9px;
}
</style>
</head>
<table border=1 class='gridview'>";
for (var i = 0; i < sss.length; i++) {
result += "<tr>";
result += "<td>" + sss[i].getName() + "</td>";
result += "</tr>";
}
result += "</table>";
ss.toast(customColorsArrays+" & "+skipFirstColors+" & "+randomSecondColor, "Output Test", 50);
ss.show(Html.setTitle("Show the Table at PopUp"));}
}
What I want is if the table have reloaded always shows the different colors of rows everytime the page has opened and it must be set with my personalisation I've set. Please, have a look to personalRandomColor() function In this case I would like such as Orange just for nth-child(odd) and White for nth-child(even) at the First Random Open and Red for nth-child(odd) and Blue for nth-child(even) at the Second Random Open and that's so on ... and on ... and on again and again and always again but with the condition of skipping the first colors !!!
Try this:
var colors = ["#ccff99", "#e6ffb3", "#dfff80", "#ffffcc", "#ffff99", "#ffe6ff", "#ffcccc", "#ffcc99", "#ffe6b3", "#fff0b3"];
$(document).ready({
var randomFirstColor = rando(colors);//grab a random color
colors.splice(randomFirstColor.index, 1);//remove color from array so we don't risk picking it again. you can remove this line if you don't care whether the second color is the same as the first
$(".gridview tr:nth-child(odd)").css({backgroundColor: randomFirstColor.value});//style odd rows
$(".gridview tr:nth-child(even)").css({backgroundColor: rando(colors).value});//style even rows
});
You just have to import Randojs and jQuery by pasting the following in the head tag of your html document:
<script src="https://randojs.com/1.0.0.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
OR, to exclude jQuery, try:
var colors = ["#ccff99", "#e6ffb3", "#dfff80", "#ffffcc", "#ffff99", "#ffe6ff", "#ffcccc", "#ffcc99", "#ffe6b3", "#fff0b3"];
$(window).on("load", function(){
var randomFirstColor = rando(colors);//grab a random color
colors.splice(randomFirstColor.index, 1);//remove color from array so we don't risk picking it again. you can remove this line if you don't care whether the second color is the same as the first
var randomSecondColor = rando(colors);//grab another random color
var gridviews = document.getElementsByClassName("gridview");
for(var i = 0; i < gridviews.length; i++){//for each gridview...
var rows = gridviews[i].getElementsByTagName("tr");
for(var j = 0; j < rows.length; j++){//for each row in the gridview...
if(j % 2 == 0){
//style even
rows[j].style.backgroundColor = randomFirstColor.value;
}
else{
//style odd
rows[j].style.backgroundColor = randomSecondColor.value;
}
}
}
});
You just have to import Randojs by pasting the following in the head tag of your html document:
<script src="https://randojs.com/1.0.0.js"></script>
Now that you've updated your post, I can see a problem with your code. You are assigning a string to the "result" variable, but you are breaking that string across multiple lines, like this:
var result = "example
of
bad
formatting";
You should be beginning and ending the quote on each line and adding a plus sign between them to join them together, like so:
var result = "example" +
"of" +
"good" +
"formatting";
Once you get that fixed, make sure you put the html-string you've made into an element on the page and THEN call the random row color code I've given you.

CSS hover "through" element without blocking click

note: I do not have access to the HTML or javascript code
I am using the excellent Chrome plugin, Web Override, to improve usability on a vendor site my company uses. I am only looking for CSS solutions (or possibly js/jq scripts I can sideload).
I'm trying to set table rows to highlight on hover, which is easy enough:
#task-list-main-table tr:hover {
background-color: lightyellow;
}
The problem is that there is a little button that appears on each row when you hover over it. This means if I hover over the button, the corresponding row is not highlighted.
Good:
Bad:
I know I could use pointer-events:none but then I can no longer click on the button, which I need to be able to do.
So, is there any way in CSS to "pass through" hover events without affecting click events?
This is a pretty convoluted method, but if you have the ability to inject javascript, this function will check if your mouse is overlapping whatever element you supply as the selector.
https://jsfiddle.net/tr_santi/aegybp6n/8/
//Change this value to desired element
var hoverElement = "td";
//Change this value to the class you'd like to add when hovering
var addClass = "hover";
function getOffset( el ) {
var _x = 0;
var _y = 0;
while( el && !isNaN( el.offsetLeft ) && !isNaN( el.offsetTop ) ) {
_x += el.offsetLeft - el.scrollLeft;
_y += el.offsetTop - el.scrollTop;
el = el.offsetParent;
}
return { top: _y, left: _x };
}
function hasClass(element, cls) {
return (' ' + element.className + ' ').indexOf(' ' + cls + ' ') > -1;
}
function overlapListener(element, x, y, classToAdd) {
var eTop = getOffset(element).top;
var eLeft = getOffset(element).left;
var eBottom = eTop + element.clientHeight;
var eRight = eLeft + element.clientWidth;
if (x <= eRight && x >= eLeft && y <= eBottom && y >= eTop) {
if (!hasClass(element, classToAdd)) {
element.className = classToAdd;
}
} else {
if (hasClass(element, classToAdd)) {
element.className = "";
}
}
}
var elementList = document.querySelectorAll(hoverElement);
document.onmousemove=function(e){
[].forEach.call(elementList, function(b) {
overlapListener(b, e.clientX, e.clientY, addClass)
});
};
I'm sure there are some JS gurus around here that could write you something a bit less obfuscated, however I found this to be a good practice exercise for myself. I chose to write it in vanilla JS as I'm unsure of what your limitations are, although JQuery could substantially reduce the amount of needed code.

Make text in select element wrap when too long?

I have a select list where the text within the options is too long as is getting cropped. Is it possible to make the text wrap instead so that all of it is visible?
http://jsfiddle.net/W4KG7/
<select>
<option>This is option 1</option>
<option>This is option 2</option>
</select>
select {
width: 92px;
}
select {
width: 92px;
white-space:pre-wrap;
}
This only appears to work in Google Chrome.
https://developer.mozilla.org/en-US/docs/Web/CSS/white-space
It seems there is no way to accomplish this in Firefox without reinventing the wheel.
The solution I have come up with achieves this for other browsers, and uses an ellipsis in Firefox:
select {
max-width: 100%;
white-space: normal;
/* For Firefox: */
text-overflow: ellipsis;
}
Using CSS to do this will only work in Chrome...
You can't do it just by using CSS, but you can use some jQuery for
a "look like" solution.
As you can see it behaves like you wanted - I'm wrapping the select box with a DIV
and adding another one that will overlap the select box - he takes the select box fixed width minus
the button of the select box. Now I'm assigning to this div the same appearance as the select box +
The selected value.
Every time the select box will be changed the new value will be set in the mask we created and
the calculated new height will be set to the select box to.
Here is the jQuery code:
$(function(){
var mYbrowser = detectBrows();
console.log(mYbrowser[0]);
$('select').each(function(index,ele){
//get current style and fixed width:
var renderWidth = $(ele).outerWidth();
var renderWidthFixed = renderWidth;
var borderstyle = $(ele).css("border-bottom-style");
var bordercolor = $(ele).css("border-bottom-color");
var borderwidth = $(ele).css("border-bottom-width");
var font = $(ele).css("font");
var defaultValue = $(ele).val();
if (borderwidth == "0px") { borderwidth = "1px"; /*FF*/ }
$(ele).css({ cursor:"pointer" });
// set by browser (different buttons):
var borderRightParsed = borderwidth +" " + borderstyle + " " + bordercolor;
var topParsed = Math.round(parseInt(borderwidth.replace(/[^0-9\.]+/g,"")));
switch(mYbrowser[0]) {
case "MSIE": renderWidthFixed = renderWidth-28; break;
case "I": renderWidthFixed = renderWidth-28; break;
case "Chrome": renderWidthFixed = renderWidth-30; break;
case "Firefox":
renderWidthFixed = renderWidth-27;
borderRightParsed= "0";
if (index > 0) topParsed++;
break;
}
//wrap + add a overlapping layer that will hide content and calculate the correct height:
$(ele).wrap($('<div />').css({width:renderWidth, margin:0, padding:0, position:"relative"}));
$(ele).after($("<div>" + defaultValue + "</div>")
.css({
minHeight:20,
padding:"5px 0px 5px 8px",
width:renderWidthFixed,
backgroundColor:"white",
whiteSpace:"pre-wrap",
position:"absolute",
borderRight:borderRightParsed,
top:topParsed,
cursor:"default",
left:borderwidth,
font:font
})
);
//set select box new height:
setHeight(ele);
//append change behavior:
$(ele).change(function(){
$(ele).next('div').text($(ele).val());
setHeight(ele);
});
});
function setHeight(ele) {
var newHeight = $(ele).next('div').outerHeight();
$(ele).height(newHeight);
}
function detectBrows(){
var ua= navigator.userAgent, tem,
M= ua.match(/(opera|chrome|safari|firefox|msie|trident(?=\/))\/?\s*(\d+)/i) || [];
if(/trident/i.test(M[1])){
tem= /\brv[ :]+(\d+)/g.exec(ua) || [];
return 'IE '+(tem[1] || '');
}
if(M[1]=== 'Chrome'){
tem= ua.match(/\bOPR\/(\d+)/)
if(tem!= null) return 'Opera '+tem[1];
}
M= M[2]? [M[1], M[2]]: [navigator.appName, navigator.appVersion, '-?'];
if((tem= ua.match(/version\/(\d+)/i))!= null) M.splice(1, 1, tem[1]);
return M;
}
});
Its simple and not complicated - the problem is that the select box element behave
and look different on each browser.
I added a small quick function to detect which browser is used and fine tuning his
unique values.
This method can be Improved but that's a good starting point.
Shlomo

contenteditable iframe editable height limit

I'm using the yui editor. I want to know if it possible to limit the editable height area.
ex: height:300px, so over 300px, the carret stop writting.
thanks
html:
<textarea id="countMe" cols="30" rows="5"></textarea>
<div class="theCount">Lines used: <span id="linesUsed">0</span><div>js:
$(document).ready(function(){
var lines = 10;
var linesUsed = $('#linesUsed');
$('#countMe').keydown(function(e) {
newLines = $(this).val().split("\n").length;
linesUsed.text(newLines);
if(e.keyCode == 13 && newLines >= lines) {
linesUsed.css('color', 'red');
return false;
}
else {
linesUsed.css('color', '');
}
});
});
You can do some code on your editor panel when user enter characters & calculate length and return false if limit exceeds.
This is a simple jQuery that can work on iExplorer, Firefox and Crome:
$('#my_frame').load(function () {
$(this).height($(this).contents().find("html").height()+20);
});
I add 20 pixels just to avoid any scroll bar, but you may try a lower bound.

Resources