Validate one button is clicked before another with Javascript - javascript

This is in ASP.NET. We are using a ExtJS frontend, and have our own VB.NET controls to make all the Ext Forms and stuff. However, I hope this can be done in plain javascript. There is already some Javascript on the page for the 'Test Connection' button click and handling the result.
However, I need validation on the screen to make sure that a user tests the connection BEFORE saving the screen. (Hits the test button before hitting the save button) -- EACH time they visit the screen.
Here is the code for the page:
<%# Page Language="VB" Inherits="Core.Web.EditBaseView" %>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
<script language="javascript" type="text/javascript">
function testConnection() {
Global.mask('Testing Connection...');
KBBConnectorController.TestConnection(function(result) { testConnectionCallback(result) });
}
function testConnectionCallback(result) {
Global.unmask();
if (result.Data.Result) {
Global.alert("Connection to KBB Successful.");
}
else {
Global.alertError(result.Data.Messages[0].Text, result.Data.ExceptionId);
}
}
function Validate() {
}
</script>
</head>
<body>
<form id="form1" runat="server">
<div style="display:none">
<% =Html.DropDownList("ddlMarketValues", TryCast(Model.MarketValues, SelectList))%>
</div>
<div>
<%
Using KBBForm As New WebControls.Forms.Form
With KBBForm
.OnValidate = "Validate"
.ID = "KBB"
.ItemName = "connector"
With .Toolbar
.UseDefaultButtons = False
.AddButton(Forms.FormToolbar.ButtonType.Save)
.AddButton(Forms.FormToolbar.ButtonType.Cancel)
.AddButton("Test Connection", "testConnection", "icon-button-testconnection", , "Test connectione")
End With
With .CenterRegion
.Id = "centerRegion"
With .AddFieldSet("Activate Service")
.Id = "activate"
.LabelWidth = 0
Dim cb As New Forms.Control("IsActive", "", "", Model.IsActive, Forms.Control.ControlType.CheckBox)
cb.BoxLabel = "Activate Service"
.AddControl(cb)
End With
With .AddFieldSet("Connection Parameters")
.Id = "params"
.LabelWidth = 150
.AddControl(New Forms.Control("UserName", "", "User Name", Model.UserName, Forms.Control.ControlType.TextField))
.AddControl(New Forms.Control("Password", "", "Password", Model.Password, Forms.Control.ControlType.Password))
.AddControl(New Forms.Control("LoginUrl", "", "URL", Model.LoginUrl))
With .AddControl(New Forms.Control("ddlMarketValues", "", "Market Value", , Forms.Control.ControlType.ComboBox))
.Id = "ddlMarketValues"
End With
End With
End With
Response.Write(.ToString)
End With
End Using
%>
</div>
</form>
</body>
</html>
As you can see I put an OnValidate function in there but it's blank, and you can see that it's tied to the Form as well. I tried fooling around with that but I could only put something together that would ask me to test every single time I clicked Save, and it wouldn't know if I already tested or not.
Any help? Thanks ahead of time.
-Scott

Uh, this should work if I did understand you correctly.
In the code which handles the result of the connection test, set a flag that indicates that the connection has been tested.
In the handler of the Save button check for that flag, and if it's not set display a message of some kind instead of actually performing the saving operation.
Your flag could be global variable which is initially set to false this way the user would be required to run the test each time the visit the page.
As on how you would override/intercept the Save buttons handler... uh... guess you'll have to extend the VB stuff for that.

Why not just hide the save button until the test connection is pressed and the connection works?

Related

Why can't I access javascript function from HTML file?

