Monk L
Monk L

Reputation: 3368

space validation need quality

JS:

var KEYS = { SPACE: 32 };
var str = $('#id_phone_daytime').val();

$("#id_phone_daytime").keyup(function(e) {
    $.trim(str)
    $('#id_phone_daytime').val(str);
    if (e.keyCode == KEYS.SPACE) {
       alert("No space please")
    }
});

html:

No space please

The above code is for validating white space for a single input field. It is working fine, but in my application I have 8 more input fields with different ids. I want to validate white space validation for these 8 input fields also.

How to implement the same functionality with minimum amount of code?

Upvotes: 1

Views: 342

Answers (3)

var KEYS = { SPACE: 32 };
$(".no-spaces").keyup(function(e) {
    this.value=$.trim(this.value);
    if (e.keyCode == KEYS.SPACE) {
        alert("No space please");
    }
});

Upvotes: 2

Ibrahim Azhar Armar
Ibrahim Azhar Armar

Reputation: 25745

You can assign multiple selector using class, for example

<input type="text" class="validate_white_space">

and use this class like below.

var str = $('.validate_white_space').val();

$(".validate_white_space").keyup(function(e) {
    $.trim(str)
    $('#id_phone_daytime').val(str);
    if (e.keyCode == KEYS.SPACE) {
        alert("No space please");
    }
});

Upvotes: 1

Rory McCrossan
Rory McCrossan

Reputation: 337560

Instead of using an id selector (which has to be unique) use a class selector, which can be used to group elements. Try this:

var KEYS = { SPACE: 32 };

$(".no-spaces").keyup(function(e) {
    var $this = $(this);
    $this.val($.trim($this.val()));

    if (e.keyCode == KEYS.SPACE) {
        alert("No space please");
    }
});

All you need to do now is add class="no-spaces" to the relevant inputs.

Upvotes: 2

Related Questions