How do you select form elements in JQuery based upon an html table?
I am working on some ASP.NET web forms which involves some dynamic generation, and I need to add some onClick helpers on the client side. I have a basic outline of something working, except for one huge problem.
There are multiple HTML tables, each generated by a different ASP.NET web control. Each table can contain overlapping field names, which is causing a problem with my JQuery click event handlers. The click event handler is linking to unintended form fields in addition to the intended form field.
I have provided a simplified sample version of the code below. This code is trying to set the value of textbox box1 when a particular radiobutton is selected in the table with id=thing1. Obviously, the jquery code will be triggered for the form fields in both tables.
The tables are dynamically added to the webpage based upon different conditions. It is possible that no tables will be loaded, only 1 table, or both tables might load. In the future, other tables could be added. Each table comes from a different .net web control.
Other than renaming the form fields to make sure they are unique across all user controls, is there a way to have JQuery act only on the intended form fields? In other words, could the table ID be incorporated into the JQuery code in a manner that does not become a nightmare to maintain later?
<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>
<radiob开发者_开发问答uttonlist id="radio1"/>
<listitem>yes</listitem>
<listitem>no</listitem>
</td></tr>
<tr><td>
<textbox id="box1"/>
</tr></td>
</table>
There are several ways to traverse the DOM using jQuery, so you can get a reference to the proper relative element.
One way is to traverse up to the parent table
element, then .find()
the relative element you're 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>
Apply classes to the tables, then specify your jquery selector to look for the form fields within a specific table, e.g. i think this would work
$(".table1 [id$=radio1_0]")
youthen just need to set the css class propertyon the relevent controls.
精彩评论