JQuery not working through Google's CDN - javascript

For a few hours I've been trying to understand what's wrong. My purpose is to enable a button after textfields are filled. Code seems fine according to my test at JSFiddle but it's still not working on my server. Am'I missing something or is this a server problem (which is hard to believe since javascript is client-side)?
PS: I'm not expert at HTML, so I don't know how to identate it's syntax; if it's not that readable I'm sorry and would appreciate an edit-help. thanks.
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<link rel="stylesheet" href="css/style.css">
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script type="text/javascript">
var $input = $('input:text'),
$apply = $('#apply');
$apply.attr('disabled', true);
$input.keyup(function() {
var trigger = false;
$input.each(function() {
if (!$(this).val()) {
trigger = true;
}
});
trigger ? $apply.attr('disabled', true) : $apply.removeAttr('disabled');
});
</script>
</head>
<body>
<section class="container">
<div class="OpenKore">
<div id="absolute">
<form method="GET" action="generate.php">
<fieldset>
<legend><h1>OpenKore Automatic Config:</h1></legend>
LOGIN:
<p><input type="text" id="id_login" name="login_value" value="" placeholder="Login"></p>
SENHA:
<p><input type="text" id= "id_senha" name="senha_value" value="" placeholder="Senha"></p>
PIN:
<p><input type="text" id="id_pin" name="pin_value" value="" placeholder="PIN"></p>
<input id="apply" type="submit" name="commit" disabled value="Gerar Configurações">
</fieldset>
</form>
</div>
</div>
</section>
</body>
</html>

When the browsers reads your HTML page, it reads top to bottom. When it gets to your <script> tags it runs them. Now it us doing this before it has got to the rest of the page, i.e. before it even knows about any body or form or input:text tags, so even though you code will run, it will simply not do anything because none of the elements on the page exist yet.
JavaScript 101, make the code run after the page has loaded, if you need to access elements on the page. How do you do that? either put the code at the bottom of the page (move your <script> tags to just before the </body> tag), or wrap your code in a function that is executed after the browser has finished loading the page. Now jQuery has a very helpful way of doing this for you, pass a function to jQuery and it will be executed after the page is loaded.
jsFiddle does this automatically for you, hence the drop down in the top left corner saying 'onLoad'
i.e. your code
$(); //this is the jQuery function
//This is your code wrapped in a function called 'yourCode'
function yourCode() {
var $input = $('input:text'),
$apply = $('#apply');
$apply.attr('disabled', true);
$input.keyup(function () {
var trigger = false;
$input.each(function () {
if (!$(this).val()) {
trigger = true;
}
});
trigger ? $apply.attr('disabled', true) : $apply.removeAttr('disabled');
});
}
$(yourCode); //this is passing the jQuery function a function,
//this will now be execute once the page is loaded
//or what most people do, pass in as an anonymous function
//which eliminates a step
$(function () {
var $input = $('input:text'),
$apply = $('#apply');
$apply.attr('disabled', true);
$input.keyup(function () {
var trigger = false;
$input.each(function () {
if (!$(this).val()) {
trigger = true;
}
});
trigger ? $apply.attr('disabled', true) : $apply.removeAttr('disabled');
});
});
as suggested by #j08691 I would suggest reading about the document ready in jQuery here

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.

Button Clicked true or false - JavaScript

