How to send clientid of asp.net control via JavaScript - javascript

I am trying to send the control id on button click in my following asp.net code:
<asp:TextBox ID="empid" runat="server" CssClass="input_box" onFocus="if (this.value == this.title) this.value='';" onBlur="if (this.value == '')this.value = this.title;" value="Enter employee ID" title="Enter employee ID" onClick="changecol(this)"></asp:TextBox>
<asp:Button ID="abc" runat="server" Text="xxx"
CssClass="submit_button" onclick="abc_Click" OnClientClick="return checkEmpid('<%=empid.ClientID%>')"/>
and Javascript is:
function checkEmpid(id){
var idValue = document.getElementById(id).value;
alert(idValue);
return false;
}
In alert I am getting null while when I use following code:
<asp:TextBox ID="empid" runat="server" CssClass="input_box" onFocus="if (this.value == this.title) this.value='';" onBlur="if (this.value == '')this.value = this.title;" value="Enter employee ID" title="Enter employee ID" onClick="changecol(this)"></asp:TextBox>
<asp:Button ID="abc" runat="server" Text="xxx"
CssClass="submit_button" onclick="abc_Click" OnClientClick="return checkEmpid()"/>
function checkEmpid(){
var idValue = document.getElementById('<%=empid.ClientID%>').value;
alert(idValue);
return false;
}
In alert I got value entered in text box. Please help me in solving this problem I want to send clientid of control as parameter for JS.

If you definitely want to pass the UserControl name via a parameter, I believe your only option would be to set the function call in the code-behind...
C#...
abc.OnClientClick = string.Format("return checkEmpid('{0}');", empid.ClientID);
VB.NET...
abc.OnClientClick = String.Format("return checkEmpid('{0}');", empid.ClientID)
(Updated, as I realised you wanted the TextBox ID, not the UserControl ID)

You can send client id of empid textbox to javascript this way.
abc.Attributes.Add("onclick", "return checkEmpid('" + empid.ClientID + "')");
function checkEmpid(clientIdOfempid){
alert("This is id of TextField with ID=empid >> "+clientIdOfempid);
return false;
}
or
You can get client ID by '<%=empid.ClientID%>' this way
function checkEmpid(){
var id = '<%=empid.ClientID%>';
alert("This is id of TextField with ID=empid >> "+id);
return false;
}

alert('<%=empid.ClientID%>');
Try this to get ID

Isn't it simplier to alert ID itseld?
alert('<%=empid.ClientID%>');

Related

ASP.net, How can I see the selected value of a radio button in javascript

I thought myRadioButton.value would work but value doesn't come up as an option I can select. If I select nodevalue the value of that during runtime is null. "No" should be selected by default but I'm not sure how to bring up that value in my javascript code. What am I missing?
<script type="text/javascript">
function TextValidation(oSrouce, args) {
var myRadioButton = document.getElementById('<%= rblUserEquip.ClientID %>');
var myTextBox = document.getElementById('<%= txtEmpName.ClientID %>');
alert("Test" + myRadioButton.value);
if (myRadioButton.value == "no")
{
alert("Test2");
if (myTextBox.value == "")
{
args.IsValid = False;
alert("Employee name empty");
return false;
}
else
args.IsValid = True;
}
else
{
args.IsValid = True;
alert("Test3");
}
}
</script>
<asp:RadioButtonList ID="rblUserEquip" runat="server">
<asp:ListItem Value="yes" Text="Yes"></asp:ListItem>
<asp:ListItem Value="no" Text="No" Selected="True"></asp:ListItem>
</asp:RadioButtonList>
<asp:TextBox ID="txtEmpName" runat="server" ></asp:TextBox>
<asp:CustomValidator runat="server" ID="cvEmpName" ClientValidationFunction="TextValidation" Display="Dynamic" text="*" ErrorMessage="Please fill TextBox" ></asp:CustomValidator>
<cc1:ValidatorCalloutExtender ID="vceSymptoms" runat="server" TargetControlID="cvEmpName"></cc1:ValidatorCalloutExtender>
It works like this:
<asp:RadioButtonList ID="rblUserEquip" runat="server" ClientIDMode="Static">
<asp:ListItem Value="1" Text="Yes"></asp:ListItem>
<asp:ListItem Value="2" Text="No" Selected="True"></asp:ListItem>
</asp:RadioButtonList>
<br />
<asp:Button ID="Button2" runat="server" Text="Client side = get RB value"
OnClientClick="MyRB();return false;"/>
<br />
<script>
function MyRB() {
// get radio button choice
rbl = $('#rblUserEquip')
choices = rbl.find('input')
choicesText = rbl.find('label')
console.log(choices[0].checked)
console.log("choice value = " + choices[0].value)
console.log("choice Text = " + choicesText[0].innerText)
// get selected rb only
mysel = rbl.find('input:checked')
console.log("choice value for sel = " + mysel[0].value)
}
</script>
Note how you can't get the "text" value, since it is rendered as a separate label. I assumed jQuery for above - but above should suffice for what you require.
And for avoiding confusing, I changed the above "yes" (value) to 1, and 2. Since we REALLY want to be crystal clear that we can get the "value" of the input, but the actual text is generated and displayed as a 100% separate label.
so, running above js code, then we get/see this:
output:
false
choice value = 1
choice Text = Yes
(above is first value in array of choices)
last set of code, we select based on checked
Ouput:
choice value for sel = 2

