Reputation: 422
I am working on a usercontrol file which contains a textbox and a button.
The control renders multiple records on one page and hence creating and rendering the textboxes and buttons dynamically.
I am trying to invoke a javascript function to validate whether the textbox has value. My problem is I am not able to determine which button is being clicked as it is dynamically created. (As I am integrating this control in parent page gridview and hence it becomes dynamic.)
Please advise community. What I am assuming is I am not able to set the index to the button Id I am retrieving before calling the closure
.
I tried following few links available on this website but finally I have post my issue here to seek specific answer.
Below is my code snipeet.
HTML:
function validateSubmit() {
var btn = document.getElementsByClassName('frmBtn').length;
var btnId = document.getElementById('<%=commentSubmitButton.ClientID%>').id;
for (var j = 1; j <= btn; j++) {
(function(j){
btnId[j].onclick = function(){
alert('INSIDE CLICK');
var e = document.getElementsByClassName('frmTextBox')[j].value;
if (e == '') {
document.getElementsByClassName('lbl')[j].style.display = 'block';
}
}
})(j);
}
}
<div class="frmContent">
<p style="float: right; padding-top: 2em;">
<asp:Button ID="commentSubmitButton" runat="server" Text="Submit" CssClass="frmBtn" OnClientClick="validateSubmit(this);" />
</p>
<p>
<label for="txtComment" class="frmLabels">
Type Comment Here
<label id="lblStar" class="lbl" style="display:none;color:red;">*</label>
</label>
<asp:TextBox ID="txtComment" runat="server" Height="60" Width="75%" TextMode="MultiLine" CssClass="frmTextBox" ></asp:TextBox>
</p>
</div>
JAVASCRIPT:
Upvotes: 0
Views: 98
Reputation: 422
Finally I figured it out.
I wonder why I kept inclining toward conventional JavaScript approach when such things can be achieved easily with so nice and so advanced jquery. I observed few concepts on jquery and it helped me made this little thing work in very few lines. Here is the relevant code I wrote with jquery.
It is working now satisfactorily. Thank you all.
jquery code
function validateSubmit(btnid)
{
//debugger;
var txtbox = $(btnid).parent().parent().find('.frmTextBox')[0];
var lblRequired = $(btnid).parent().parent().find('.lbl')[0];
if (txtbox.value == '') {
lblRequired.style.display = 'block';
event.preventDefault();
} else {
lblRequired.style.display = 'none';
}
}
Upvotes: 1