2016-04-05 32 views
0

这里是我使用的代码:如何在JSP中动态更改迭代逻辑中的文本元素的ID?

<% int number=0 %> 
<logic:iterate name="sample" id="sample1" property="lstWaferRequests" indexId="rowid"> 
<tr> 
    <% number= (rowid.intValue())+1;%> 
<td> 
    <html-el:text name="sample1" property="strExpDate" styleId='<%="Date"+number%>'/> 
</td> 

<script> 
    var x=document.getElementById("<%="Date"+number%>"); 
</script> 

<a href="javascript:show_calendar(x,'');"> 
    <img src="images/calendar.gif" width="16" height="16" border="0" alt="Click Here to Pick up the timestamp"></a> 
</td> 
</tr> 
</logic:iterate> 

我想增加一个变量(数字),并将其添加到sample1 textbox的ID,但ID不会改变为下一次迭代。我使用Inspect Element option in IE11进行了检查。

我用setatttribute()方法在JavaScript来设置ID,但我得到的,

对象不支持的setAttribute方法的错误。

我需要改变其存储的日期值(SAMPLE1)动态因为我需要将其作为参数传递到方法show_calendar文本框的ID。

请指教。

+0

使用$('your element')。attr(“id”,“assign ID”); –

+0

你可以发布你的'show_calendar'函数吗? –

+0

谢谢:)我会尝试,但有没有办法改变已被传递给JavaScript方法的参数动态? – Tommy

回答

0

我已将类添加到您的textboxanchortag

从您的链接中,我知道您必须通过文本框的name属性而不是id

因此我添加了动态名称。这可以通过strExpDate<%=number%>来实现。但我建议使用JSTL而不是scriptlet。 有关详细信息,请参见java expertBalusCHow to avoid Java code in JSP files?

更新: 在你的逻辑迭代,你必须改变这样的

<% int number=1 %> 
<logic:iterate name="sample" id="sample1" property="lstWaferRequests" > 
    <tr> 
     <td> 
      <html-el:text name="strExpDate<%=number%>" property="strExpDate" styleClass="dates" /> 
     </td> 
     <td> 
      <a class="test" href="#"> 
       <img src="images/calendar.gif" width="16" height="16" border="0" alt="Click Here to Pick up the timestamp"> 
      </a> 
     </td> 
    </tr> 
    <% number++; %> 
</logic:iterate> 

在脚本中找到点击锚标记和最近的文本框与dates类。我使用jQuery库,因为你标记了它。

$(document).ready(function() { 
    $(".test").click(function(e) { 
     var value = $(e.target).closest('tr').find('.dates').val(); 
     var name = $(e.target).closest('tr').find('.dates').attr('name'); 
     alert("Name : "+name+" Value : "+value); 

     // You can call show_calendar() from here by passing name and value. 
    }); 
}); 

查看Demo in fiddle。如果有任何澄清,请告知我,希望这会有所帮助。

+0

谢谢你:)但我不是预先确定要添加的文本框的数量。我通过点击添加行按钮来动态添加它:( – Tommy

+0

您不必预先定义任何地方的文本框数量。为了刺激您的问题,我使用了5行文本框。任何数量的行希望我已经提到了我的答案 –

+0

请参阅我的'更新'在回答您的动态部分 –

0

将数字变量转换为字符串并连接到indexId。 然后再次回到int。它应该工作