Client side validation for Textbox inside Gridview control Using Javascript Or Jquery

I am developing asp.net application, in that i have a page contains gridview with text boxes,
in that i need to validate to fill atleast one text box in that gridview.
I googled many pages, but i have found only check box validation like this,
when save button click, i need to validate to fill atleast one text box in deposit amount in that gridview..
please any answers would be appreciated..
Use RequiredFieldValidator
<asp:RequiredFieldValidator ID="RequiredFieldValidator4" runat="server" ControlToValidate="txtAmount" ErrorMessage="Fill This"></asp:RequiredFieldValidator>
<script type="text/javascript">
function validateTextBox() {
//get target base & child control.
var TargetBaseControl = document.getElementById('<%=this.Gridview1.ClientID%>');
var TargetChildControl1 = "txtDepositAmount";
//get all the control of the type INPUT in the base control.
var Inputs = TargetBaseControl.getElementsByTagName("input");
for (var n = 0; n < Inputs.length; ++n)
if (Inputs[n].type == 'text' && Inputs[n].id.indexOf(TargetChildControl1, 0) >= 0)
if (Inputs[n].value != "") return true;
alert('Enter Atleast One Deposit Amount!');
return false;
}
</script>
<asp:ImageButton ID="btnSave" runat="server" ValidationGroup="valInsert" ImageUrl="~/images/save6.png"
Width="40px" Height="40px" OnClientClick="javascript:return validateTextBox();" OnClick="btnSave_Click" ToolTip="Save" />
You can use a CustomValidator and jQuery to check if at least one TextBox has text in it.
<asp:CustomValidator ID="CustomValidator1" runat="server" ErrorMessage="At least one TextBox is required" ClientValidationFunction="validateMyTextBoxes"></asp:CustomValidator>
<script type="text/javascript">
function validateMyTextBoxes(oSrc, args) {
var isValid = false;
$("#<%= GridView1.ClientID %> input[type=text]").each(function () {
if ($(this).val() != "") {
isValid = true;
}
})
args.IsValid = isValid;
}
</script>

validate user control input value

