0

I'm working on a project that uses jQuery UI, along with a few other libraries. I'm trying to do input validation (after onChange event) and it's not working correctly. I have several ASP.NET MVC TextBox's and I've tried accessing them by class, and a few other ways, but they're not working.

<%=Html.TextBox("Name1", Model.Customer.FirstName, new { style = "width:200px", @class="alphaOnly", onchange = "InputValidation();"  })%>

This bit of code does work, but I'd have to repeat the last 3 lines several times (~20), which is no good. Any ideas on what the problem could be?

function InputValidation() {
var className = $('.alphaOnly').attr('class');
var regexAlpha = new RegExp('[^[a-zA-Z]+$'); 
var value = $("#Name1").val();
value = value.replace(regexAlpha, '');           
$("#Name1").val(value);

I've tried several methods to get the ID dynamically and to loop through all the controls with the "alphaOnly" class, but still to no avail.

1 Answer 1

1

You don't have to get the ID, you can already just select off class. And you don't have to loop, because the selector will return all the matching items and you can apply a function to the results with something like:

function InputValidation(){
    var regexAlpha = new RegExp('[^[a-zA-Z]+$');
    $(".alphaOnly").each(function(){
        this.value = this.value.replace(regexAlpha, '');
    });
}
Sign up to request clarification or add additional context in comments.

1 Comment

I wasn't able to get it to work. I had to use the manual code below. I think it has something to do with jQuery UI, but I really have no clue. I'll just hard-code the non-dynamic code and check it in. Thanks for your help, that looks exactly what I was looking for.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.