How do you select form elements in JQuery based on html table?

I am working on some ASP.NET web forms that include some dynamic generation and I need to add some client side onClick helpers. I have a basic work plan except for one huge problem.

There are several HTML tables, each created using a different ASP.NET Web control. Each table may contain overlapping field names causing a problem with my jQuery event handlers. The click event handler binds to unexpected form fields in addition to expected form fields.

I have provided a simplified sample code below. This code tries to set the value of the textbox1 field when a specific beacon with id = thing1 is selected in the table. Obviously, the jquery code will run for form fields in both tables.

Tables are dynamically added to a web page based on different conditions. It is possible that tables will not be loaded, only one table may be loaded, or both tables. More tables may be added in the future. Each table comes from a different .net web control.

Aside from renaming form fields to make sure they are unique across all custom controls, is there a way for JQuery to only act on intended form fields? In other words, can a table id be included in jQuery code in a way that doesn't become a maintenance nightmare?

   <script>
    $(document).ready(function() {
      $("[id$=radio1_0]").click(function() {
        $("[id$=box1]").attr("value", "");
      });
      $("[id$=radio1_1]").click(function() {
        $("[id$=box1]").attr("value", "N/A");
      });
   </script>

   <table id="thing1">
      <tr><td>
        <radiobuttonlist id="radio1"/>
          <listitem>yes</listitem>
          <listitem>no</listitem>
      </td></tr>
      <tr><td>
        <textbox id="box1"/>
      </td></tr>
   </table>

   <table id="thing2"> 
      <tr><td>
        <radiobuttonlist id="radio1"/>
          <listitem>yes</listitem>
          <listitem>no</listitem>
      </td></tr>
     <tr><td>
        <textbox id="box1"/>
     </tr></td>
   </table>

      

+2


a source to share


2 answers


There are several ways to move the DOM using jQuery, so you can get a reference to the corresponding relative element.

One way is to navigate to the parent element table

, then the .find()

relative element you are looking for.



   <script>
    $(document).ready(function() {
      $("[id$=radio1_0]").click(function() {
          $(this).closest('table').find("[id$=box1]").attr("value", "");
      });
      $("[id$=radio1_1]").click(function() {
        $(this).closest('table').find("[id$=box1]").attr("value", "N/A");
      });
    });
   </script>

      

+1


a source


Apply classes to tables and then specify your jquery selector to find form fields in a specific table eg. i think it will work

$(".table1 [id$=radio1_0]")

      



you just need to set the css class property for the relevant controls.

+1


a source







All Articles