Search code examples
jqueryhtml-tabletraversal

Table cell traversal jQuery


I have seen many related posts, but nothing is working for me here. So here goes, I am trying to validate data from input on every key press and show error in the next div (in the next cell), tried many traversal combinations but no luck.

Code is given below:-

$(this).keypress( function() {
//alert(this);
if (($(this).val().length < 5)||($(this).val().length > 20)) // maybe not working
$(this).parent('td').next('td').children('div').text("Error"); // <- not working
// check input for validity here
});

table:-

<table width="1032" height="448" align="center" cellpadding="1" cellspacing="0">
  <tr>
   <th width="153" align="right" scope="row"><strong>Name:</strong></th>
    <td width="420">
      <label for="user_name"></label>
     <input name="user_name" type="text" id="user_name" size="70" maxlength="100" value="<?php if (isset($row))  echo $row[1]; ?>"/>

   </td>
   <td width="451"> 
    <div id="div_user_name"></div>
   </td>
  </tr>
</table>

Solution

  • Assuming $(this) is in fact selecting your input element, you'll also need to adjust the if statement to check for the value of the input boxes' length, not the length of the selector:

    if (($(this).val().length < 5) || ($(this).val().length > 20))
    

    Also, I'm assuming you have this selector around your current script code:

    $("input[type='text']").each(function(){
    
       $(this).keypress( function() {
       ...
       });
    
    });
    

    Here's a jsfiddle of your code with my input...working...