What is the method to enable both text and numbers in an input field while restricting special characters?

Is it possible to allow both text and numbers but disallow special characters in this input field?

Currently, my code only allows numbers. How can I modify it to also allow text?

Is it possible to achieve this using JavaScript?

http://jsfiddle.net/mhgv0wt0/

<form action=# name=f1 id=f1 onsubmit="return false">
<input type=text name=t1 id=t1 value="" size=25 style="width:300px;"
 onkeypress="if(this.value.match(/\D/)) this.value=this.value.replace(/\D/g,'')"
 onkeyup   ="if(this.value.match(/\D/)) this.value=this.value.replace(/\D/g,'')"
>
</form>

Answer №1

To easily restrict input, simply include a pattern attribute:

<input pattern="^[a-zA-Z0-9\s]+$" type="text" />

Test it out here

The code above should work well in most browsers. If needed, you can use jQuery as a fallback solution:

$('input').keypress(function (e) {
    if (!/[a-zA-Z0-9\s]/.test(String.fromCharCode(e.which || e.keyCode))) {
        e.preventDefault();
    }
});

Give it a try here

Answer №2

Utilize jQuery library. It is also recommended to incorporate the whitespace character (\s) in your code.

$('#t1').on('keypress', function (event) {
    var regex = new RegExp("^[a-zA-Z0-9]+$");
    var key = String.fromCharCode(!event.charCode ? event.which : event.charCode);
    if (!regex.test(key)) {
       event.preventDefault();
       return false;
    }
});

Check out this JSFiddle demo

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Using a SASS watcher to keep an eye on every folder and compile them into a single CSS

I'm interested in setting up a folder structure like this: assets - scss - folder file.scss anotherfile.scss anotherfile.scss anotherfile.scss - anotherfolder file.scss anotherfile.scss anotherfile.scss ...

Improving the layout and size of text within input fields

How can we adjust the input text positioning to the right so it's not directly against the edge? Is there a way to move 'searching' 5px to the right? ...

The Chrome Extension Javascript popup appears to be empty

Feeling a bit lost on my first attempt at creating a chrome extension. Check out my manifest.json below: { "manifest_version": 2, "name": "Get Offensive Wallpapers", "version": "1.0", "permissions": [ "tabs", "http://*/*", "https://*/*" ], ...

Utilizing the powerful combination of TailwindCSS and Next.js Image to achieve a full height display with

Trying to utilize the Next.js' <Image> component with the layout=fill setting, I created a relative div housing the Image tag. However, I am looking for a way to set the height based on the Image's height. Came across this example, but the ...

Is there a way to synchronize breakpoint values across different media queries?

Currently utilizing Next.js version 9.53. Utilizing the built-in CSS module support provided by Next.js without the use of CSS pre-processors (less, sass, etc.) or CSS-in-JS (styled-components, etc.). Presently, my approach involves writing CSS in a mobi ...

Highlight the parent item when the child item is being hovered over

I am working on a menu that has 2 submenus. I want to use jQuery to highlight the item when it is hovered over. However, I am struggling with how to also highlight the parent item when the cursor is on the child item. The class I am using for highlighting ...

How can a div be positioned outside of an overflow scroll without resorting to absolute positioning?

I am currently designing a blog theme and I would like to include a small box that displays the post date offset to the left of each post, similar to this mockup: My issue arises because the post container has overflow scrolling enabled, making it difficu ...

Display a pop-up window upon clicking anywhere on the webpage using jQuery and HTML

Is it possible for me to create a pop-up window that opens a specific website when a user clicks anywhere on the page, similar to pop-up companies? Can this be achieved using HTML, JavaScript, and jQuery? Any help would be greatly appreciated. ...

Integrate a button following the first paragraph exclusively when there are two or more paragraphs present

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> jQuery(document).ready(function($) { if ( $('p').length < 1 ) { $('p:last-child').after('<div id="toggle" class="btn"> ...

Validating multiple input fields using ajax

Currently, I am in the process of developing a new system and have encountered an issue while working with jquery + ajax. My particular challenge revolves around figuring out how to validate multiple fields within my registration form using ajax. I am hopi ...

Retrieve the information located within the error section of an Ajax request

When sending an ajax request to a Django view, I am including data in the response based on certain logic. return JsonResponse(content={ "Message": "user is not present.", },status=400) This response falls under the error section ...

Transfer the value of a JavaScript variable to paste it into a fresh tab on Google Chrome

I have come across some examples where users can copy HTML text to the clipboard. However, I am working on something more dynamic. Here's what I'm trying to achieve: <button id="" ng-click="outputFolder()">Output Folder</button> $sc ...

Tips for creating a mandatory textarea input field

It's pretty straightforward - I have a textarea that is set to required, but it only alerts the user if you actually click inside the text area. If you try to submit without clicking inside, it won't prompt the alert. Take a look at this Fiddle ...

The servlet is notified of a request with no data being sent from

I have encountered an issue with my JavaScript program that is attempting to send an AJAX request to a Java HTTPServlet. The servlet, which listens on the specific URL pattern "/users", is expected to return XML data. However, when the request is made to t ...

Exploring ways to repeatedly collapse rows using HTML, CSS, and JavaScript

GOAL: I want to freeze the header, freeze the first column, and be able to collapse rows multiple times. CURRENT PROGRESS: I have achieved freezing the header, first column, but can only collapse rows once. MY CODE SNIPPET: </head> <body> &l ...

Dreamweaver constantly combines an external CSS file with locally stored CSS when running on a local server

When I used Dreamweaver CS5, XAMPP Server, and PHP files in the past, I encountered an issue. The websites within my htdocs folder seemed to be pulling a specific website's CSS file. In 'Live View,' I could see all external .css and .js file ...

Altering information with the use of history.pushState throughout time

I've created a template that I want to load using the jQuery .load() function. However, during testing, I discovered that it's not loading at all. Here is the code I'm trying to use for loading: function open() { history.p ...

Best Practices for Prioritizing CSS Selection

My usual practice is to organize the rules in my CSS file to align with their corresponding elements in the HTML code. However, when it comes to global rules such as styling for input,textarea,p,tr,th, and so on, I wonder if there is a specific convention ...

The HTML/CSS authentication system is experiencing technical difficulties and is not functioning as intended

I came across this code on codepen.io and tried to implement it using the provided HTML and CSS. However, I encountered some errors during implementation. While the code works perfectly in the CodePen compiler, it doesn't seem to be error-free. One i ...

Displaying the Polymer Paper spinner when the page is still loading

How can I make the polymer paper spinner display while the body tag is set to unresolved? I'm experiencing a brief blank screen before the page finishes loading. I'm feeling lost and unsure of how to begin. Check out the Polymer Project documen ...