Fairly basic question here. I've run into a situation where I can't seem to access Javascript functions from within my HTML file, even though I've linked the JS file as a script src. It seems like a pretty simple issue but I can't figure out what the problem is.
I'm trying to add a function called startLogin to an HTML button. I added it as an onclick, but then when I try to click the button, the console says the function is undefined. However the function is clearly defined in the JS file and as far as I can tell the syntax I'm using for the onclick and the script src link is correct.
In addition I've confirmed that the JS file is linked to the HTML file. If I try to manipulate the DOM from the JS file just to do something simple, like set the background to red, that works fine. The problem is when I try to call a function defined in the JS file. Also I've made sure the function I'm trying to call does actually work. If I stick it right in the HTML file inside script tags, it works fine.
I've already tried moving the script tags inside the body at the end of the HTML, as I know that's often the issue, but in this case it didn't work. Can anyone help me identify why I'm unable to access the "startLogin" function from the HTML button?
FYI, this is a javascript project and I'm using Vite.js for bundling. All the other HTML/JS files in my project are playing nicely together, I'm only having an issue with the Login page.
file structure:
|-pages
|-login.html
|-login.js
login.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-
scale=1.0" />
<title>Document</title>
<!-- LINK JS FILE -->
<!-- MODULE TYPE IS RELATED TO VITE.JS -->
<script type="module" src="./login.js"></script>
</head>
<body>
<!-- email login form -->
<form name="emailLogin" id="emailLogin" style="display: none">
<div class="row" style="width: 600px">
<div class="col">
<div class="form-row" style="padding-bottom: 10px">
<input
type="email"
class="form-control"
id="emailAddress"
placeholder="email associated with your login"
style="width: 576px"
/>
</div>
</div>
<div class="form-row">
<br />
<button type="button" class="btn btn-primary" onclick="startLogin('email')">
Send Email Login
</button>
</div>
</div>
</form>
</body>
</html>
login.js
// start the login process by generating a code sent either SMS or EMAIL
function startLogin(login_type) {
// local variables
var ajaxResult;
var subs;
var tempString;
// get the login values and set up the call
if (login_type == "phone") {
// get the values
use_country_code = $("#country").val();
use_phone = $("#phoneNumber").val();
use_phone = use_phone.replace(/\D/g, "");
// do the validation
if (use_phone.length < 10) {
$("#errorText").html(
"Phone number doesn't have enough digits, please try again."
);
$("#errorModal").modal("show");
return;
}
// build the url
post_url =
"https://us-central1-dev-api-327415.cloudfunctions.net/user-login?cc=" +
use_country_code +
"&phone=" +
use_phone;
} else {
// get the values
use_email = $("#emailAddress").val();
// do the validation
if (!validateEmail(use_email)) {
$("#errorText").html(
"Email address does not appear to be valid, please check the format and try again."
);
$("#errorModal").modal("show");
return;
}
// build the url
post_url =
"https://us-central1-dev-api-327415.cloudfunctions.net/user-login?email=" +
use_email;
}
// send the request to the server and process the results
$.LoadingOverlay("show");
$.ajax({
type: "POST",
url: post_url,
// process the returned result of the Ajax call
success: function (ajaxResult) {
// see if we have a session token and handle the response
session_token = ajaxResult["session_token"];
if (session_token == "None") {
// hide the login and show the text message area if phone, otherwise hide email and show email message
if (login_type == "phone") {
$("#loginMethod").hide();
$("#phoneLogin").hide();
$("#codeLogin").show();
$("#loginMessage").hide();
$("#textMessage").show();
} else {
$("#loginMethod").hide();
$("#emailLogin").hide();
$("#loginMessage").hide();
$("#codeLogin").show();
$("#emailMessage").show();
}
} else {
// hide everything since already logged in and show the right message
$("#phoneLogin").hide();
$("#emailLogin").hide();
$("#loginMethod").hide();
$("#loginMessage").hide();
$("#codeLogin").hide();
$("#continueLoginAlready").show();
}
},
// process after the Ajax call has been fully completed
complete: function () {
$.LoadingOverlay("hide");
},
// handle total failure
error: function (jqXHR, exception) {
console.log(jqXHR);
console.log(exception);
json_error = jqXHR["responseJSON"];
$("#errorText").html(json_error.error_message);
$("#errorModal").modal("show");
},
});
}
Javascript modules work a bit differently. There, variables and functions are not exposed to the global scope.
If you want to use your function from other parts of the code, you have to set it explicitly on the window object:
function startLogin(...) {
...
}
window.startLogin = startLogin;
an other solution is to set the js at end of the html, than you don't need to use the window object (memory lag)
<html lang="en">
<head>...</head>
<body>
<button type="button" id="myButton">Title</button>
</body>
<script>
function myFunction(){
console.log('running myFunction');
}
const button = document.querySelector('#myButton');
button.addEventListener('click', function clickListener(
{
myFunction();
}
</script>
</html>
the browser is simply stupid, it loads the page from top to bottom and if you load your js after the body all your html is present and you can do it this way.

inmobi javascript return empty banner

I want to get a test ad banner from inmobi. According to inmobi Developer Wiki
http://developer.inmobi.com/wiki/index.php?title=JavaScript
this script
<script type="text/javascript">
var inmobi_conf = {
siteid : "4028cba631d63df10131e1d3191d00cb",
slot : "15",
test: "true"
};
</script><script type="text/javascript" src="http://cf.cdn.inmobi.com/ad/inmobi.js"></script>
must return test banner 320x50, but it always returns an empty banner.
Please help. What am I doing wrong?
You're getting "No-Fill Response". From that link you provided:
For example, if a publisher faces an NFR (No-Fill Response) scenario,
a callback is sent notifying that there is an NFR. The publisher can
now take steps to address and blank real estate issue that was caused
by non-availability of ads.
<div id="my-ad-slot">
<script type="text/javascript">
var inmobi_conf = {
siteid : "your site id",
slot : "slot number",
test: true,
onError : function(code) {
if(code == "nfr") {
document.getElementById("my-ad-slot").style.display = "none";
// do something else. call to other ad network or logic to display in-house ads, etc.
}
}
};
</script>
<script type="text/javascript" src="http://cf.cdn.inmobi.com/ad/inmobi.js"></script>
</div>
In the above code example, the parameter code will give nfr when no ads are returned.

MVC Razor Ajax Form Submit giving 'unexpexted token u'

This is a MVC VB.NET Razor application. I have a partial view which loads in the bottom of a parent view. And in that partial view I have buttons that when click fire a popup dialog modal window which has a partial view attached to it. The user is supposed to be able to edit the form then click update and the information is then posted to the controller. However I am getting the below error message on submit.
I followed the blog here to get everything wired up. When the update button is clicked there error is occuring here:
Below is the PartialView that contains the buttons and javascript that trigger the popup modal
#ModelTYPE IEnumerable(of data_manager.attendance)
<script src="#Url.Content("~/Scripts/jquery.unobtrusive-ajax.js")" type="text/javascrip</script>
<table>
<tr>
<th>Conf. Number</th>
<th>Class Title</th>
<th>Status of Class</th>
<td>Edit</td>
</tr>
#For Each x In Model
Dim currentItem = x
#<tr>
<td>#Html.DisplayFor(Function(f) currentItem.conf_number)</td>
<td>#Html.DisplayFor(Function(f) currentItem.courseTitle)</td>
#If currentItem.Completed_Class = "Completed" Then
#<td>#Html.ActionLink("Completed(Print Cert)", "Ind_Cert", "Printing", New With {.firstName = currentItem.firstName, .lastname = currentItem.lastName, .classRef = currentItem.course_ref, .cNumber = currentItem.conf_number}, Nothing)</td>
Else
#<td>#Html.DisplayFor(Function(f) currentItem.Completed_Class)</td>
End If
<td>#Html.ActionLink("Modify", "CourseHistoryEdit", New With {.id = currentItem.id}, New With {.class = "editLink"})</td>
</tr>
Next
</table>
<div id="updateDialog" title="Update Attendance"></div>
<script type="text/javascript">
var linkObj;
$(function () {
$(".editLink").button();
$('#updateDialog').dialog({
autoOpen: false,
width: 400,
resizable: false,
modal: true,
buttons: {
"Update": function () {
$("#update-message").html(''); //make sure there is nothing on the message before we continue
$("#updateAttendance").submit();
},
"Cancel": function () {
$(this).dialog("close");
}
}
});
$(".editLink").click(function () {
//change the title of the dialgo
linkObj = $(this);
var dialogDiv = $('#updateDialog');
var viewUrl = linkObj.attr('href');
$.get(viewUrl, function (data) {
dialogDiv.html(data);
//validation
var $form = $("#updateAttendance");
// Unbind existing validation
$form.unbind();
$form.data("validator", null);
// Check document for changes
$.validator.unobtrusive.parse(document);
// Re add validation with changes
$form.validate($form.data("unobtrusiveValidation").options);
//open dialog
dialogDiv.dialog('open');
});
return false;
});
});
function updateSuccess(data) {
if (data.Success == true) {
//we update the table's info
var parent = linkObj.closest("tr");
parent.find(".Completed_Class").html(data.Object.completed);
parent.find(".carDescription").html(data.Object.Description);
//now we can close the dialog
$('#updateDialog').dialog('close');
//twitter type notification
$('#commonMessage').html("Update Complete");
$('#commonMessage').delay(400).slideDown(400).delay(3000).slideUp(400);
}
else {
$("#update-message").html(data.ErrorMessage);
$("#update-message").show();
}
}
</script>
And this is the partialView that is rendered when the Modify button is clicked next to each one.
#ModelTYPE DataModels.DataModels.AjaxCourseHistoryEdit
#Using (Ajax.BeginForm("CourseHistoryEdit", "Admin", Nothing, New AjaxOptions With {.InsertionMode = InsertionMode.Replace, .HttpMethod = "POST", .OnSuccess = "updateSuccess"}, New With {.id = "updateAttendance"}))
#Html.ValidationSummary(true)
#<fieldset>
<legend>Attendance Update</legend>
#Html.HiddenFor(Function(m) Model.attendId)
<div class="editor-label">
#Html.Label("Course Title")
</div>
<div class="editor-field">
#Html.DisplayFor(Function(m) Model.courseTitle)
</div>
<div class="editor-label">
#Html.Label("Completed Status")
</div>
<div class="editor-field">
#Html.DropDownList("completed", New SelectList(ViewBag.CourseStatuses))
</div>
<div class="editor-label">
#Html.Label("Hours Completed")
</div>
<div>
#Html.EditorFor(Function(m) Model.hoursCompleted)
</div>
</fieldset>
End Using
Below are the javascript libraries that are being loaded in the _layout file for the project.
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.10.1/jquery.min.js"></script>
<script src="//ajax.googleapis.com/ajax/libs/jqueryui/1.10.3/jquery-ui.min.js"></script>
<script src="#Url.Content("~/Scripts/jquery.unobtrusive-ajax.js")" type="text/javascript"> </script>
<script src="#Url.Content("~/Scripts/jquery.validate.min.js")" type="text/javascript"></script>
<script src="#Url.Content("~/Scripts/jquery.validate.unobtrusive.min.js")" type="text/javascript"></script>
Any help is greatly appreciated. I have went around with this for hours and google searches have turned up several SO posts saying that Unexpected token u is related to an invalid line termination. This helps me none as I cannot find anything that remotely looks like improper html namely tags that arent closed..
I had a csharper bring up the # on the table and fieldset. This is normal in these instances for vb.net below is a screenshot of the rendered html
A comment made by Moeri pointed me in the right direction. It turned out that my model was using a integer value for the hiddenFor value. Which for reasons unknown to me the AJAX post did not like that at all. By changing the type of attendId from Integer to String and further using proper editorFor / labelFor the issue has been resolved. Maybe this will help someone that hits this stumbling block as I have.

Javascript getElementByID for asp:Image returns null

I am trying to find the control and display set to "block" or "none" on onclientselectedindexchanged event of RadCombobox. It returns always null. The script and controls are in User Control of Content page. There is also Master page for this Content page. I debugged the code with Debugger statement but the control has this tag. "ctl00_content2_ucControl1_imgTest". How can show and hide image? Please let me know. Thanks for your help. Also I tried to use document.getElementById("<%=imgTest.ClientID"); and $find(("<%=imgTest.ClientID") ; but none of these working.
<asp:Image ID="imgTest" ImageUrl="../../../images/test.gif" AlternateText="test"
runat="server" style="display:none"></asp:Image>
<telerik:RadComboBox ID="Combobox1" runat="server" DataTextField="test1"
DataValueField="test_id" NoWrap="true" Width="250" onclientselectedindexchanged="OnClientSelectedIndexChanged"> </telerik:RadComboBox>
<script type="text/javascript">
function OnClientSelectedIndexChanged(sender, eventArgs) {
{
var item = eventArgs.get_item();
if(item.get_value() == "8")
{
var imageControl = document.getElementById('imgTest');
imageControl.style.display = "block";
}
}
</script>
imgTest is a server control, so the client id will be automatically generated by the server.
Change this line:
var imageControl = document.getElementById('imgTest');
to:
var imageControl = document.getElementById('<%=imgTest.ClientId%>');
The issue with your previous attempts was the missing end tag %>
If you are on .net 4.0 you can set the ClientIDMode='Static' and then your code should work fine as intended as long as you aren't in a repeatable element.
Here is some more info on how to use the ClientIDMode:
http://weblogs.asp.net/asptest/archive/2009/01/06/asp-net-4-0-clientid-overview.aspx

How to trigger else clause in an onload event?

I have the Comments handle in my Google App Engine app to display the comments. I want to stop the page from loading if the user (defined as "chooser" here) is not in localStorage.
I get the first 2 alerts: "load event" and chooser: "undefined". Since "chooser" is undefined I expect the else clause to trigger but I don't get the alert in else clause.
Also, the first item in ordered list is displayed but not the rest. So I assume there is an issue with loading of the page. How can I fix this?
class Comments(webapp.RequestHandler):
def get(self):
self.response.out.write("""
<html>
<head>
<title>Choices</title>
<script type="text/javascript">
function showChoices ()
{
alert("load event");
var chooser = localStorage.getItem("chooser");
alert("chooser: " + chooser);
if (chooser)
{
document.getElementById("topten").style.display="inline";
}
else
{
alert("else triggers");
document.write("get an invitation");
}
}
window.onload = showChoices;
</script>
</head>
<body>
<div class="content">""")
#python code:
query = Users.all()
e = query.fetch(10)
self.response.out.write("""<ol>""")
for item in e:
self.response.out.write("""
<div id="topten" class="title" style="display:none">
<li>%s (<span class="small">%s</span>)</li>
</div>
<hr><br />"""
% tuple([item.choice, item.owner]))
self.response.out.write("""</ol>""")
self.response.out.write("""
</div>
</body>
</html>""")
Are you sure that chooser is undefined and not the string literal "undefined"?
see this fiddle i made

Categories

Resources