Restrict backspace in textbox Javascript [duplicate] - javascript

I have a textbox which is extended by an Ajax Control Toolkit calendar.
I want to make it so that the user cannot edit the textbox and will have to instead use the calendar extender for input.
I have managed to block all keys except backspace!
This is what I have so far:
<asp:TextBox ID="TextBox1" runat="server" onKeyPress="javascript: return false;" onKeyDown="javascript: return false;" onPaste="javascript: return false;" />
How would I also disable backspace within the textbox using javascript?
EDIT
Made an edit since I need a solution in javascript.
EDIT
It turns out that onKeyDown="javascript: return false;" DOES work. I have no idea why it wasn't working before. I tried using a new textbox and it blocked backspaces fine. So sorry to everyone who posted an answer hoping to get some rep esp. after I marked it for bounty.
My textboxes now (seem) to block ALL keystrokes and also still work with the calendar extender.

ZX12R was close. This is the correct solution:
The TextBox is like this:
<asp:TextBox ID="TextBox1" runat="server" onKeyDown="preventBackspace();"></asp:TextBox>
and the script looks like this:
<script type="text/javascript">
function preventBackspace(e) {
var evt = e || window.event;
if (evt) {
var keyCode = evt.charCode || evt.keyCode;
if (keyCode === 8) {
if (evt.preventDefault) {
evt.preventDefault();
} else {
evt.returnValue = false;
}
}
}
}
</script>
First of all, the backspace wont come through on Key Press, so you have to use Key Down.

Can't you just use the HTML readonly="readonly" attribute?
<input type="text" name="country" value="Norway" readonly="readonly" />
<textarea rows="3" cols="25" readonly="readonly">
It should work! :)
</textarea>

How about using a label for the display and a hidden textbox to get the value back to the server?

You need to apply readonly on the client side controller ONLY, so that asp.net doesn't see it and still reads the data on postback. You can do this several ways, one of the easier if you use jQuery is to add a class to the text-boxes eg. cssclass="readonly" in question and $(".readonly").attr("readonly", true);.

As others said ReadOnly="True" will break the postback mechanism.
I believe you can get around it in your code-behind by accessing the Request object directly during PageLoad:
//assuming your textbox ID is 'txtDate'
if(Page.IsPostBack)
{
this.txtDate.Text = Request[this.txtDate.UniqueID];
}
Your other option is to allow Disabled controls to postback on the form, but this is somewhat of a security concern as readonly fields modified via script could potentially come back:
<form id="MyForm" runat="server" SubmitDisabledControls="True">
..
</form>
http://msdn.microsoft.com/en-us/library/system.web.ui.htmlcontrols.htmlform.submitdisabledcontrols.aspx
I'm not sure the impact of this property on ReadOnly (vs Enabled="False") controls but it's worth trying.
And finally - I did run into the same issue you're having a few years ago, and from what I remember there is a difference between using an html input marked as readonly and runat="server", and an actual serverside control where ReadOnly="true".
I have a feeling doing:
<input type="text" readonly="readonly" runat="server" id="myTextBox" />
may have still allowed the data to come through, although in the code-behind you have to treat the control as a HtmlInputText or HtmlGenericControl vs. a TextBox. You can still access the properties you need though.
Just a few ideas anyway...

