i have gridview in my aspx page as
<asp:GridView ID="Grid_FeeCategory" Width="100%" CssClass="table table-striped responsive-utilities jambo_table" runat="server" AutoGenerateColumns="False">
<HeaderStyle CssClass="headings" />
<Columns>
<asp:TemplateField>
<HeaderTemplate>
<asp:CheckBox ID="checkAll" runat="server" onclick = "checkAll(this);" />
</HeaderTemplate>
<ItemTemplate>
<asp:CheckBox ID="chkRow" runat="server" onclick = "Check_Click(this)"/>
</ItemTemplate>
</asp:TemplateField>
<asp:BoundField DataField="CatName" HeaderText="Category" />
<asp:TemplateField HeaderText="Category Fee" HeaderStyle-Width="125px">
<ItemTemplate>
<asp:TextBox ID="txtCatFee" runat="server" placeholder="Int or Decimal" style="width:100%" />
</ItemTemplate>
</asp:TemplateField>
<asp:BoundField DataField="FeeCatID" HeaderText="Category ID" HeaderStyle-CssClass="hidden-field" ItemStyle-CssClass="hidden-field"/>
</Columns>
</asp:GridView>
and my custom validator looks like
<asp:CustomValidator ID="CustomValidator1" runat="server" ErrorMessage="Please enter value"
ClientValidationFunction="Validate" ForeColor="Red"></asp:CustomValidator>
i need to validate textbox in gridview when checkbox in the gridview is checked and user leave textbox empty
e-g if user check the checkbox from row 1 of gridview and also leave textbox empty in row 1 and so on.. then custom validator inform to enter value,
for this i got javascript yesterday from google and manipulate it but it does nothing and here is javascript
<script type="text/javascript">
function Validate(sender, args) {
var gridView = document.getElementById("<%=Grid_FeeCategory.ClientID %>");
var fields= gridView.getElementsByTagName("input");
for (var i = 0; i < fields.length; i++)
{
if (fields[i].type == "fields" && fields[i].checked)
{
if (fields[i].type == "text" && fields[i].value.length < 1)
{
args.IsValid = false;
return;
}
}
}
args.IsValid = true;
}
</script>
i check it by using alerts inside script and it cannot enter into this section of javascript
if (fields[i].type == "text" && fields[i].value.length < 1)
{
args.IsValid = false;
return;
}
It is requirement to do this at client side using javascript so i need your help to get out of it
i know this is late one but any one can get help from following function....
I have example related to your logic. you can do this on client side ...
following code is not exactly your requirement but you can manipulate it according to your requirement .
<script type="text/javascript">
function validate() {
var flag = false;
var gridView = document.getElementById('<%= Grid_FeeCategory.ClientID %>');
for (var i = 1; i < gridView.rows.length; i++) {
var inputs = gridView.rows[i].getElementsByTagName('input');
if (inputs != null && inputs.length > 1 && inputs[0] != null) {
if (inputs[1].type == "text" && inputs[0].type == "checkbox") {
var txtval = inputs[1].value;
if (inputs[0].checked && (txtval == "" || txtval == null)) {
flag = false;
break;
}
else {
flag = true
}
}
}
}
if (!flag) {
new PNotify({
title: 'Error',
text: 'Please provide values for "CHECKED" fee categories....!',
type: 'error',
hide: true
});
}
return flag;
}
</script>
and button where you can call above function
<asp:Button ID="btnCalculate" runat="server"OnClientClick="if(!validate()) { return false;}" OnClick="btnCalculate_Click" Text="Calculate" ValidationGroup="Update"/>
if you need any kind of query to understand then please feel free to ask
I tried this code for validating empty field,But it doesn't works properly when call javascript it does not focus on Textbox,and code will execute continues.
Html Code:
<asp:TextBox ID="txtholdername" runat="server" Width="60%"></asp:TextBox>
<asp:TextBox ID="txtusername" runat="server" Width="60%"></asp:TextBox>
<asp:ImageButton ID="btnsave" runat="server" OnClientClick="javascript:return validateRegistrationMaster();" ImageUrl="~/Images/save.png" />
Script
function IsBlank(obj) {
if (obj) {
if (!String.prototype.trim) { String.prototype.trim = function () { return this.replace(/^\s+|\s+$/g, ''); }; }
if ((obj.value.trim().length == 0) || (obj.value == null)) {
obj.focus();
return false;
}
return true;
}
}
function validateRegistrationMaster() {
var Holder_Name = document.getElementById('<%= txtholdername.ClientID %>');
var username = document.getElementById('<%= txtusername.ClientID %>');
if ((!IsBlank(Holder_Name))) {
Holder_Name.focus();
return false;
}
if ((!IsBlank(username))) {
username.focus();
return false;
} return true;
}
Use Required Field Validator instead of custom Javascript, while using Asp.Net Controls.
Example : Click Here W3 Schools Link
Code:
<asp:RequiredFieldValidator ControlToValidate="txtholdername" Text="The holder name field is required!"
runat="server" />
<asp:RequiredFieldValidator ControlToValidate="txtusername" Text="The user namefield is required!"
runat="server" />
I am wondering if it is possible to get the element by id in javascript when there is no form tag available.
I am using the following command to get the text box value but i am getting error message 'null or undefined'. This works fine if i use proper form tag on asp.net page.
var _txt = document.getElementById("txt").value;
Is there any other way of getting textbox values in javascript (when there is no form,body and header tag in asp.net page)
Here is the code
enter code here
<asp:dropdownlist runat="server" ID="ddl" Height="20px"
Width="215px" ValidationGroup="aa">
<asp:ListItem Selected="True" Value="0">--select--</asp:ListItem>
<asp:ListItem Value="1">item-1</asp:ListItem>
</asp:dropdownlist>
<asp:RequiredFieldValidator ID="RequiredFieldValidator1" runat="server"
ControlToValidate="ddl" ErrorMessage="required" InitialValue="0"
SetFocusOnError="True" Display="Dynamic" ValidationGroup="aa"></asp:RequiredFieldValidator>
<br />
<asp:textbox runat="server" ID="txt" ValidationGroup="aa" Width="140px"></asp:textbox>
<asp:RequiredFieldValidator ID="RequiredFieldValidator2" runat="server"
ControlToValidate="txt" ErrorMessage="required" InitialValue=""
SetFocusOnError="True" Display="Dynamic" ValidationGroup="aa"></asp:RequiredFieldValidator>
<br />
</div>
<div>
<asp:validationsummary runat="server" ID="valSummary"
HeaderText="Vendor Ref and Contact are required" ValidationGroup="aa"
CssClass="valsummary">
</asp:validationsummary>
</div>
<asp:Button ID="btn" runat="server" Text="DO" ValidationGroup="aa"
Width="118px" OnClientClick="Test2()"/>
<br />
<script type="text/javascript" language="javascript">
function Test() {
var _indx = document.getElementById('ddl');
var _txt = document.getElementById("txt").value;
if (_indx.selectedIndex == 0 || _txt == '') {
document.getElementById('_div').style.visibility = 'visible';
document.getElementById('_div').style.display = "block";
}
else {
document.getElementById('_div').style.visibility = 'hidden';
document.getElementById('_div').style.display = "none";
}
}
function Test2() {
var _indx = document.getElementById('ddl');
var _txt = document.getElementById("txt").value;
var msg_I = "........"
var msg_II = "...."
var msg_III = ".."
if (_indx.selectedIndex == 0 && _txt == '') {
txtHeader = msg_I
}
else if (_indx.selectedIndex == 0 && _txt != '') {
txtHeader = msg_III
}
else if (_indx.selectedIndex != 0 && _txt == '') {
txtHeader = msg_II
}
document.getElementById('<%= valSummary.ClientID %>').headertext = txtHeader;
} </script>
Change var _txt = document.getElementById("txt").value; to:
var _txt = document.getElementById("<%= txt.ClientID %>").value;
ClientID returns you generated ID to use in your client code.
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
Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
This question does not appear to be about programming within the scope defined in the help center.
Closed 9 years ago.
Improve this question
I am trying to compare many page elements from their initial values to what they are changed by the user, to prompt them to save etc.
Is there a better way to do this check without many if / else statements? A switch doesn't work since there are many different values being check, instead of a single one with many cases. Any and all tips / pointers are welcome, thanks!
if ($('#InitialhidLeadType').val() != $('#hidLeadType').val())
bIsChange = true;
else if ($('#InitialhidProductType').val() != $('#hidProductType').val())
bIsChange = true;
else if ($('#InitialhidFixedFilterType').val() != $('#hidFixedFilterType').val())
bIsChange = true;
else if ($('#InitialhidMinCreditScore').val() != $('#hidMinCreditScore').val())
bIsChange = true;
else if ($('#InitialhidMaxCreditScore').val() != $('#hidMaxCreditScore').val())
bIsChange = true;
else if ($('#InitialhidMinLoanAmount').val() != $('#hidMinLoanAmount').val())
bIsChange = true;
else if ($('#InitialhidMinLTV').val() != $('#hidMinLTV').val())
bIsChange = true;
else if ($('#InitialhidMaxLTV').val() != $('#hidMaxLTV').val())
bIsChange = true;
else if ($('#InitialhidMinCLTV').val() != $('#hidMinCLTV').val())
bIsChange = true;
else if ($('#InitialhidMaxCLTV').val() != $('#hidMaxCLTV').val())
bIsChange = true;
else if ($('#InitialhidPropertyType').val() != $('#hidPropertyType').val())
bIsChange = true;
else if ($('#InitialhidPropertyUse').val() != $('#hidPropertyUse').val())
bIsChange = true;
else if ($('#InitialhidBankruptcy').val() != $('#hidBankruptcy').val())
bIsChange = true;
else if ($('#InitialhidForeclosure').val() != $('#hidForeclosure').val())
bIsChange = true;
else if ($('#InitialhidLoanPurpose').val() != $('#hidLoanPurpose').val())
bIsChange = true;
else if ($('#InitialhidIsCashout').val() != $.trim($('#hidIsCashout').val()))
bIsChange = true;
else if ($('#InitialhidNoCreditScore').val() != $.trim($('#hidNoCreditScore').val()))
bIsChange = true;
else if ($('#InitialhidRelationship').val() != $.trim($('#hidRelationship').val()))
bIsChange = true;
else if ($('#InitialhidCurrentLoanVA').val() != $.trim($('#hidCurrentLoanVA').val()))
bIsChange = true;
else if ($('#InitialhidFoundHome').val() != $.trim($('#hidFoundHome').val()))
bIsChange = true;
else if ($('#InitialhidFHA').val() != $.trim($('#hidFHA').val()))
bIsChange = true;
else if ($('#InitialhidIsConforming').val() != $.trim($('#hidIsConforming').val()))
bIsChange = true;
else if ($('#InitialhidMSA').val() != $('#hidMSA').val())
bIsChange = true;
else if ($('#InitialhidStatedCreditRating').val() != $('#hidStatedCreditRating').val())
bIsChange = true;
else if ($('#InitialhidCampEffectivedate').val() != $('#hidCampEffectivedate').val())
bIsChange = true;
else if ($('#InitialhidCampExpirationdate').val() != $('#hidCampExpirationdate').val())
bIsChange = true;
else if ($('#InitialhidIsFixedFilter').val() != $('#hidIsFixedFilter').val())
bIsChange = true;
else if ($('#InitialhidTestCompaign').val() != $('#hidTestCompaign').val())
bIsChange = true;
else if ($('#InitialhidSelectedStates').val() != $('#hidSelectedStates').val())
bIsChange = true;
else if ($('#InitialhidVolumeTieredPricing').val() != $('#hidVolumeTieredPricing').val())
bIsChange = true;
else if ($('#InitialhidWeekDayCapacity').val() != $('#filterCapacity').val())
bIsChange = true;
else if ($('#InitialhidWeekendCapacity').val() != $('#filterCapacityWeekEnd').val())
bIsChange = true;
else if ($('#InitialhidHolidayCapacity').val() != $('#filterCapacityHoliday').val())
bIsChange = true;
///////////////////////////////////// HTML Below //////////////////////////////////////
<div id = "changeCheck">
<asp:HiddenField ID="InitialhidLeadType" ClientIDMode="Static" runat="server" />
<asp:HiddenField ID="InitialhidProductType" ClientIDMode="Static" runat="server" />
<asp:HiddenField ID="InitialhidFixedFilterType" ClientIDMode="Static" runat="server" />
<asp:HiddenField ID="InitialhidMinCreditScore" ClientIDMode="Static" runat="server" />
<asp:HiddenField ID="InitialhidMaxCreditScore" ClientIDMode="Static" runat="server" />
<asp:HiddenField ID="InitialhidMinLoanAmount" ClientIDMode="Static" runat="server" />
<asp:HiddenField ID="InitialhidMaxLoanAmount" ClientIDMode="Static" runat="server" />
<asp:HiddenField ID="InitialhidMinLTV" ClientIDMode="Static" runat="server" />
<asp:HiddenField ID="InitialhidMaxLTV" ClientIDMode="Static" runat="server" />
<asp:HiddenField ID="InitialhidMinCLTV" ClientIDMode="Static" runat="server" />
<asp:HiddenField ID="InitialhidMaxCLTV" ClientIDMode="Static" runat="server" />
<asp:HiddenField ID="InitialhidWeekDayCapacity" ClientIDMode="Static" runat="server" />
<asp:HiddenField ID="InitialhidWeekEndCapacity" ClientIDMode="Static" runat="server" />
<asp:HiddenField ID="InitialhidHolidayCapacity" ClientIDMode="Static" runat="server" />
<asp:HiddenField ID="InitialhidPropertyType" ClientIDMode="Static" runat="server" />
<asp:HiddenField ID="InitialhidPropertyUse" ClientIDMode="Static" runat="server" />
<asp:HiddenField ID="InitialhidBankruptcy" ClientIDMode="Static" runat="server" />
<asp:HiddenField ID="InitialhidForeclosure" ClientIDMode="Static" runat="server" />
<asp:HiddenField ID="InitialhidLoanPurpose" ClientIDMode="Static" runat="server" />
<asp:HiddenField ID="InitialhidIsCashout" ClientIDMode="Static" runat="server" />
<asp:HiddenField ID="InitialhidNoCreditScore" ClientIDMode="Static" runat="server" />
<asp:HiddenField ID="InitialhidRelationship" ClientIDMode="Static" runat="server" />
<asp:HiddenField ID="InitialhidCurrentLoanVA" ClientIDMode="Static" runat="server" />
<asp:HiddenField ID="InitialhidFoundHome" ClientIDMode="Static" runat="server" />
<asp:HiddenField ID="InitialhidFHA" ClientIDMode="Static" runat="server" />
<asp:HiddenField ID="InitialhidIsConforming" ClientIDMode="Static" runat="server" />
<asp:HiddenField ID="InitialhidMSA" ClientIDMode="Static" runat="server" />
<asp:HiddenField ID="InitialhidStatedCreditRating" ClientIDMode="Static" runat="server" />
<asp:HiddenField ID="InitialhidCampEffectivedate" ClientIDMode="Static" runat="server" />
<asp:HiddenField ID="InitialhidCampExpirationdate" ClientIDMode="Static" runat="server" />
<asp:HiddenField ID="InitialhidIsFixedFilter" ClientIDMode="Static" runat="server" />
<asp:HiddenField ID="InitialhidTestCompaign" ClientIDMode="Static" runat="server" />
<asp:HiddenField ID="InitialhidSelectedStates" ClientIDMode="Static" runat="server" />
<asp:HiddenField ID="InitialhidVolumeTieredPricing" ClientIDMode="Static" runat="server" />
Iterate the elements, compare each one, and if there are changes, prompt the user to save:
var save = false;
$('[id^="Initial"]').each(function() {
if ( this.value != $('#'+this.id.replace('Initial','')).val()) save = true;
});
if (save) confirm(' would you like to save ');
Normally you'd solve this a different way, by changing a variable when the element is changed, and not with a check of all elements at some time:
var save = false;
$(':input').on('change', function() {
save = true;
});
window.onbeforeunload = function() {
if (save) confirm(' would you like to save ');
}
Change your approach. Rather than checking all the values for changes, intercept the change event for your form to set your flag when an input is changed:
$('#some-form-element').on('change', function (e) {
// ... set flag here
});
This would tell you if any form elements had their value changed at any point.
var formIsDirty = false;
$(document).ready(function() {
$(':input').change(function() {
formIsDirty = true;
});
});
Of course, if they change the value back to the original value, it won't tell you that. If that isn't enough, you could do this:
$(document).ready(function() {
$(':input').each(function() {
$(this).data('original', $(this).val());
});
});
Then when you validate:
var formIsDirty = false;
$(':input').each(function() {
if ($(this).data('original') != $(this).val()) {
formIsDirty = true;
return false;
}
});
The second option would let you do away with your hidden "initial values" fields.
Try this:
var map = [
['#InitialhidLeadType', '#hidLeadType'],
['#InitialhidProductType', '#hidProductType'],
['#InitialhidFixedFilterType', '#hidProductType']
// etc..
];
for (var i = 0; i < map.length; i++) {
if ($(map[i][0]).val() != $(map[i][1]).val()) {
bIsChange = true;
break;
}
}
I'd say a combination of the two approaches that adeneo and ACEfanatic02 suggested . . . with a twist:
$("input:visible").change(function() {
var currID = $(this).prop("id");
var initialValContainer = $("#Initial" + currID);
if (initialValContainer.length > 0) {
var currVal = $.trim($(this).val());
var initialVal = $.trim(initialValContainer.val());
if (currVal === initialVal) {
$(this).addClass("changed");
}
else {
$(this).removeClass("changed");
}
}
});
At that point, whenever you are ready to check to see if you want to save, you can use the following code to see if it is necessary:
if ($(".changed").length > 0) {
**prompt to save**
}
That way, the code will only prompt if at least one of the inputs has been tagged as changed. This approach will also allow you to "untag" inputs that the user returns to their original value, as well as "reset" all the inputs if you need to with $(".changed").removeClass("changed") (e.g., if you are saving the new values without a page reload).