...">

JQuery class selectors

I have an html text box with some class names like numbers

<input type="text" name="msg_timeout" class="numbers" />

Similarly, there is a text box with the numbers class . I want to assign a keydown event for this text box that has a class as a number, so I tried the following, but it didn't work

$('input.numbers').each

$('.numbers').each

$('input.numbers:text').each

$('input:text.numbers').each

$('input[type=text]').each  // only this is working but it selects all textboxes.

kindly let me know the idea. CODE below

$(document).ready(function() {


    $('input.numbers').each(function() {

        $(this).get(0).oncontextmenu = function() { return false; };
           $(this).bind("keydown",function(event) {
           // alert(window.event);

            // Allow only backspace and delete
            if ( event.keyCode == 46 || event.keyCode == 8  
                    && (event.keyCode >=96 && event.keyCode <=105) ) 
            {
                // let it happen, don't do anything
            }
            else {
                // Ensure that it is a number and stop the keypress
                if (event.keyCode < 48 || event.keyCode > 57 || event.shiftKey || event.ctrlKey || event.altKey ) {
                    event.preventDefault(); 
                }   
            }

            var forbiddenKeys = new Array('c', 'x', 'v');
            var keyCode = (event.keyCode) ? event.keyCode : event.which;
            var isCtrl;
            isCtrl = event.ctrlKey;
            if (isCtrl) {
                for (i = 0; i < forbiddenKeys.length; i++) {
                    if (forbiddenKeys[i] == String.fromCharCode(keyCode).toLowerCase()) {
                        //alert('You are prompted to type this twice for a reason!');
                        return false;
                    }
                }
            }
            return true;
        });
   });

});
+3
source share
4 answers

Do you call the selector after dom.ready?

$(document).ready(function() {
    $('input.numbers').keydown(function() {
        // code here
    });
});

without $(document).ready()unpredictable which elements will be present on the screen when your selector is rated.

+3
source

, . :

// bind a keydown handler to all input elements with class 'numbers'
$("input.numbers").keydown(function() {
    // handler implementation here
});
+1

, , ?

.. ..

$("input.numbers").live('keydown', function() {
    // do stuff here
});
+1
source

do you mean "numbers" not as text, but as a number, a digit, an integer?

$("input").filter(function() {
   return $(this).attr("class").match(/\d+/);
});
0
source

Source: https://habr.com/ru/post/1790180/


All Articles