meena
meena

Reputation: 245

How to validate a textbox in jQuery

Following code creates a table & a textbox in jQuery.

 var table = $("#dynamic-table").children();
 var row = $('<tr class="data"></tr>');
 row.append($('<td ><input type="text" value=' + item.Marks1 + '
               size="10px" class="marks" id="txtmarks1"  ></td>'));

I'm trying to validate the textbox using following code which is not working.

$(".data").delegate(".marks","keyup",function () {        
    if ($('#txtmarks1').val().length > 2) {          
        if ($('#txtmarks1').val() > 100) {
            alert("does not exceed 100");
        }
    }
});   

If it is not the correct way to validate then please suggest a solution.

Upvotes: 1

Views: 158

Answers (6)

Jain
Jain

Reputation: 1249

Try this:

$('#dynamic-table').off('keyup').on("keyup",".marks",function () { 
      if ($('#txtmarks1').val().length > 2) { 
        if ($('#txtmarks1').val() > 100) { 
             alert("does not exceed 100"); 
        } 
     } 
}) ; 

Upvotes: 0

Naved Munshi
Naved Munshi

Reputation: 507

Try this jsFiddle

   $(document).on('keyup', ".marks", function () {  
     if ($(this).val().length > 2) {          
         if ($(this).val() > 100) {
           alert("does not exceed 100");
         }
     }
   });

Upvotes: 0

spongecode
spongecode

Reputation: 79

just use:

$(".data").change(".marks","keyup",function () {        
    if ($('#txtmarks1').val().length > 2) {          
        if ($('#txtmarks1').val() > 100) {
            alert("does not exceed 100");
        }
    }
})   

Upvotes: 0

Mandeep Pasbola
Mandeep Pasbola

Reputation: 2639

Try this :

$("body").delegate(".data .marks","keyup",function () {        
    if ($('#txtmarks1').val().length > 2) {          
        if ($('#txtmarks1').val() > 100) {
        alert("does not exceed 100");
        }
    }
})

Upvotes: 0

Sadikhasan
Sadikhasan

Reputation: 18600

$(".marks").keyup(function () {    
    if ($(this).val().length > 2) {          
        if ($(this).val() > 100) {
            alert("does not exceed 100");
        }
    }
});

Demo

Upvotes: 0

Girish
Girish

Reputation: 12117

Event target section $(".data") and target selector ".marks" both added after page load

so you delegate() method won't target section .data selector class you should use parent selector that is load on page load or document for delegate selector section

$(document).delegate(".marks","keyup",function () {        
    if ($('#txtmarks1').val().length > 2) {          
        if ($('#txtmarks1').val() > 100) {
            alert("does not exceed 100");
        }
    }
})   

Upvotes: 1

Related Questions