How to invoke a onclick event on specific dynamic button on javascript - javascript

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:

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';
}
}

Related

Setting the value of an input through javascript

What I'm trying to do is to change a behind-the-code C# veriable's value through javascript. My code:
HTML & JS -
function SetPostbackValues() {
document.getElementById("hiddenControl").value = "Employer";
}
function SetPostbackValues2() {
document.getElementById("hiddenControl").value = "Employee";
}
<!-- it's all inaide a form tag -->
<div id="left">
<div id="background" style="background: url(paper.gif); background-size: cover;" onclick="chg();SetPostbackValues();"><img id="man" style="right:16px;" src="https://www.watertankfactory.com.au/wp-content/uploads/2015/08/Smiling-young-casual-man-2.png" /> <div id="desc">employer</div>
</div>
<div id="trying"></div>
</div>
<div id="right">
<div id="background2" style="background: url(paper.gif); background-size: cover;" onclick="chg();SetPostbackValues2();"><img id="man2" style="right:16px;" src="https://www.watertankfactory.com.au/wp-content/uploads/2015/08/Smiling-young-casual-man-2.png" /><div id="desc2">employee</div>
</div>
</div>
<input id="hiddenControl" type="hidden" runat="server" />
C# -
protected void RegisterUser()
{
//this will run when the client presses on the 'register' button
ScriptManager.RegisterClientScriptBlock(this, this.GetType(), "alertMessage", "alert('Record Inserted Successfully')", true);
u.Email = Email.Text;
u.Password = Password.Text;
u.Firstname = Firstname.Text;
u.Lastname = Lastname.Text;
u.Gender = Gender.SelectedItem.Text;
//relevant bit:
u.Type = hiddenControl.Value;
u.Birthday = Birthday.SelectedDate.ToString("dd/MM/yyyy");
u.Country = Country.Text;
u.City = City.Text;
u.Address = Address.Text;
if (Pfp.HasFile)
{
string path = Server.MapPath("pics/");
Pfp.SaveAs(path + Pfp.FileName);
u.Pfp = Pfp.FileName;
}
s.AddClient(u);
}
So when the client first enters the site, they'll press on either background or background2 which are supposed to set a value to the hidden input, which will be used in the registration function behind the code. When I set a breakpoint, I saw the value always was just an empty string - "" throughout all my iterations (tried setting a To.String() to it in C#, and removing the "" around the value in javascript, and nothing worked). I can't figure out why it won't set a value...
Thanks for any help!
Maybe your error is in the chg() function, check it.
On the other hand you must add "" to values like this:
function SetPostbackValues() {
document.getElementById("hiddenControl").value = "Employer";
}
function SetPostbackValues2() {
document.getElementById("hiddenControl").value = "Employee";
}
Found the solution, it was the ID...
In your code, the ASP elements' ID is server-side. But when you run the code, the ASP element's ID in the client-side is different. In the javascript script, the functions are looking for an element matching the server-side ID, which they will never find, hence why the hidden element's value will stay an empty string.
TLDR - write it like this to prevent the script from detecting a (seemingly) nonexistent element in the client-side's code:
function SetPostbackValues() {
document.getElementById('<%= hiddenControl.ClientID %>').value = "Employer";
}
function SetPostbackValues2() {
document.getElementById('<%= hiddenControl.ClientID %>').value = "Employee";
}

Asp radio buttons is not calling javascript function