here is a possible solution... add an event listener...
<asp:TextBox ID="TextBox1" runat="server" onKeyPress="KeyCheck;" />
and then the function can be like this..
function KeyCheck(e) {
var KeyID = (window.event) ? event.keyCode : e.keyCode;
if (KeyID == 8 ) {
alert('no backspaces!!);
}
}
doubt if it has to be onkeypress or onkeyup...

ReadOnly attribute does not help. The backspace still is taking your browser to back page even if your text box is read only..

use regular text boxes not read-only and not Disabled, just use client-side JavaScript to ignore keypresses.
This will ignore all keypress so you will have your READONLY behaviour and it will also ignore the backspace.
<input type="text" value="Your Text Here" onkeydown="return false;" />

No Need to call any function and all just try this:
<asp:TextBox runat="server" ID="txt" onkeydown="return false;"
onpaste = "return false;" onkeypress="return false;" />

I was able to do something similar, with Jquery. Just putting it out here for reference!
$("#inputID").keypress(function (e)
{e.preventDefault();});
$("#inputID").keydown(function (e)
{e.preventDefault();});
the first prevents keypresses, while the second prevents key down events.
Still a JS noob, so feel free to point out good / bad things with this.

Related

Cross browser code to restrict user input using Javascript

I found this code through Stack Overflow to restrict users from putting numbers in a textbox, however it only works in Chrome and IE. Anyone know of any cross browser code to do this?
Note: we've already added the global attribute and it didn't work at all, this was the only one that fully worked in Chrome and IE.
<input type="text" onkeyup="this.value = this.value.replace(/[^a-z]/, '')" />
You want to catch onkeydown that is when the character gets inserted, not on onkeyup. You should also instead of removing the number, just prevent it from getting inserted with event.preventDefault()
<p>
<input type="text" onkeydown="event.key.match(/\d/) && event.preventDefault()" />
</p>
One thing I would recommend is removing the code from the html and putting it in a function so it is reusable like this:
// Wait till the dom is loaded
document.addEventListener('DOMContentLoaded', function(e) {
// Add the event to each input that has `data-type="number"`
document.querySelectorAll('[data-type=number]').forEach(function(input) {
// Add the event to the input
input.addEventListener('keydown', number)
})
})
function number(event) {
event.key.match(/\d/) && event.preventDefault()
}
<p>
<input type="text" data-type="number" />
</p>

ASP.Net LinkButton Prevent Postback Not Working - JavaScript

I know how to prevent javscript within the href attribute from firing as evident in this JSFiddle (http://jsfiddle.net/mkarr/KNefK/)
However, when this logic is applied to an ASP.Net LinkButton as such:
<asp:LinkButton ID="btnSubmit" runat="server" Text="Submit" OnClientClick="return formTest.validate(event);" OnClick="btnSubmit_Click"></asp:LinkButton>
which translates to:
<a onclick="return formTest.validate(event);" id="ctl00_m_g_87932399_e546_4e12_8297_982b811d8cea_ctl00_btnSubmit" href="javascript:WebForm_DoPostBackWithOptions('blah blah blah')">Submit</a>
The formTest.validate() method does execute correctly and returns false, but the WebForm_DoPostBackWithOptions is always fired immediately after!
Can anyone see any flaws in my logic that I cannot??
EDIT:
Also, several stack overflow solutions have been accepted for this issue but all of them are doing virtually what I have already done leading me to believe I'm missing something simple!
Disable the postback on an <ASP:LinkButton>
Prevent LinkButton post back OnClientClick not working. Why?
ANSWER:
Since I cannot answer my own question because I'm not reputable yet (LOL), here's an edit with the answer:
Going off #QBM5's original tip of not using ASP.Net controls, I solve the problem, although I still do not know why the initial problem occurred in the first place (does anyone when it comes to ASP.Net? Turn it off, then back on comes to mind here) :o)
I replaced the LinkButton ASP.Net control with the following:
<input type="submit" value="Submit" id="btnSubmitButton" runat="server" OnServerClick="btnSubmitButton_Click" class="submitBtn" />
I then bound the .submitBtn's click event via jQuery:
$('.submitBtn').on('click', function (e) {
if (!instance.validate()) {
e.preventDefault();
}
});
The trick is to use OnServerClick and runat="server" on the control but getting away from LinkButton was the goal and the postback behavior is completely different.
which translates to this:
<input onclick="if (typeof(Page_ClientValidate) == 'function') Page_ClientValidate(''); " type="submit" id="ctl00_m_g_87932399_e546_4e12_8297_982b811d8cea_ctl00_btnSubmitButton" value="Submit" class="submitBtn">
Anyone want to take a stab at the root cause? I need to move foward so don't have time. :o)
The following is working for me, by changing element.href = "#"
<asp:LinkButton ID="btnSubmit" runat="server" Text="Submit" OnClientClick="return ClientSideValidation()" OnClick="btnSubmit_Click"></asp:LinkButton>
Javascript validation
function ClientSideValidation() {
var element = document.getElementById("<%=txtAmount.ClientID%>");
element.href = "";
if (element.value == "") {
element.href = "#";
return false;
}
return true;
}

How to call the onclick function after pressing Enter

I am making a chat web application, to send a message, there's an input type="text" and an input type="button", using a function in JavaScript, I managed to work it out by adding onclick="sendMessage()" as an attribute for the input button, but I need to click on it, but I want it to work like any chat messengers or apps, the client writes something down and hits ENTER key, this could work if I used a <form onsubmit="sendMessage()"> and input type="submit" but then the page will refresh, How can I do this?
<form onsubmit="sendMessage();return false">
That prevents the default action of sending a request to the server.
This in-case you want also diable the enter button from Posting to server and execute the Js script.
<input type="text" id="txtSearch" onkeydown="if (event.keyCode == 13)
{document.getElementById('btnSearch').click(); return false;}"/>
<input type="button" id="btnSearch" value="Search" onclick="doSomething();"/>
You'll have to hook into the onkeypress/up/down events for the textbox.
This should get you started:
Enter key press event in JavaScript
Use onkeydown() (or keyPress or keyUp, depending on semantics) instead of on click - this will get you an event with the event.keyCode you want - 13 - and you can easily submit using an AJAX request (i.e. XMLHttpRequest)
Simple Code: - raw Javascript, Don't need JQuery:
<html>
<script>
function keyPress(e)
{
if (!e) e = window.event; // needed for cross browser compatibility
alert(e.keyCode); // You want 13 here , so
// if (e.keyCode == 13)
// etc..
// return true; or false, if you want to cancel event
}
</script>
<body>
<input type="text" onkeydown="keyPress()" size="20"/>xx
</body>
</html>

Enabling Disabling button asp .net - using javascript

Currently in my application I am having a button and a text box. The user types something in the textbox and then presses the button. What I want is that:
The search button should should stay disabled when the page loads for the first time. I can achieve that by setting it to disabled in the code behind file.
Now I want it to remain disabled when the user types upto 2 characters. The moment the user types third character the button should get enabled automatically.
The important thing is that it has to be done without asp .net AJAX since this website will be run from old mobile phones. So only pretty basic javascript or jquery is supported.
Any help will be appreciated.
Thanks
Varun
in order to use the document.getElementById in asp.net and not have to use the full name, you should let asp.net provide it. Instead of:
document.getElementById("ctl00_ctl00_phContent_phPageContent_btnSearch")
Try:
document.getElementById('<%= btnName.ClientID %>')
Where btnName is the asp:Button Id. The <%= code will generate the actual button id, fully qualified, so you don't have to worry about things changing with the hard coded id.
I got this to work with a HTML text box, I don't think you can do it with a asp.net text box:
<head>
<script type="text/javascript">
function TextChange() {
var t = document.getElementById("Text1");
var b = document.getElementById("Button1");
if (t.value.length > 2) {
b.disabled = false;
}
else {
b.disabled = true;
}
}
</script>
</head>
<body>
<form id="form1" runat="server">
<div>
<input id="Text1" type="text" onkeyup="TextChange();" />
<asp:Button ID="Button1" runat="server" Text="Button" Enabled="False" />
</div>
</form>
</body>
If you're using jQuery, use
$(<selector>).val().length
to get the size, then you can set the button's disabled attribute with
$(<button selector>).attr('disabled',false).

JavaScript: Clear search-field when enter with mouse?

I have a textfield () in my homepage for a searchstring.
Normaly I have a text like "enter here to searach..." in it.
Now I will clear the box from the text when a user click into it.
How to solve?
JavaScript?
This can be done by using the placeholder attribute in HTML. Example:
<input type="text" placeholder="e.g. John Doe">
For browsers who don’t support this attribute natively, you could use JavaScript.
If you’re using jQuery, you could consider using my placeholder plugin for jQuery, which is the most robust solution I’ve seen. Here’s a demo page: http://mathiasbynens.be/demo/placeholder
create a JavaScript file or use a current one then write in it:
Function function_name()
{
document.getEelementByName("Control_Name").setAttribute("Value", '');
}
then in the page head:
<script id="js1" type="text/javascript" src="dir/file_name.js"></script>
The Control Tag become:
<input type="text" name="Control_Name" onClick="return js1/function_name();" />
Yes you need javascript to achieve this. You could subscribe for the onclick event and when this event is triggered set the text to empty and then unsubscribe from the onclick event to avoid clearing the text every time a user clicks:
var foo = document.getElementById('foo');
foo.onfocus = function() {
foo.value = '';
foo.onfocus = null;
};
Live demo.
And if you are using jquery there is a really nice watermark plugin which allows you to do this.
I would suggest writing an onfocus Javascript handler; that will be triggered whether you’ve clicked it or tabbed into it.
<input type="text" name="..." value="" onfocus="this.value = '';" />
You can use onfocus and onblur javascript methods
<input type="text" name="searchinput" onblur="this.value='enter here to search...';" onfocus="this.value = '';" />

Categories

Resources