My question might be little old but I tried all the possibilities and could not find any solution.
I want to do one function for verification the input field:
This function works fine:
function myFunction()
{
var x;
x = document.getElementById('<%=textBoxCustomerCode.ClientID%>').value;
if(isNaN(x) || x == "")
{
alert('Problem input');
return false;
}
else
{
return true;
}
}
and here is the code:
<asp:ImageButton ID="imageButtonView" runat="server" Height="60px" ToolTip="بحث" Width="60px" BorderStyle="Solid" ImageUrl="~/Images/searchButton.jpg" OnClick="imageButtonView_Click" OnClientClick="return myFunction();"/>
This function works fine but once I need to make the function works with any input field. I want way to pass any field to the function so it will verify it. Any idea to do so.
Something like this could work (making the function work for any textbox):
function myFunction(textboxid)
{
var x;
x = document.getElementById(textboxid).value;
if(isNaN(x) || x == "")
{
alert('Problem input');
return false;
}
else
{
return true;
}
}
Here you give the function the id of the textbox you want to check. We do not check if a textbox with the given id exists though.
Change x = document.getElementById('<%=textBoxCustomerCode.ClientID%>').value; to x = document.getElementById('imageButtonView').value;
Try ..........this
function myFunction(id)
{
var x;
x = document.getElementById(id).value;
if(isNaN(x) || x == "")
{
alert('Problem input');
return false;
}
else
{
return true;
}
}
and pass that id through onclientclick event. i.e.
<asp:ImageButton ID="imageButtonView" runat="server" Height="60px" ToolTip="بحث" Width="60px" BorderStyle="Solid" ImageUrl="~/Images/searchButton.jpg" OnClick="imageButtonView_Click" OnClientClick="return myFunction(here is that id to pass);"/>
You can simply use class for finding the element. Or you can pass id to the function in OnClientClick()..
function myFunction(element)
{
var x;
x = document.getElementById('element').value;
if(isNaN(x) || x == "")
{
alert('Problem input');
return false;
}
else
{
return true;
}
}
and you can call this function by OnClientClick="return myFunction(this);"
Related
I am using Javascript function with confirm() message box and also having RequiredFieldValidator if I press cancel on my confirm message box but ValidatorGroup is true then it not stopping a request from getting post back.
I want to implement in such a way that If validatorGroup is treu but function return false then request should not get post back
Here is my Code:-
<asp:Button ID="btnStaffSendRequest" runat="server" Text="Send" OnClientClick="UploadRefrrel()"
UseSubmitBehavior="false" ValidationGroup="SaveRequestGroup" OnClick="btnStaffSendRequest_OnClick"
TabIndex="1000" />
Here is my Javascript Function:-
<script language="javascript" type="text/javascript">
function UploadRefrrel() {
var hiddenFile = this.document.getElementById("<%= hfInputForm.ClientID %>");
var upload = $find("<%= radUploadFiles.ClientID %>");
var inputs = upload.getUploadedFiles();
var retVal;
if (hiddenFile != null && hiddenFile.value != "" && inputs.length == 0) {
retVal = confirm("FYI - Only 'Referral Form' is attached. Do you want to proceed without any other attachment?");
}
return retVal;
}
</script>
<asp:CustomValidator ID="validatePostBack" runat="server" Display="None" ClientValidationFunction="Validate_PostBack"
ValidationGroup="SaveRequestGroup" ErrorMessage="<br /> Please add other attachment."></asp:CustomValidator>
<telerik:RadScriptBlock ID="uploadReferel" runat="server">
<script language="javascript" type="text/javascript">
function Validate_PostBack(sender, e) {
var hiddenFile = this.document.getElementById("<%= hfInputForm.ClientID %>");
var upload = $find("<%= radUploadFiles.ClientID %>");
var inputs = upload.getUploadedFiles();
if (hiddenFile != null && hiddenFile.value != "" && inputs.length == 0) {
var retVal = confirm("FYI - Only 'Referral Form' is attached. Do you want to proceed without any other attachment?");
if (retVal == true) {
e.IsValid = true;
}
else {
e.IsValid = false;
}
}
}
</script>
</telerik:RadScriptBlock>
Found my solution and working fine
I am trying to validate a form using javascript. On button click function I have called a javascript function where I have displayed the message after the text box. The number of times I click the button same number of times message gets displayed just below the existing validation message. Please help me
Here goes my code:
function check() {
var v = true;
if ((document.getElementById('firstname').value == "")) {
$('#firstname').after('Validation message');
document.getElementById('firstname').style.borderColor='#DA394B';
v = false;
}
if ((document.getElementById('lastname').value == "")) {
$('#lastname').after('Some validation text');
document.getElementById('lastname').style.borderColor = '#DA394B';
v = false;
}
return v;
}
Assuming I understand what v is for. Which i probably don't because v (I hate one letter variable names...).
Try this:
function check() {
var v = true;
if ((document.getElementById('firstname').value == "")) {
if ($('#firstnameMessage').length <= 0)
{
$('#firstname').after('<p id="firstnameMessage">Validation message</p>');
document.getElementById('firstname').style.borderColor='#DA394B';
}
v = false;
}
if ((document.getElementById('lastname').value == "")) {
if ($('#lastnameMessage').length <= 0)
{
$('#lastname').after('<p id="lastnameMessage">Some validation text</p>');
document.getElementById('lastname').style.borderColor = '#DA394B';
}
v = false;
}
return v;
}
Simple fiddle to show this working: https://jsfiddle.net/srLt7wo0/
Using .after will insert another element per http://api.jquery.com/after/
The below solution uses a separate element already in the HTML to display the error message. If you use .after you have to check that you have not already added an element to your HTML
HTML
<input id="firstname" type="text"/><div id="firstnameMessage"></div>
<input id="lastname" type="text"/><div id="lastnameMessage"></div>
JS
function check() {
$("#firstnameMessage,#lastnameMessage").text(''); // clear message, reset border color
document.getElementById('firstname').style.borderColor='';
document.getElementById('lastname').style.borderColor='';
var isValid = true;
if ((document.getElementById('firstname').value == "")) {
$('#firstnameMessage').text('First name is required');
document.getElementById('firstname').style.borderColor='#DA394B';
isValid = false;
}
if ((document.getElementById('lastname').value == "")) {
$('#lastnameMessage').text('Last name is required');
document.getElementById('lastname').style.borderColor='#DA394B';
isValid = false;
}
return isValid;
}
I'm not sure to have understood you issue but maybe this could help you :)
window.firstname = document.getElementById('firstname')
window.lastname = document.getElementById('lastname')
window.issue = document.getElementById('issue')
function check() {
if(firstname.value == '' || lastname.value == '') {
issue.innerHTML = 'Please, use correct credentials.'
} else {
issue.innerHTML = ''
}
}
<input id="firstname" />
<input id="lastname" />
<button onclick="check()">
Check
</button>
<div id="issue" style="color:red;"></div>
This should work if i understand you.
It will add only one message no matter how many times you click
function check() {
var v = true;
if ((document.getElementById('firstname').value == "")) {
$('#message').remove()
$('#firstname').after('<span id='message'>Validation message</span>');
document.getElementById('firstname').style.borderColor='#DA394B';
v = false;
}
if ((document.getElementById('lastname').value == "")) {
$('#message').remove()
$('#lastname').after('<span id='message'>Some validation text</span>');
document.getElementById('lastname').style.borderColor = '#DA394B';
v = false;
}
return v;
}
i have written a javascript code to compare 2dates from 2 textboxes
function CompareDates() {
var fdate = document.getElementById('txtFromDate');
var edate = document.getElementById('txtToDate');
var FromDate = fdate.value.split('/');
var EndDate = edate.value.split('/');
var val = 'false';
if (parseInt(FromDate[2]) < parseInt(EndDate[2])) {
val = 'true';
return true;
}
else if (parseInt(FromDate[2]) == parseInt(EndDate[2])) {
if (parseInt(FromDate[0]) < parseInt(EndDate[0])) {
val = 'true';
return true;
}
else if (parseInt(FromDate[0]) == parseInt(EndDate[0])) {
if (parseInt(FromDate[1]) <= parseInt(EndDate[1])) {
val = 'true';
return true;
}
}
}
if (val == "false") {
alert("FromDate Always Less Than ToDate");
return false;
}
}
and html code is
<asp:TextBox ID="txtFromDate" runat="server" Width="150px" />
<ajaxToolkit:CalendarExtender CssClass="MyCalendar" runat="server"
ID="ceFromDate"
TargetControlID="txtFromDate"
Format="dd/MM/yyyy" />
<asp:TextBox ID="txtToDate" runat="server" Width="150px" />
<ajaxToolkit:CalendarExtender CssClass="MyCalendar" runat="server"
ID="ceToDAte"
TargetControlID="txtToDate"
Format="dd/MM/yyyy" />
<asp:Button ID="btnGenerate" runat="server" CssClass="button"
Text="Generate" OnClientClick="if(!CompareDates()) return false;"
OnClick="btnGenerate_Click" />
the problem is that the page is running well in chrome but when i run my application in IE it throw an error
0x800a138f - JavaScript runtime error: Unable to get property 'value'
of undefined or null reference
please help me to overcome from this problem.
The error is here:
var fdate = document.getElementById('txtFromDate');
var edate = document.getElementById('txtToDate');
The problem is that txtFromDate and txtToDate are the server name of controls, not the client name (look the source of page from the browser).
Try this:
var fdate = document.getElementById('<%=txtFromDate.ClientID%>');
var edate = document.getElementById('<%=txtToDate.ClientID%>');
If your javascript is located in an external JS file (which it should), the posted solutions will not work. But you could give the text fields a unique class name and modify your code as such:
<asp:TextBox ID="txtFromDate" runat="server" Width="150px" CssClass="txtFromDate" />
<asp:TextBox ID="txtToDate" runat="server" Width="150px" CssClass="txtToDate" />
and your javascript:
var fdate = document.getElementsByClassName('txtFromDate')[0];
var edate = document.getElementsByClassName('txtToDate')[0];
Please try this
document.getElementById('<%=txtFromDate.ClientID %>')
Change your code like following:
function CompareDates() {
var fdate = document.getElementById('<%=txtFromDate.ClientID %>');
var edate = document.getElementById('<%=txtFromDate.ClientID %>');
var FromDate = fdate.value.split('/');
var EndDate = edate.value.split('/');
var val = 'false';
if (parseInt(FromDate[2]) < parseInt(EndDate[2])) {
val = 'true';
return true;
}
else if (parseInt(FromDate[2]) == parseInt(EndDate[2])) {
if (parseInt(FromDate[0]) < parseInt(EndDate[0])) {
val = 'true';
return true;
}
else if (parseInt(FromDate[0]) == parseInt(EndDate[0])) {
if (parseInt(FromDate[1]) <= parseInt(EndDate[1])) {
val = 'true';
return true;
}
}
}
if (val == "false") {
alert("FromDate Always Less Than ToDate");
return false;
}
}
You are missing the # for your id reference.
Change from:
var fdate = document.getElementById('txtFromDate');
to:
var fdate = document.getElementById('#txtFromDate');
I was wrong about the above statements.
I was able to fix the same error in my jquery code where I was missing the #. getElementById does not need this special character.
in my webpage in a model PopUp Window i am comparing ages present in two textBox,using javascript but somehow it is not working.
kindly help to overcome from this issue.
Thanks In Advance.
my javascript code is
function CompareAge() {
var maxage = document.getElementById('<%=txtMaxAge.ClientID%>');
var minage = document.getElementById('<%=txtMinAge.ClientID%>');
var val = 'false';
if (maxage>=minage) {
val = 'true';
return true;
}
if (val == 'false') {
alert('Max-Age Alaways greater than or Equal Min-Age');
return false;
}
}
and popup window is like this
<ul>
<li>
<asp:Button ID="btnCancelInPopUpReservation" runat="server" CssClass="button" Text="Cancel" />
</li>
<li>
<asp:Button ID="btnSaveInPopUpReservation" runat="server" CssClass="button" Text="Save" OnClick="btnSaveInPopUpReservation_Click" ValidationGroup="g" OnClientClick="if(!CompareAge()) return false;"/>
</li>
I just tried your piece of code I think the problem lies here you should use .value for getting value in var maxage and var minage.
document.getElementById('<%= txtMaxAge.ClientID %>').value
document.getElementById('<%= txtMinAge.ClientID %>').value
<script type="text/javascript">
function CompareAge() {
var maxage = document.getElementById('<%= txtMaxAge.ClientID %>').value;
var minage = document.getElementById('<%= txtMinAge.ClientID %>').value;
var val = 'false';
if (maxage >= minage) {
val = 'true';
return true;
}
if (val == 'false') {
alert('Max-Age Alaways greater than or Equal Min-Age');
return false;
}
}
I'm using this code to check if a radiobuttonlist has been selected, however it doesn't return false if nothing has been checked, and continues through to the function in the class behind. The radiobutton list is generated from databinding in codebehind.
<asp:LinkButton class="btn" id="linkDelete" runat="server" onclick="link_Delete" OnClientClick="checkform()">Delete Template</asp:LinkButton>
<asp:radiobuttonlist id="optMessageType" runat="server" onselectedindexchanged="optMessageType_SelectedIndexChanged" RepeatDirection="Vertical" CssClass="none-table">
</asp:radiobuttonlist>
function checkform() {
var radiolist = document.getElementById('<%= optMessageType.ClientID %>');
var radio = radiolist.getElementsByTagName("input");
if (radio.length > 0) {
for (var x = 0; x < radio.length; x++) {
if (radio[x].type === "radio" && radio[x].checked) {
//alert("Checking...");
// alert("Selected item Value " + radio[x].value);
var r = confirm("Are you sure you want to delete this template?")
if (r == true) {
//alert("You pressed OK!")
return true;
}
else {
//alert("You pressed Cancel!");
return;
}
}
else {
alert("Select a template to delete");
return;
}
}
}
else {
alert("nope");
return;
}
}
Code Behind:
protected void link_Delete(object sender, System.EventArgs e)
{
Label3.Text = "Deleted!"; //For Testing
}
You should write
<asp:LinkButton class="btn" id="linkDelete" runat="server" onclick="link_Delete" OnClientClick="return checkform();">Delete Template</asp:LinkButton>
i have added return in OnClientClick atribute funcion call
hope this may solve our problem.