I am a Bit Beginner In JavaScript. So I need a code about { If we clicked a button a function need to run} more of them suggested this but it still not working ! and I don`t know why? Can you solve it?
if(document.getElementById("btn").clicked == true){
//some code here
console.log("working");
}
<button id=""btn>ClickEvent</button>
Do not use the if. if statement is executed on page load.
Instead, use Onclick() for example :
var data = "";
function clickBtn() {
if(data != "")
document.getElementById("result").innerHTML = "Hello World !";
else
getData();
}
function getData() {
data = "Hello World !";
}
<button onclick="clickBtn()">Click me</button>
<p id="result"></p>
Good question, lets use the an HTML file that references a JavaScript.
So the first file lets call it webpage.html
<!DOCTYPE html>
<html>
<head>
<script src="script.js"></script>
</head>
<body>
<input type="button" value="save" onclick="save()"></input>
<input type="button" value="display" onclick="print()"></input>
<div id="area"></div>
</body>
</html>
And the second file script.js
function save()
{
StringTest="Hello world";
}
function print()
{
document.getElementById("area").innerHTML=StringTest;
}
The approach might be a little different but this is recommended as you would more control over the elements in the script.
For example:
<input type="button" will tell the script that it is a form input of the type button whose click will call the function print() in the JavaScript
document.getElementById("area")captures the elements that we define from the Document Object Model(DOM)

Set value element to a other page called by window.open()

I'm struggling to implement this case, I really appreciate your help.
UPDATE :
page1.html
<html>
<head>
<title></title>
</head>
<body >
<form>
filled value : <input type="text" id="one">
</form>
</body>
</html>
page2.html
<form>
<input type="button" onclick='go();' value='call_page1'/>
</form>
First attempt : page1 shows up, but value is not set
<script>
function go(){
var newWindow;
newWindow= window.open('page1.html', 'form', 'width=400,height=350');
newWindow.document.getElemetById('one').value='xxx';
}
</script>
Second attempt : page1 is not even shown up
<script>
function go(){
var detailsWindow;
detailsWindow = window.open('page1.html', 'form', 'width=400,height=350');
detailsWindow.onload = function{
document.getElementById('one').value='test';
}
}
<script>
Question : setting value' value to page1.html, when it's called in page2.html?
Or if there's an alternative (but please take it easy on me, i'm just learning this stuff ). I don't use JQuery, if there's something unclear, i'm happy to hear it.
regard.
// page1.html
<script>
var newWindow = window.open('page2.html', 'formUntukUpdate', 'width=400,height=350');
newWindow.onload = function(){
newWindow.document.getElementById('one').value = 'ok 2';
};
</script>
// page2.html
<input type="text" id="one" value="ok" />
First of all javascript is case sensetive, and n is missing. so replace getElemetByID with getElementById.
Second is that the code executes immediately and doesn't wait the page to load. You must wrap your code in window.onload :
newWindow.onload = function(){
newWindow.document.getElementById('one').value='xxx';
}
there's 3 bugs in the update:
function in detailsWindow.onload = function must be declared with detailsWindow.onload = function() to work.
your end script is must be replaced from <script> to </script>
you are missing detailsWindow in document.getElementById('one').value = 'test'; it must be detailsWindow.document.getElementById('one').value = 'test';

post form values to html

I want to POST form values and display them on another html page using Javascript. No server-side technology should be used. I have a function that posts the values but to read the values to another html page, I think I am missing something. Below is the code.
Any help? Thanks in advance.
<html xmlns="http://www.w3.org/1999/xhtml" >
<head>
<title>Untitled Page</title>
<script type="text/javascript">
function post_to_page(path, params, method) {
method = method || "post"; // Set method to post by default, if not specified.
var form = document.createElement("form");
form.setAttribute("method", method);
form.setAttribute("action", path);
form.setAttribute("target", "formresult");
for (var key in params) {
if (params.hasOwnProperty(key)) {
var hiddenField = document.createElement("input");
hiddenField.setAttribute("type", "hidden");
hiddenField.setAttribute("name", key);
hiddenField.setAttribute("value", params[key]);
form.appendChild(hiddenField);
}
}
document.body.appendChild(form);
// creating the 'formresult' window with custom features prior to submitting the form
window.open('target.htm', 'formresult', 'scrollbars=no,menubar=no,height=600,width=800,resizable=yes,toolbar=no,status=no');
form.submit();
}
</script>
</head>
<body>
<form id="form1" action="target.htm" method="post">
<div>
USB No: <input name="usbnum" id="usbnum" type="text"/><br />
USB Code: <input name="usbcode" id="usbcode" type="text"/>
</div>
<button onclick="post_to_page()">Try it</button>
</div>
</form>
</body>
</html>
Here is a simple example of moving data from one Window to another
<!-- HTML -->
<textarea id="foo"></textarea><br/>
<input id="bar" value="click" type="button"/>
and the real code to make it work, which assumes you pass the same origin policy
// JavaScript
var whatever = 'yay I can share information';
// in following functions `wnd` is the reference to target window
function generateWhatever(wnd, whatever) { // create the function actually doing the work
return function () {wnd.document.getElementById('foo').innerHTML = whatever};
} // why am I using a generator? You don't have to, it's a choice
function callWhenReady(wnd, fn) { // make sure you only invoke when things exist
if (wnd.loaded) fn(); // already loaded flag (see penultimate line)
else wnd.addEventListener('load', fn); // else wait for load
}
function makeButtonDoStuff() { // seperated button JS from HTML
document
.getElementById('bar')
.addEventListener('click', function () {
var wnd = window.open(window.location); // open new window, keep reference
callWhenReady(wnd, generateWhatever(wnd, whatever)); // set up function to be called
});
}
window.addEventListener('load', function () {window.loaded = true;}); // set loaded flag (do this on your target, this example uses same page)
window.addEventListener('load', makeButtonDoStuff); // link button's JavaScript to HTML when button exists
You can't get POST values using JavaScript. You can use GET method to pass values.
If you are using html5 you can use localStorage. Otherwise a query string or cookies are your other options.
You said you didn't want the server involved...why are you calling submit?
[Edit]
#Paul S's comment/answer looks very helpful. But you might look at something like the jQuery PostMessage plugin if you need it to be cross browser compatible.
http://benalman.com/projects/jquery-postmessage-plugin/
You don't require a POST request to send data from one page to another. Simply use LocalStorage to do the trick. Just call a Javascript function on form submission. This may help:
HTML:
<form id="form1" action="target.htm" method="post">
<div>
USB No: <input name="usbnum" id="usbnum" type="text"/><br />
USB Code: <input name="usbcode" id="usbcode" type="text"/>
</div>
<button onclick="post_to_page()">Try it</button>
</form>
Javascript:
function post_to_page() {
localStorage.value = "Your content here";
window.location = "nextpage.html";
}
This will save the data locally and go to the next page. In the next page, simply call this function to retrieve the stored data:
function get_stored_data() {
alert(localStorage.value);
}
You can simply assign it to a div, textbox other Javascript variable.

FireFox capture autocomplete input change event

I'm trying to subscribe to change events on an input tag for an ajax auto complete form. These change events are not firing when the user clicks an autocomplete suggestion from FireFox.
I've seen fixes for IE, but not FireFox. You can view this behavior here
Steps to recreate:
type any input in one of the boxes and click submit.
Start typing the value again in the same box.
You should see the autocomplete suggestion box appear below the input box. Notice that clicking the suggestion does not fire the change event (it also doesn't fire the click event)
Currently my only option is to disable autocomplete on this field, but I do not want to do that.
Firefox 4+ fire 'oninput' event when autocomplete is used.
Here's some jQuery to make this more actionable:
$('#password').bind('input', function(){ /* your code */});
I've had the same problem.
Apparently, there is password manager debugging available
https://wiki.mozilla.org/Firefox:Password_Manager_Debugging
So I've found that for me DOMAutoComplete event got triggered and
I've managed to attach it sucessfuly to a field via jQuery's bind like
$('#email').bind('DOMAutoComplete',function() { ...
If it makes you feel better, it is a known bug
Proposed workaround: (Not mine, from here
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<html>
<head>
<title>Mozilla Firefox Problem</title>
<script type="text/javascript">
function fOnChange()
{
alert('OnChange Fired');
}
var val_textBox;
function fOnFocus()
{
val_textBox = document.getElementById('textBox').value;
}
function fOnBlur()
{
if (val_textBox != document.getElementById('textBox').value) {
fOnChange();
}
}
</script>
</head>
<body>
<form name="frm">
<table>
<tr>
<td><input type="text" id="textBox" name="textBox" onFocus="fOnFocus()" onBlur="fOnBlur()"></td>
</tr>
<tr>
<td><input type="submit" value="Submit"></td>
</tr>
</form>
</body>
</html>
Another Suggested work around. This time using polling, you can work it in exactly
the same way, checking for "changes" to your field. Tweak the poll value (default to
375ms for your own taste).
I've used jQuery and a jquery plugin someone wrote:
https://github.com/cowboy/jquery-dotimeout/
Git Hub Src: https://raw.github.com/cowboy/jquery-dotimeout/master/jquery.ba-dotimeout.js
<html>
<head>
<meta charset="utf-8">
<title>onChange() for Firefox / IE autofil get-around</title>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4/jquery.min.js"></script>
<script type="text/javascript" src="http://code.jquery.com/jquery-latest.min.js"></script>
<script type="text/javascript" src="/~dsloan/js/ba-dotimeout.js"></script>
<script type="text/javascript">
$(document).ready(function(){
var val;
var count=0; // used to illustrate the "poll count"
// when focusing on the element and typing
// (vs not focused)
// set a focus function to poll the input
$("#myname").focus(function() {
// start polling
$.doTimeout('checkname', 375, function() {
++count;
// no changes, just exit this poll
if($("#myname").val() == val) {
return true;
// store the value
} else {
val = $("#myname").val();
}
var str;
// do stuff here with your field....
if($(document.activeElement) &&
($(document.activeElement).attr('id') ==
$("#myname").attr('id'))) {
var len = $("#myname").val().length;
if(len == 0) {
str = 'Timer called, length 0...';
} else if(len < 2) {
str = 'Timer called, length < 2...';
} else {
str = 'Timer called, valid!';
}
}
// show some debugging...
$("#foo span").html(str+' (count: '+count+'): '+
$(document.activeElement).attr('id')+
', val: '+$("#myname").val());
return true;
});
});
// set a blur function to remove the poll
$("#myname").blur(function() {
$.doTimeout('checkname');
});
});
</script>
</head>
<body>
<form action="#" method=post>
Name: <input type="text" name="name" value="" id="myname" />
Scooby: <input name="scooby" value="" id="scooby" />
<input type="submit" value="Press Me!" />
</form>
<div id="foo"><span></span></div>
</body>
</html>
A possibly alternative: could you simply use a timer to tell when the value of the text box changes?
You're going to have to blur the input field and reset the focus to it. That's going to require a little trickeration though.

Categories

Resources