asp.net code doesn't call the javascript function - javascript

I am working on a project where I have to show and hide buttons based on drop down selection. Please find the attached fiddler link. My function is not getting called/nothing is happening when I select the drop down values. Any help?!
Page code:
<div class="span6 offset2">
<br />
<div class="row">
Location ID
<select id="iloc_Id" runat="server" class="form-control" style="width: 50%" visible="true" onchange="validate()">
<option disabled="">All Locations</option>
<option value ="1">1- Verona</option>
<option value ="2">2- Como</option>
</select>
</div>
</div>
<br/>
<div class="row">
<asp:LinkButton ID="LinkButton1" CssClass="btn btn-success" runat="server" Width="50%"> First Report </asp:LinkButton>
</div>
<br />
<div class="row">
<asp:LinkButton ID="LinkButton2" CssClass="btn btn-success" runat="server" Width="50%" OnClick="Report2"> Second Report
</asp:LinkButton>
</div>
Javascript:
function validate()
{
var selected_loc = $("#iloc_Id").val();
if (selected_loc == '1')
{
$('#LinkButton1').show();
$('#LinkButton2').hide();
}
else if (selected_loc == '2')
{
$('#LinkButton1').hide();
$('#LinkButton2').show();
}
else
{
$('#LinkButton1').show();
$('#LinkButton2').show();
}
link: https://jsfiddle.net/rickfiddle/5pvwznge/5/

Your code is working fine, just need to add a closing bracket at the end
function validate()
{
var selected_loc = $("#iloc_Id").val();
alert(selected_loc);
if (selected_loc == '1')
{
$('#LinkButton1').show();
$('#LinkButton2').hide();
}
else if (selected_loc == '2')
{
$('#LinkButton1').hide();
$('#LinkButton2').show();
}
else if (selected_loc == '3')
{
$('#LinkButton1').hide();
$('#LinkButton2').hide();
}
else
{
$('#LinkButton1').show();
$('#LinkButton2').show();
}
}
and change the jsfiddle configuration Load Type from
On Load
to
No wrap - bottom of <head>

In the javascript code, after closing validate() function add:
document.getElementById("iloc_Id").onchange = function() {validate()};

Related

Unable to get values from individual check boxes in JavaScript

I am working on an asp.net webforms page. I have three html checkboxes and if any of them are checked I have to append the corresponding values to a JavaScript string. When I execute the btnSave, the saveOrderTypes() is called and goes up to alert("D"); and then exits. I don't see any JavaScript error in the console. I am not sure why this is happening. I tried to get the values using jQuery and similar issue happens.
<asp:Content ID="scriptArea" runat="server" ContentPlaceHolderID="headerScript">
<script>
function saveOrderTypes() {
alert("In saveOrderTypes");
var orderTypes = '';
if (document.getElementById('chkDelivery').checked) {
orderTypes = 'D';
alert("D");
}
if (document.getElementById('chkUPS').checked) {
orderTypes = orderTypes + 'U';
alert("U");
}
if (document.getElementById('chkCustomer').checked) {
orderTypes = orderTypes + 'C';
alert("C");
}
alert("orderTypes: " + orderTypes);
//more code here
}
$(document)
.ready(function () {
});
</script>
</asp:Content>
<asp:Content ID="mainDivision" ContentPlaceHolderID="mainContent" runat="server">
<div class="row" style="width: 100%">
<div class="col-sm-4">
<input type="checkbox" id="chkDelivery">
<label >Delivery</label><br>
<input type="checkbox" id="chkUPS">
<label >UPS</label><br>
<input type="checkbox" id="chkCustomer">
<label >Customer</label><br>
</div>
</div>
<button type="button" id="btnSave" onclick="javascript:saveOrderTypes();return false;"
>Save</button>
</asp:Content>

Textbox should be disabled unless a certain option in the dropdown box is selected

Here's my JavaScript code: it's not working
<script language="javascript" type="text/javascript">
function ShowExpenseReport(Expense_Report_ID) {
var width = screen.width;
var leftpad = (width - 740) / 2;
var jsoption = "width=740,height=700,resizable=no,scrollbars=yes,toolbar=no,titlebar=no,location=no,directories=no,status=no,menubar=no,copyhistory=no,left=" + leftpad + ",top=10";
window.open("Documents/ExpenseReport.aspx?Expense_Report_ID=" + Expense_Report_ID, 'win02', jsoption);
return false;
}
function changetextbox() {
if (document.getElementById("ddlItem").value == '3') {
document.getElementById("txtPurpose").disabled = 'true';
} else {
document.getElementById("txtPurpose").disabled = '';
}
}
</script>
Below is the HTML side:
<asp:TemplateField HeaderStyle-CssClass="innerGridHeader" ItemStyle-CssClass="itemPadding"
ItemStyle-Width="150px" HeaderStyle-VerticalAlign="Top" FooterStyle-VerticalAlign="Top">
<HeaderTemplate>
Item
</HeaderTemplate>
<ItemTemplate>
<asp:Label ID="lblItem" Visible="false" runat="server" Text='<%#Eval("Item_Description") %>'></asp:Label>
<asp:Label ID="lblItemID" Visible="false" runat="server" Text='<%#Eval("Item_ID") %>'></asp:Label>
<asp:DropDownList ID="ddlItem" Width="140px" runat="server" onChange="changetextbox()" CssClass="combobox">
</asp:DropDownList>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderStyle-CssClass="innerGridHeader" ItemStyle-CssClass="itemPadding"
ItemStyle-Width="260px" HeaderStyle-VerticalAlign="Top" FooterStyle-VerticalAlign="Top">
<HeaderTemplate>
Purpose
</HeaderTemplate>
<ItemTemplate>
<asp:Label ID="lblPurpose" runat="server" Width="240px" Text='<%#Eval("Purpose") %>'></asp:Label>
<asp:TextBox ID="txtPurpose" runat="server" Width="240px" CssClass="inputbox" Text='<%#Eval("Purpose") %>'></asp:TextBox>
<asp:RequiredFieldValidator ID="rfvPurpose" runat="server" ErrorMessage="Enter Purpose"
ControlToValidate="txtPurpose" Display="None" ValidationGroup="NER" SetFocusOnError="True">
</asp:RequiredFieldValidator>
<asp:ValidatorCalloutExtender ID="vcePurpose" runat="server" TargetControlID="rfvPurpose"
PopupPosition="BottomRight" WarningIconImageUrl="~/Library/Images/exclamation.png" />
</ItemTemplate>
</asp:TemplateField>
I just want to disable the textboxes when the user chooses entertainment from the dropdown which has the value 3 in the database.
I believe what you are trying to do is disable/enable a textbox field on the basis of select value. A proper way followed in ASP is as follows, try this:
onchange="DisableTextBox();"
<script language=javascript>
function DisableTextBox() {
var dropDown = document.getElementById('<%=DropDown.ClientID%>');
if (dropDown.selectedIndex = ValueTocompare) {
document.getElementById('<%=txtBoxID.ClientID%>').disabled = disabled;
} else {
document.getElementById('<%=txtBoxID.ClientID%>').disabled = '';
}
}
</script>
if this doesn't work out for you, try using this fiddle:
http://jsfiddle.net/SurajMindfire/zxvfcvq0/
This will help you:
dropdown is there contain YES and No value(by default yes),
there is text box, when user select YES value from dropdown textbox will enabled but when select No value then textbox get desabled.
astric is id for validation of textbox
function EnableDisableInputField(customerNarration) {
var selectedValue = customerNarration.options[customerNarration.selectedIndex].value;
var txtOther = document.getElementById("customisedNarration");
txtOther.disabled = selectedValue == 'N' ? true : false;
document.getElementById("asterisk").innerHTML = "";
if (!txtOther.disabled) {
txtOther.focus();
document.getElementById("asterisk").innerHTML = "*";
}
var checkError = document.getElementById("customisedNarration_box").style = "display: none";
}
<div class="form-group ">
<label class="floatinglabel"><sup class="text-red">*</sup> Customer Narration required</label>
<div class="selectwrapper">
<select class="form-control" id="customerNarration" name="customerNarration" onchange="EnableDisableInputField(this)" onfocus="hideerrmsgdelayed('customerNarration')">
<option value="Y">Yes</option>
<option value="N">No</option>
</select>
</div>
<span class="inputError" id="customerNarrationReq_box"><%=siteValidation.getErrorMessage("customerNarration")%></span>
</div>
<div class="form-group ">
<label class="floatinglabel"><sup class="text-red" id="asterisk"></sup> Customised Narration </label>
<input type="text" class="form-control" name="customisedNarration" id="customisedNarration" onfocus="hideerrmsgdelayed('customisedNarration')" maxlength="50" />
<span class="inputError" id="customisedNarration_box"><%=siteValidation.getErrorMessage("customisedNarration")%></span>
</div>

jQuery .click() not working on ajax modalpopupextender button click

I have to invoke ImageButton (in repeater footer) click event from jQuery on response to ajax modalpopupextender button. I tried the below code but it's not working. It doesn't throw any error but PostBack is not happening.
var isCurrentPortalFormSaveClicked = false;
var controlsValuesOnload = '';
var controlsValuesWhileExit = '';
window.onbeforeunload = beforeUnload;
window.onload = getValues;
function getValues() {
controlsValuesOnload = $('form').serialize();
}
function beforeUnload() {
if (isCurrentPortalFormSaveClicked == true) return;
controlsValuesWhileExit = $('form').serialize();
if (controlsValuesOnload != controlsValuesWhileExit) {
return "Your changes have not been saved. To stay on the page so that you can save your changes, click Cancel.";
}
}
function confirmExit(callBackMethod, saveButtonId) {
controlsValuesWhileExit = $('form').serialize();
if (controlsValuesOnload != controlsValuesWhileExit) {
return ShowUnSavedChangesWarning(callBackMethod,saveButtonId);
}
else {
window.open('', '_self', '');
window.close();
return false;
}
}
function ShowUnSavedChangesWarning(callBackMethod, saveButtonId) {
saveButtonControl = saveButtonId;
callBack = callBackMethod;
$find('<%= modalPopUpConfirmExitWarning.ClientID %>').show();
return true;
}
function saveFormAndClose() {
HideUnSavedChangesWarning();
if (callBack != '' && callBack != null && callBack != undefined) {
return callBack();
}
else if (saveButtonControl != '' && saveButtonControl != undefined) {//if the control is other than ribbon save and close button.
saveButtonControl.click();
window.open('', '_self', '');
window.close();
}
else if ($('.saveandclose') != null && $('.saveandclose') != '' && $('.saveandclose') != undefined) {
$('.saveandclose')[0].click();
}
return false;
}
function closeForm() {
isCurrentPortalFormSaveClicked = true;
window.open('', '_self', '');
window.close();
return false;
}
function SaveNewNotes() {
//Save Notes
var notes = $('.newNote').first().val();
if (notes != null && notes != "") {
$('.saveNotes')[0].click();
}
return true;
}
ASPX:
<ajax:ModalPopupExtender ID="modalPopUpConfirmExitWarning" CancelControlID="btnCancel"
runat="server" PopupControlID="panelConfirmExitWarning" TargetControlID="btnHiddenConfirmExitWarning"
BackgroundCssClass="modalBackground">
</ajax:ModalPopupExtender>
<asp:Button runat="server" ID="btnHiddenConfirmExitWarning" Style="display: none" />
<asp:Panel ID="panelConfirmExitWarning" runat="server" Style="display: none" CssClass="ModalWindow">
<div class="window_header">
<span id="spanSubscirptionWindowHeader" runat="server" />
</div>
<div class="window_body">
<img src="../Images/Icon_Warning_New.png" />
<span id="spanConfirmExitExpiryWarning" runat="server" />
</div>
<div class="window_footer" align="right">
<asp:Button ID="btnSave" runat="server" Text="<%$ Resources:DealerWebPortal, DWP_SPAN_Ribbon_Save %>"
OnClientClick="return saveFormAndClose();" CssClass="popUp_button" />
<asp:Button ID="btnDontSave" runat="server" Text="<%$ Resources:DealerWebPortal, DWP_BTN_Page_Home_DontSave %>"
OnClientClick="return closeForm();" CssClass="popUp_button" />
<asp:Button ID="btnCancel" runat="server" Text="<%$ Resources:DealerWebPortal, DWP_BTN_Page_DealerEmailSubscription_Cancel %>"
CssClass="popUp_button" />
</div>
</asp:Panel>
Button (to trigger modalpopupextender):
<a id="lnkClose" class="close" runat="server" onclick="isCurrentPortalFormSaveClicked=true;return confirmExit(SaveNewNotes,null);"> </a>
Repeater:
<asp:Repeater runat="server" ID="rptrCaseNotes" OnItemCommand="rptrCaseNotes_ItemCommand">
<FooterTemplate>
<table>
<tr style="width: 650px">
<td style="vertical-align: middle; width: 50px">
<asp:ImageButton ID="AddNote" Width="16px" Height="16px" ImageUrl="~/Images/112_Plus_Blue_32x32_72.jpg"
runat="server" CommandName="Add" OnClick="OnAddNotes" OnClientClick="isCurrentPortalFormSaveClicked=true" CssClass="saveNotes" />
</td>
<td style="width: 600px">
<asp:TextBox runat="server" ID="NewNotes" Rows="6" Width="600px" Height="80px" TextMode="MultiLine"
MaxLength="2000" CssClass="newNote" />
</td>
</tr>
</table>
</FooterTemplate>

Bootstrap validation with ASP.NET framework 4.5 Web Forms

I have some ASP.NET aspx form that contains:
<div class="form-group input-group" runat="server" id="div_last_name">
<span class="input-group-addon glyphicon glyphicon-user"></span>
<asp:TextBox ID="TextBox4" CssClass="form-control required" runat="server" placeholder="Last Name"></asp:TextBox>
</div>
<div class="form-group input-group" runat="server" id="div_email" >
<span class="input-group-addon">#</span>
<asp:TextBox ID="TextBox1" CssClass="form-control required" runat="server" placeholder="E-Mail"></asp:TextBox>
</div>
I want to validate using this jQuery, but I don't know how to use it.
jQuery(document).ready(function ($) {
$("#btnRegister_Click").click(function () {
var error = 0;
$('input.required').each(function (i, item) {
if ($(item).val() == '') {
$(item).addClass('form-control has-error');
error = 1;
}
else {
$(item).removeClass('form-control has-error');
}
});
if (error) {
return false;
}
});
var min_height = jQuery(window).height();
jQuery('div.col-lg-6 col-lg-offset-3').css('min-height', min_height);
jQuery('div.col-lg-6 col-lg-offset-3').css('line-height', min_height + 'px');
$(".inner", ".boxed").fadeIn(500);
});
Where it says:
$("#btnRegister_Click")
You need to replace that with the name of your button. If it's a regular HTML button, just use the name of your button like:
$("#nameofbutton")
If you using Server Control, you need to get the unique client id of the button. You can do that using:
$('#<%= nameofbutton.ClientID %>')

Why my jquery script doesn't work in my webform which was inherited from MasterPage?

I have a master page and in its head, i have :
<script src="Script/jquery.min.js"></script>
<link href="Stylesheet/Master.css" rel="stylesheet" />
and i have a webform (by name=Login.aspx) which was inherited from my master page, in Login.aspx i have :
<asp:Content ID="Content2" ContentPlaceHolderID="ContentPlaceHolder1" runat="server">
<input id="t1" type="password" placeholder="Passwords" class="login-input-class1" runat="server" ClientID="Static" />
<input id="t2" type="text" placeholder="ConfirmPasswords" class="login-input-class1" runat="server" ClientID="Static"/>
<label class="display" id="lblerror">Error</label>
<script>
$(document).ready(function () {
$("#t2").change(function () {
if ($("#t1").val() === $("#t2").val()) {
$("#lblerror").addClass("display");
}
else {
$("#lblerror").removeClass("display");
}
});
});
</script>
</asp:Content>
and in Master.css i have :
.display {
display:none;
}
But my script does not work, what is the problem?
Because the ID changes at run-time. You should use ClientId for your controls.
You can also use ClientIDMode="Static" to stop the id form changing to it's original.
More Detail about client id mode
$("#<%= Control.ClientID %>").addClass("display");
$("#<%=t2.ClientID %>").change(function () {
if ($("#<%=t1.ClientID %>").val() === $("#<%=t2.ClientID %>").val()) {
$("#lblerror%>").addClass("display");
}
else {
$("#lblerror").removeClass("display");
}
});
Edit 1
<input id="t1" type="password" placeholder="Password" class="login-input-class1"
runat="server" />
<input id="t2" type="text" placeholder="ConfirmPassword" class="login-input-class1"
runat="server" />
And jQuery
$(document).ready(function () {
$("#<%=t2.ClientID %>").change(function () {
if ($("#<%=t1.ClientID %>").val() === $("#<%=t2.ClientID %>").val()) {
$("#lblerror%>").addClass("display");
}
else {
$("#lblerror").removeClass("display");
}
});
});
Seem like you want:
if ($("#t2").val() === $("#t1").val()) {
or:
if ($(this).val() === $("#t1").val()) {
instead of:
if ($("#t1").val() === $("#t1").val()) {

Categories