Can anyone simplify my code please, this work on my page, but when I checked on Google Developer tool console, I got this error:
Uncaught TypeError: Cannot read property 'length' of undefined
Below code:
<asp:TextBox ID="txtCounter" runat="server" Width="250px" TextMode="MultiLine"></asp:TextBox>
<SPAN id="chars"></SPAN>
<script>
$(document).ready(function () {
var char2 = ($(this).find('textarea[id$=txtCounter]').val().length);
if (char2 == 0) {
$('#chars').text("100 Maximum characters"); }
else {
$('#chars').text( char2 + " Characters Remaining"); }
textchar();
});
function textchar() {
$('textarea[id$=txtCounter]').on('keyup keydown change',
function (){
var limit = 100;
var lengthtxt = $(this).val().length;
if (lengthtxt >= limit)
{ this.value = this.value.substring(0, limit); lengthtxt = limit; }
$('#chars').text((limit - lengthtxt) + " Characters Remaining")
});
};
</script>
You problem is with this line:
$('textarea[id$=txtCounter]').on('keyup keydown change',
txtCounter is not the client ID of your textarea control when rendered to the client. View your page source to find the client ID, or use:
$('textarea[id$=<%= txtCounter.ClientID %>]').on('keyup keydown change',
Here's my working example using a simple textarea:
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<script src="./jquery-1.6.4.min.js" type="text/javascript"></script>
</head>
<textarea ID="txtCounter" Width="250px"></textarea>
<SPAN id="chars"></SPAN>
<script language="javascript" type="text/javascript">
$(document).ready(function () {
var char2 = ($(this).find('textarea[id$=txtCounter]').val().length);
if (char2 == 0) {
$('#chars').text("100 Maximum characters");
}
else {
$('#chars').text( char2 + " Characters Remaining");
}
textchar();
});
function textchar() {
$('textarea[id$=txtCounter]').bind('keyup keydown change', function (){
var limit = 100;
var lengthtxt = $(this).val().length;
if (lengthtxt >= limit){
this.value = this.value.substring(0, limit);
lengthtxt = limit;
}
$('#chars').text((limit - lengthtxt) + " Characters Remaining");
});
}
</script>
</html>
Related
I'm facing a problem when the same code at the .cshtml change to .aspx can't run in visual studio. How should I change any format or the coding for the run at .aspx? This a chatroom coding
#section scripts
{
<script src="~/Scripts/jquery.signalR-2.4.0.min.js"></script>
<script type="text/javascript" src="~/signalr/hubs"></script>
<script type="text/javascript">
$(function () {
var $chats = $('#chats'),
chatHub = $.connection.chatHub;
chatHub.client.gotMessage = function (nickname, message) {
$chats.append('<li><span class="label label-primary">' + htmlEncode(nickname)+'</span>' + htmlEncode(message));
$chats.scrollTop($chats.innerHeight());
};
var htmlEncode = function (content) {
return $('<div />').text(content).html();
}
$.connection.hub.start().done(function () {
$("#ctrl button").click(function (evt) {
var $name = $("#nickname"),
name = $name.val(),
$message = $("#message"),
message = $message.val();
chatHub.server.sendMessage(name, message);
$message.val("").focus();
});
});
$(window)
.resize(function () {
var h = Math.max(200, screen.availHeight - $chats.offset().top - 200);
$chats.height(h);
})
.resize();
});
</script>
}
There is no tag called section in ASP.NET webforms. So basically you could just remove the section tag.
In webforms you can use ContentPlaceholders like this, Masterpage:
<asp:ContentPlaceHolder id="scripts" runat="server">
</asp:ContentPlaceHolder>
And in any site using the masterpage:
<asp:Content ID="Content1" ContentPlaceHolderID="scripts" Runat="Server">
<script src="~/Scripts/jquery.signalR-2.4.0.min.js"></script>
<script type="text/javascript" src="~/signalr/hubs"></script>
<script type="text/javascript">
$(function () {
var $chats = $('#chats'),
chatHub = $.connection.chatHub;
chatHub.client.gotMessage = function (nickname, message) {
$chats.append('<li><span class="label label-primary">' + htmlEncode(nickname)+'</span>' + htmlEncode(message));
$chats.scrollTop($chats.innerHeight());
};
var htmlEncode = function (content) {
return $('<div />').text(content).html();
}
$.connection.hub.start().done(function () {
$("#ctrl button").click(function (evt) {
var $name = $("#nickname"),
name = $name.val(),
$message = $("#message"),
message = $message.val();
chatHub.server.sendMessage(name, message);
$message.val("").focus();
});
});
$(window)
.resize(function () {
var h = Math.max(200, screen.availHeight - $chats.offset().top - 200);
$chats.height(h);
})
.resize();
});
</script>
</asp:Content>
I'm trying to implement a websocket-server with Progress OpenEdge. I still didn't get it working.
I've successfully created a socket-server with the example i-sktsv1.p from here.
When I run my html-page, which looks like:
<!DOCTYPE html>
<html lang="en">
<meta charset="utf-8" />
<title>WebSocket Client</title>
<script language="javascript" type="text/javascript">
var wsUri = "ws://localhost:3333/";
var output;
function init() {
output = document.getElementById("output");
testWebSocket();
}
function testWebSocket() {
websocket = new WebSocket(wsUri);
websocket.onopen = function(evt) { onOpen(evt) };
// websocket.onclose = function(evt) { onClose(evt) };
websocket.onmessage = function(evt) { onMessage(evt) };
websocket.onerror = function(evt) { onError(evt) };
}
function onOpen(evt) {
writeToScreen("CONNECTED");
doSend("WebSocket rocks");
}
function onClose(evt) {
writeToScreen("DISCONNECTED");
}
function onMessage(evt) {
writeToScreen('<span style="color: blue;">RESPONSE: ' + evt.data+'</span>');
websocket.close();
}
function onError(evt) {
writeToScreen('<span style="color: red;">ERROR:</span> ' + evt.data);
}
function doSend(message) {
writeToScreen("SENT: " + message);
websocket.send(message);
}
function writeToScreen(message) {
var pre = document.createElement("p");
pre.style.wordWrap = "break-word";
pre.innerHTML = message;
output.appendChild(pre);
}
window.addEventListener("load", init, false);
</script>
<body>
<h2>WebSocket Test</h2>
<div id="output"></div>
</body>
</html>
I getting a error that the websocket connection could not be established.
The problem is (I think) that Progress offers a socket, not a websocket. Do you know how to get this working?
I
I have created a text counter to tell the user how many characters of they have typed and how many they have remaining available. This should show when the text area has focus and disappear then the text area loses focus.
I have created a binding handler that uses an extender to extend the observable object that is being passed into it. The problem is that it works only after entering text, navigating off of the text area, and then navigating back to the text area.
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title></title>
</head>
<body>
<div class="question" >
<label for="successes" data-textkey="successes">This is a question</label>
<textarea data-bind="textCounter: successes, hasFocus: successes.hasFocus, maxLength:200, event: { keyup:successes.updateRemaining }"></textarea>
<div class="lengthmessage edit" data-bind="visible:successes.hasFocus()">
<div >
<em>Length:</em> <span data-bind="text:successes.currentLength"></span>
<em>Remaining:</em> <span data-bind="text:successes.remainingLength"></span>
</div>
</div>
</div>
<script src="../Scripts/knockout-2.3.0.debug.js" type="text/javascript"></script>
<script type="text/javascript">
(function (ko) {
ko.extenders.textCounter = function (target, options) {
options = options || {};
options.maxLength = options.maxLength ? parseInt(options.maxLength) : 2000;
target.maxLength = ko.observable(options.maxLength);
target.currentLength = ko.observable(target().length);
target.remainingLength = ko.observable(target.maxLength() - target.currentLength());
target.hasFocus = ko.observable(false);
target.hasFocus.subscribe(function () {
target.currentLength(target().length);
target.remainingLength(target.maxLength() - target.currentLength());
});
target.updateRemaining = function (data, event) {
if (event.target == undefined && event.srcElement.value == "") {
target.currentLength(0);
}
else {
var e = $(event.target || event.srcElement);
target.currentLength(e.val().length);
if (target.currentLength() > target.maxLength()) {
e.val(e.val().substr(0, target.maxLength()));
target.currentLength(target.maxLength());
}
}
target.remainingLength(target.maxLength() - target.currentLength());
};
return target;
};
ko.bindingHandlers.textCounter = {
init: function (element, valueAccessor, allBindingsAccessor, viewModel) {
var val = ko.utils.unwrapObservable(valueAccessor());
var observable = valueAccessor();
observable.extend({ textCounter: allBindingsAccessor() });
ko.applyBindingsToNode(element, {
value: valueAccessor()
});
},
update: function (element, valueAccessor, allBindingsAccessor, viewModel) {
var val = ko.utils.unwrapObservable(valueAccessor());
var observable = valueAccessor();
ko.bindingHandlers.css.update(element, function () { return { hasFocus: observable.hasFocus }; });
}
};
var viewModel = function () {
this.successes = ko.observable("");
//this.successes.hasFocus = ko.observable();
}
ko.applyBindings(new viewModel());
} (ko));
</script>
</body>
</html>
If I uncomment:
//this.successes.hasFocus = ko.observable();
The page will behave the way that I want it to, from the very beginning, but it defeats the whole purpose of using the extender since my view model now has one of the objects from the extender in it.
I have got to believe that there is something relatively simple that I am missing here.
Thanks for your help..
The issue is that hasFocus has not been defined when the binding string here is parsed:
<textarea data-bind="textCounter: successes, hasFocus: successes.hasFocus, maxLength:200, event: { keyup:successes.updateRemaining }"></textarea>
So, when the binding string is parsed successes.hasFocus is undefined.
One option would be to apply the hasFocus binding inside of your textCounter binding after your hasFocus property is available.
Also, in Knockout 3.0 (released today), the parsing of the binding string happens when the value is accessed in the binding itself. So, your code actually works property in KO 3.0 already.
I would not like to call asp.net server side code with jquery $.ajax .
So I have written a pure javascript ajax file .But when I call webmethod,this do not work.
Can anyony help me out how correct this? THANK you very much .
ajax.js:
var ajax = {
_params: null,
_callback: null,
_xhr: null,
_createXHR: function () {
if (window.ActiveXObject) {
_xhr = new ActiveXObject("Microsoft.XMLHTTP"); //IE
}
else if (window.XMLHttpRequest) {
_xhr = new XMLHttpRequest(); //FireFox,Chrome et.
}
},
_ajaxcallback: function () {
if (_xhr.readyState == 4) {
if (_xhr.status == 200) {
_callback.call(this, _xhr.responseText)
}
}
},
_changeParams: function () {
var args = arguments[0];
var s = "";
for (var i in args) {
s += "&" + i + "=" + args[i];
}
_params = s;
},
get: function (url, params, callback) {
_callback = callback;
ajax._createXHR();
ajax._changeParams(params);
if (null != _xhr) {
_xhr.open('get', url + '?' + _params, true);
_xhr.onreadystatechange = ajax._ajaxcallback;
_xhr.send();
}
},
post: function (url, params, callback) {
_callback = callback;
ajax._createXHR();
ajax._changeParams(params);
if (null != _xhr) {
_xhr.open('post', url, true);
_xhr.onreadystatechange = ajax._ajaxcallback;
_xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
_xhr.send(_params);
}
}
}
WebForm1.aspx
<head runat="server">
<title></title>
<script src="ajax.js" type="text/javascript"></script>
<script type="text/javascript">
function ajaxtest() {
var uid = document.getElementById("txtuid").value;
var pwd = document.getElementById("txtpwd").value;
ajax.post("WebForm1.aspx/GetModel", "{ 'uid':" + uid + ", 'pwd':" + pwd + " }", function (data) {
alert(data);
});
}
</script>
</head>
<body>
<form id="form1" runat="server">
<div>
<input type="text" id="txtuid" value="eeee" />
<input type="text" value="222" id="txtpwd" onblur="ajaxtest()"/>
WebForm1.cs:
[WebMethod]
public static string GetModel(string uid,string pwd)
{
return "1";
}
In your markup you need to have a ScriptManager with EnablePageMethods set to true. Doing this will ensure you can call the methods you have marked up with [WebMethod].
In your JavaScript you can then call your method like this: PageMethods.GetModel("userName", "password", OnSuccessMethod, OnFailureMethod); - you won't need any of the ActiveXObject/XmlHttpRequest stuff if you do it this way, which keeps things much simpler.
Use AJAX.PRO from Michael Schwarz --> http://www.ajaxpro.info/
I'm trying to use the jqueryUI combobox into my asp.net 3.5 webforms application. I've added a dropdownlist and modified it style with jquery. The problem i got is when i try to execute the postback the dropdown normally does when it selected item it's changed. The combobox doesn't change it's value and I'm getting the error that _dopostback is not defined in my firebug error console. I've been reading about this here and in and in in the asp.net forums, and found some answers that told me that should give a try to the GetPostBackEventReference method, but still nothing has happened. Below is the code, thanks.
<script type="text/javascript">
(function ($) {
$.widget("ui.combobox", {
_create: function () {
var input,
self = this,
select = this.element.hide(),
selected = select.children(":selected"),
value = selected.val() ? selected.text() : "",
wrapper = $("<span>")
.addClass("ui-combobox")
.insertAfter(select);
input = $("<input>")
.appendTo(wrapper)
.val(value)
.addClass("ui-state-default")
.autocomplete({
delay: 0,
minLength: 0,
source: function (request, response) {
var matcher = new RegExp($.ui.autocomplete.escapeRegex(request.term), "i");
response(select.children("option").map(function () {
var text = $(this).text();
if (this.value && (!request.term || matcher.test(text)))
return {
label: text.replace(
new RegExp(
"(?![^&;]+;)(?!<[^<>]*)(" +
$.ui.autocomplete.escapeRegex(request.term) +
")(?![^<>]*>)(?![^&;]+;)", "gi"
), "<strong>$1</strong>"),
value: text,
option: this
};
}));
},
select: function (event, ui) {
ui.item.option.selected = true;
self._trigger("selected", event, {
item: ui.item.option
});
_doPostBack('<%= ddlModalities.UniqueID %>', "");
},
change: function (event, ui) {
if (!ui.item) {
var matcher = new RegExp("^" + $.ui.autocomplete.escapeRegex($(this).val()) + "$", "i"),
valid = false;
select.children("option").each(function () {
if ($(this).text().match(matcher)) {
this.selected = valid = true;
$(select).change();
return false;
}
});
if (!valid) {
// remove invalid value, as it didn't match anything
$(this).val("");
select.val("");
input.data("autocomplete").term = "";
return false;
}
}
}
})
.addClass("ui-widget ui-widget-content ui-corner-left");
input.data("autocomplete")._renderItem = function (ul, item) {
return $("<li></li>")
.data("item.autocomplete", item)
.append("<a>" + item.label + "</a>")
.appendTo(ul);
};
$("<a>")
.attr("tabIndex", -1)
.attr("title", "Show All Items")
.appendTo(wrapper)
.button({
icons: {
primary: "ui-icon-triangle-1-s"
},
text: false
})
.removeClass("ui-corner-all")
.addClass("ui-corner-right ui-button-icon")
.click(function () {
// close if already visible
if (input.autocomplete("widget").is(":visible")) {
input.autocomplete("close");
return;
}
// work around a bug (likely same cause as #5265)
$(this).blur();
// pass empty string as value to search for, displaying all results
input.autocomplete("search", "");
input.focus();
});
},
destroy: function () {
this.wrapper.remove();
this.element.show();
$.Widget.prototype.destroy.call(this);
}
});
})(jQuery);
$(function () {
$("#<%=ddlModalities.ClientID %>").combobox();
});
</script>
<div class="ui-widget">
<asp:DropDownList runat="server" ID="ddlModalities" Width="150px" AutoPostBack="True"
DataSourceID="odsModalitiesNoWorklist" DataTextField="Ae" DataValueField="Id"
CssClass="ddlStandardWidth" OnDataBound="ddlModalities_DataBound" OnSelectedIndexChanged="ddlModalities_SelectedIndexChanged" />
</div>
It looks like you're calling "_doPostBack". However, the ASP.NET-generated function is "__doPostBack" - there are two "_" characters at the beginning, not just one. That could be the cause of your "function not defined" error.