I am working on using asp :radio buttons. I am trying to use 2 radio buttons so that if any one of them is selected then other will be unchecked. I am calling JavaScript function on change event of these buttons. That function will add some values and return the out put in the textboxes.I tried to use normal asp buttons then switch to radio button groups and now trying radio button list. need to call javascript function on radio button change event.These buttons will checked and unchecked but java script function is not returning correct values. I guess there are some naming conventions which are not correct or something is not working . looking forward for help to fix this. Neither one of these 3 way is working.
My test.aspx file contains
<asp:UpdatePanel ID="UpdatePanel1" runat="server">
<ContentTemplate>
<div class="span2">Test Career:</div>
<div class="span8">
<asp:RadioButton ID="TestCareerList" runat="server" clientmode=Static Text="MasterDegree">
</div>
</ContentTemplate>
</asp:UpdatePanel>
Document.ready function in aspx page
$(document).ready(function () {
$("input:radio").click(function ()
{
updateYears();
}
}
javascript function is:
function updateYears() {
var yrsDocTemp = parseFloat(yrsDoc);
var yrsMastTemp = parseFloat(yrsMast);
if ($("ContentPlaceHolder2_drpEmplClass").val() != "" && $("#ContentPlaceHolder2_StudentCareerList]").SelectedValue!= "") {
var updateValue = 0;
//Get EmplCalss
if ($("#ContentPlaceHolder2_drpEmplClass").val() == "GA") {
updateValue = updateValue + 1;
}
else if ($("#ContentPlaceHolder2_drpEmplClass").val() == "GAF" || $("#ContentPlaceHolder2_drpEmplClass").val() == "GAP") {
updateValue = updateValue + .5;
}
if ($("#ContentPlaceHolder2_Career").Text =="DoctoralDegree")
{
yrsDocTemp = yrsDocTemp + updateValue;
}
else if ($("#ContentPlaceHolder2_Career").Text == "MastersDegree") {
yrsMastTemp = yrsMastTemp + updateValue;
}
}
//Update the fields
$("#ContentPlaceHolder2_drpYearsDoctoral").val(yrsDocTemp);
$("#ContentPlaceHolder2_drpYearsMasters").val(yrsMastTemp);
}
I am calling this function under document.ready function like this-
$("input:RadioButtonList[ID=^TestCareerList").change(function(){
updateYears();
});
$("#ContentPlaceHolder2_drpEmplClass").change(function () {
updateYears();
});
When I debug the javascript code I see the names of buttons have been changed.
<tr>
<td>
<input id="ContentPlaceHolder2_TestCareerList_0" type="radio" name="ctl00$ContentPlaceHolder2$TestCareerList" value="MastersDegree" />
<label for="ContentPlaceHolder2_TestCareerList_0">Master</label>
</td>
<td><input id="ContentPlaceHolder2_TestCareerList_1" type="radio" name="ctl00$ContentPlaceHolder2$TestCareerList" value="DoctoralDegree" />
<label for="ContentPlaceHolder2_TestCareerList_1">Doctoral</label>
</td>
</tr>
Kindly looking for help.
This is trying to bind to your server-side elements:
$("input:RadioButtonList[ID=^TestCareerList")
But JavaScript has no knowledge of the server-side code. It only operates on the client-side code. And, as you've noticed, your client-side HTML is different. So your JavaScript needs to target that code. Something like this:
$("input:radio[ID=*TestCareerList")
The same would be true for any other selectors you have. As you're discovering, WebForms controls are famously not great for finely controlling your client-side code. ASP.NET MVC makes this a lot easier, but may be a pretty fundamental shift for what you're doing.
One thing that may help is setting your ClientID property on some controls to Static. Take care when doing this however and debug your HTML accordingly, because if you end up with repeated id values in your HTML then it's invalid and the behavior of the JavaScript when selecting on that id would be undefined.

Need to identify which textbox is used using javascript

I have four text boxes in 4 different tabs of an ASP.NET Page. I need to provide same validation message to all the text boxes. Presently I am using four different functions with same functionality. Kindly suggest a way to identify which textbox is being used make that a single funtion
Code from Commend:
<asp:TextBox ID="textBox1" runat="server" ValidationonGroup="abcd"></asp:TextBox>
<asp:CustomValidator ID="ID1" runat="server" ValidationGroup="abcd"
ControlToValidate="textBox1" ErrorMessage="message"
ClientValidationFunction="fname"></asp:CustomValidator>
--Javascript Fn--
function fname(sender, args) {
var x = document.getElementById('<%=txtBox1.ClientID%>').value;
if (some condition) {
args.IsValid = false;
} else {
args.IsValid = true;
}
}
Edit
if you are using Asp.Net then you should use like this
Aspx page code
<div>
<asp:TextBox runat="server" ID="txt1" ClientIDMode="Static" onKeyPress="javascript:text_changed(this.id);"></asp:TextBox>
</div>
JS Code
<script type="text/javascript">
function text_changed(event)
{
var id = event;
alert(id);
}
</script>
You got the textbox id in id variable and now u can get value etc using this id you are applying your conditions.... i hope this will help u

How to call javascript function from asp:textbox?

I am using textbox for searching items from data base and loading them in gridview and
i used custom paging on gridview to show only 25 records per page
and i found java script for searching records on client side as
script>
function filter2(phrase, _id) {
var words = phrase.value.toLowerCase().split(" ");
var table = document.getElementById(_id);
var ele;
for (var r = 1; r < table.rows.length; r++) {
ele = table.rows[r].innerHTML.replace(/<[^>]+>/g, "");
var displayStyle = 'none';
for (var i = 0; i < words.length; i++) {
if (ele.toLowerCase().indexOf(words[i]) >= 0)
displayStyle = '';
else {
displayStyle = 'none';
break;
}
}
table.rows[r].style.display = displayStyle;
}
}
</script>
and calling this as:
<input name="txtTerm" onkeyup="filter2(this, '<%=GridView1.ClientID %>')" placeholder="Search" type="text"/>
this function search record from activated page and obviously searching from whole database will be done on server side and i used asp textbox
but i need onkeyup="filter2(this, '<%=GridView1.ClientID %>')"event in my asp textbox e-g
<asp:TextBox ID="txtSearch" onkeyup="filter2(this, '<%=GridView1.ClientID %>')" placeholder="Search" runat="server" AutoPostBack="True" OnTextChanged="txtSearch_TextChanged" />
but asp didn't allow me to do that..
i need your help to achieve this.
thanks in advance.
EDIT:
I need both searching (client side, server side) in single textbox
because
client side allow searching from loaded page of gridview and
server side allow searching from database on clicking
You could add the client attribute of rendered input control via code behind:
protected void Page_Load(object sender, EventArgs e)
{
txtSearch.Attributes.Add("onkeyup", string.Format("filter2(this,'{0}')",GridView1.ClientID)");
}
EDIT:
After the right comment of #Lukas, we should say that the main problem was the use of <%=GridView1.ClientID %> inline expression inside the textbox webcontrol:
<%= %> will write the string directly to the response-stream, which happens after the server control is constructed, so will be rendered as string and not resolved.
For example:
<asp:Label runat="server" ID="label">test</asp:Label>
<asp:TextBox runat="server" ID="txt" Text="<%# label.ID %>" onkeyup="alert('<%: label.ID %>')"></asp:TextBox>
This is what we have in output:

Updating of the asp.net dropdown control using javascript

In my ASP.Net default.aspx, I have dropdown list control and following javascript code
<asp:DropDownList ID="ddlGenres" runat="server" AppendDataBoundItems="True" AutoPostBack="True" DataSourceID="EntityDataSource2" DataTextField="cityID" DataValueField="cityID" OnSelectedIndexChanged="ddlGenres_SelectedIndexChanged" ClientIDMode="Static" >
<script type="text/javascript">
var ddlClientID = '<%=ddlGenres.ClientID%>';
//document.getElementById(ddlGenres)
function SetddlVal(nIndx)
{
//$("#ddlGenres")
var ddlListSelect = document.getElementById(ddlClientID);
ddlList.SelectedIndex = nIndx;
}
</script>
====================================================================
In a external javascript file, I am calling the function SetddlVal.
I debugged the code and the ddlList selectedIndex is successfully changed within the script.
=====================================================================
The issue I am facing is, when the SelectedIndex value is changed in the javascript, The ddlGenres_SelectedIndexChanged code is not being triggered.
Please let me know if I am missing anything.
Thanks
Nate
In javascript the property of an <select> input is selectedIndex not SelectedIndex.
Change your function to this:
function SetddlVal(nIndx)
{
var ddlListSelect = document.getElementById('<%=ddlGenres.ClientID%>');
ddlListSelect.selectedIndex = nIndx;
}

Categories

Resources