How to validate user control textbox value on Parent page? I have the following code but it couldn't find the control. I have checked IE View Source(HTML) and this control renders as
ctl00_Management_Initiation_txtTitle_txtInput
How to get the value using JQuery? Please let me know.
User Control
<telerik:RadTextBox id="txtInput" runat="server" TextMode="MultiLine" LabelCssClass=""></telerik:RadTextBox>
<asp:image id="ImgRequired1" ImageUrl="../../images/requiredfield.gif" AlternateText="Required Field" Runat="server" Visible=false></asp:image><br />
.aspx page
<script type="text/javascript">
$(document).ready(function () {
$("#<%=btnSave.ClientID %>").click(function () {
var valid = true;
var msg = "Please fill form:\n";
if($("input[id*=txtTitle]").val().length == 0{
msg += "Title is Required!\n";
valid = false;
}
});
});
</script>
<uc1:ControlTextBox ID="txtTitle" runat="server" MaxLength="200" ></uc1:ControlTextBox>
<asp:Button ID="btnSave" name="btnSave" runat="server" Text="Save" />
if($("#<%= txtTitle.TextInputClientID %>").val().length == 0) {
There is serious lack of closing brackets, both "}" and ")" in your javascript.
Add property to your user control:
public string TextInputClientID { get { return txtInput.ClientID; } }

JavaScript not working with RadTextBox

<telerik:RadCodeBlock ID="RadCodeBlock1" runat="server">
<script type="text/javascript">
function ValidatePhoneNumbers() {
var phone = document.getElementById('txtPhone1');
var mobile =document.getElementById('txtPhone2');
alert(phone.value);
if ((phone.value == null || phone.value == "") && (mobile.value == null || mobile.value == "")) {
alert('something');
return false;
}
else {
alert('something');
return true;
}
}
</script>
<tr>
<td>
<label for="txtPhone1">
Phone :</label>
</td>
<td>
<telerik:RadNumericTextBox ID="txtPhone1" runat="server" Text='<%# Bind("Phone_One") %>' Type="Number" Skin="Windows7" CssClass="txt">
<numberformat allowrounding="false" keepnotroundedvalue="False" GroupSeparator=""></numberformat>
</telerik:RadNumericTextBox>
<asp:CustomValidator ID="rqfldPhone1" runat="server" ControlToValidate="txtPhone1"
Display="Dynamic" ErrorMessage="*" ValidationGroup="Submit" ToolTip="Enter Phone Number" ></asp:CustomValidator>
</td>
<telerik:RadButton ID="btnUpdate" runat="server" Text='<%# (Container is GridEditFormInsertItem) ? "Insert" : "Update" %>'
CommandName='<%# (Container is GridEditFormInsertItem) ? "PerformInsert" : "Update" %>'
Skin="Windows7" ValidationGroup="Submit">
When i add "OnClientClicked" to RadButton to call javaScript ( "return ValidatePhoneNumbers" ) in javaScript It showing NULL WHY ?
there are 2 rad textbox txtphone1 and txtphone2 ,
Actually i want to validate these textbox , if any one is filled no prob otherwise i need to show A error/warning msg.
pls help me
Actually ".value" is not shownig in javascript (document.GetelementById.value)
When you are working with telerik controls the javascript to find controls and do operations is different that of we work with normal html and javascript:
To find radcombox:
$find("<%=RadComboBox1.ClientID %>");//for example
Let work with your problem:
var phone=$find("<%=txtPhone1.ClientID %>");
var mobile=$find("<%=txtPhone2.ClientID %>");
alert(phone.get_value());//use get_value() to get the value of radcombobox
if ((phone.get_value() == null || phone.get_value() == "") && (mobile.get_value() == null || mobile.get_value()== "")) {
alert('something');
eventArgs.set_cancel(true);
}
else {
alert('something');
}
}
The OnClientClicked event will run a function by name with 2 parameters, these are akin to that used by .NET event handlers (sender and eventArgs). The Telerik controls don't cancel the action in the same manner as general HTML objects in that return false; doesn't cancel a post back. Instead, the Telerik API provides a set_cancel() function in the eventArgs parameter.
function ValidatePhoneNumbers(sender, eventArgs) {
var phone = document.getElementById('<%= txtPhone1.ClientId %>'); // Corrected as per my comment
var mobile =document.getElementById('<%= txtPhone2.ClientId %>'); // Corrected as per my comment
alert(phone.value);
if ((phone.value == null || phone.value == "") && (mobile.value == null || mobile.value == "")) {
alert('something');
eventArgs.set_cancel(true);
}
else {
alert('something');
}
}
You don't need to set the OnClientClicked="return ValidatePhoneNumbers" instead I would recomment using OnClientClicking ="ValidatePhoneNumbers" (see: http://www.telerik.com/help/aspnet-ajax/button-onclientclicking.html)
For more information regarding client side event handlers, see: http://demos.telerik.com/aspnet-ajax/menu/examples/programming/clientevents/defaultcs.aspx
The validator should trigger when the button is pressed, if it is not set CausesValidation="True" and maybe consider a RequiredFieldValidator to ensure it is populated before postback.

Using a custom validator to change a label color if data isn't validated

I am wanting to change the color of a label when its associated text box doesn't pass validation. Not getting any results with my current code:
<asp:Label ID="lblFirstName" runat="server" Text="Your First Name*:"></asp:Label>
<br />
<asp:CustomValidator
ID="customValFirstName"
runat="server"
Text=""
ControlToValidate="txtFirstName"
ClientValidationFunction="validateFirstName"
Display="Dynamic"></asp:CustomValidator>
<asp:TextBox ID="txtFirstName" runat="server" CssClass="textbox" MaxLength="50"></asp:TextBox>
Javascript:
function validateFirstName(sender, args) {
var firstName = document.getElementById('<%=txtFirstName.ClientID %>');
var firstNameLbl = document.getElementById('<%=lblFirstName.ClientID %>');
if (firstName !== "") {
args.IsValid = true;
}
else {
args.IsValid = false;
firstNameLbl.style.color = '#FF0000';
}
};
Any light that can be shed on what I'm doing wrong would be appreciated.
You need to compare the value of the textbox.
Change if (firstName !== "") to if (firstName.value !== "")
Also add one more attribute to your custom validator markup: ValidateEmptyText="true" otherwise empty text won't be validated at all

Categories