Why does my javascript function result in a rangeError? - javascript

Fairly new to this. I read a bunch of answers with people having a similar problem. I tried all the solutions offered (using e.stopPropagation, using e.stopImmediatePropagation, using id instead of tag...) but nothing worked. I deployed a single html page through firebase.
I wrote the script directly in the html. Here's my code:
function onclick(e) {
/*e.stopPropagation() and e.preventDefault() --YIELDD SAME RESULT*/
e.stopImmediatePropagation()
console.log("hello")
}
<h3>Please update your information below</h3>
<form id="login-form" class="reset-form">
<label>Email:</label>
<input name="email" type="email" placeholder="#">
<label>New Password:</label>
<input name="password" type="password">
<label>Confirm Password:</label>
<input name="second-password" type="password">
<button id="submit-button" type="button" onclick="onclick()">Update</button>
</form>
</div>
</body>
Desired behavior: on click, button with id logs a message in the devtools console.
p.s. I'm sure there's a basic mistake I'm making but I am not able to find which one. Please help!

onclick is the name of a common DOM property. When a function with this name exists in the Global scope (as yours does), it essentially becomes a property of the window object and can overwrite the Global one. Call your callback function something else or move it out of the Global scope and it will work.
Also, e.stopImmediatePropagation() is most likely not required for your use case.
Finally, nothing can come after </body> except </html>. <script> elements are allowed in the head and body, but no where else.
<h3>Please update your information below</h3>
<form id="login-form" class="reset-form">
<label>Email:</label>
<input name="email" type="email" placeholder="#">
<label>New Password:</label>
<input name="password" type="password">
<label>Confirm Password:</label>
<input name="second-password" type="password">
<button id="submit-button" type="button" onclick="onclick1()">Update</button>
</form>
<script>
function onclick1(e) {
console.log("hello")
}
</script>
Now, since you are just learning all this, let's make sure you get off on the right foot. There is soooo much bad HTML and JavaScript floating around and bad habits are still used today because most people don't know any better so they just copy/paste someone else's code that seems to work.
Don't use inline HTML event handlers (onclick, onmouseover, etc.) in the first place. Separate your JavaScript from your HTML and follow modern, standards based code. There are many reasons to not use inline HTML event handlers. Instead, use the .addEventListener() method.
Next, the <label> element is a semantic element that works in one of two ways:
It has a for attribute that has a value that is identical to the
form field that it is the label "for":
<label for="txtFirstName">First Name:</label>
<input id="txtFirstName">
It contains the form field element that is is a label for:
<label>First Name: <input id="txtFirstName"></label>
In either case, you are telling the client that there is a relationship between the label and the form field it is a label for. This allows a user to click or touch the label and activate the form field. It is also very helpful to those who rely on assistive technologies (like screen readers) to use the web.
So, putting all this together, your code reworked would look like this (I've added just a little CSS to make the page a little cleaner to look at, but none of that is required):
label { display:block; width:200px; margin-bottom:.5em; }
button { margin-top: 1em; font-size:1.2em; padding:5px; }
<h3>Please update your information below</h3>
<form id="login-form" class="reset-form">
<label>Email: <input name="email" type="email" placeholder="#"></label>
<label>New Password: <input name="password" type="password"></label>
<label>Confirm Password: <input name="second-password" type="password"></label>
<button id="submit-button" type="button">Update</button>
</form>
<script>
// get a reference to the DOM element you want to work with
let btn = document.getElementById("submit-button");
// configure the event handler in JavaScript, not in HTML
btn.addEventListener("click", logToConsole);
// give your functions meaningful names
function logToConsole(e) {
console.log("hello")
}
</script>

<button id="submit-button" type="button"
onclick="onclick()">Update</button> causes an infinite loop. You're overriding the onclick method which basically makes your code say "When I'm clicked, click me" ad infinitum.
Change the name of function onclick() to anything else, like function hello() and it'll work.
Here's a working codepen you can play with. https://codepen.io/anon/pen/mzajGd

I think it's best to change which event your stopping, which seems to be the form submit. Unsure why you're getting the range issue, but this should work.
<!DOCTYPE html>
<html>
<body>
<form id="login-form" class="reset-form" >
<label>Email:</label>
<input name="email" type="email" placeholder="#">
<label>New Password:</label>
<input name="password" type="password">
<label>Confirm Password:</label>
<input name="second-password" type="password">
<input type="submit">Update</button>
</form>
<script>
document.getElementById("login-form").addEventListener("submit", function(event){
event.preventDefault();
alert('boogy');
});
</script>
</body>
</html>

Hi Steve and welcome to Stack Overflow.
First place your Button, there are several ways to acomplish this:
<button class="ui-btn" id="cmdHello">Push Me</button>
Yet another Button
Now react to it's Click event:
<script type="application/javascript">
$(document).bind("pageinit", function() {
$(document).on("click", "#cmdHello", function(evt) {
console.log("Hello World");
});
});
</script>
That should do the trick.

Related

Why can't my javascript redirect the following code, I've tried multiple solution that i found in StackOverFlow

I have tried multiple of things making the code to redirect, my teacher told me that I need to use method POST, while the following code is the working one which the method get, if I change the method to POST it cannot redirect. I tried using the location.href inside my code, it doesn't seem to work at all. I even tried putting the return false in my javascript. May I know how can I fix these issues?
The following are my code for my form
<form action="/Membership/member-profilepage/member_home.html">
<div class="row">
<div class="col-1">
<input type="text" name="username" placeholder="Username" required>
<input type="password" name="password" placeholder="Password" required>
<input type="checkbox" id="rmbpw" name="rmbpw" value="rmbpw">
<label for="rmbpw" id="rmbpw" name="rmbpw"> RememberMe</label>
<input type="submit" value="Login" onclick="login()">
</div>
<script src="login.js"></script>
</div>
</form>
This will be the code for my javascript
function login(){
alert("Login Successfully!");
}
Oh, Guys, I figure out an answer after doing a couple more research and trying a few more things. I cannot use input type="submit". Hence, I need to use input type="button" to do the redirection.

google apps script sidebar form Send button not working

I'm creating a google add on for sheets. The sidebar I'm working on is intended to be sort of help ticket submission, but way before I can develop that part of things, I'm not getting the submit button in the form to call the javascript function I want to build.
I've removed all of the form data from the html button call to activate a Logger.log. No dice.
I created a completely separate (and very simple) button to call a different function to call Logger.log. This also did not work.
I've double checked the form data, the send call, and the function.
I made sure the name of the function (sendMsg) is unique.
I think that the issue may not be in my code but in some other way the html and javascript (.gs) are connected.
here is the html form:
<div class="block form-group">
<form>
<label for="reason">Purpose of Contact</label>
<select id="reason">
<option selected>Help Request</option>
<option>Feature Request</option>
<option>Error Report</option>
<option>Other</option>
</select>
<label for="email">Email</label>
<input type="text" id="email" style="width: 200px;">
<label for="phone">Phone</label>
<input type="text" id="phone" style="width: 120px;" value = "optional">
<br>
<label for="translated-text">
<b>Message</b></label>
<textarea id="userMsg" rows="15" cols="35">
</textarea>
<br>
<input id="app" name="appSrc" type="hidden" value="COE">
<input type="button" class="action" name="helpRequest" value="SEND" onClick="google.script.run.sendMsg(
document.getElementById('reason').value,
document.getElementById('email').value,
document.getElementById('phone').value,
document.getElementById('userMsg').value,
document.getElementById('appSrc').value
)" />
</form>
</div>
and here is the function called:
function sendMsg(appSrc,reason,email,phone,userMsg) {
appV = appSrc;
reasonV = reason;
emailV = email;
phoneV = phone;
userMsgV = userMsg;
Logger.log('cheese');
}
Right now the form should simply result in a Logger.log message. At this point nothing happens.
In your situation, when "SEND" button is clicked, the script of sendMsg() at Google Apps Script side doesn't work.
You want to run sendMsg().
If my understanding is correct, how about this modification?
Modification point:
When I saw <input id="app" name="appSrc" type="hidden" value="COE">, appSrc is not id. By this, an error occurs at document.getElementById('appSrc').value, and sendMsg() didn't work. So if your script is modified, for example, please use app.
From:
document.getElementById('appSrc').value
To:
document.getElementById('app').value
Or
From:
<input id="app" name="appSrc" type="hidden" value="COE">
To:
<input id="appSrc" name="appSrc" type="hidden" value="COE">
If I misunderstood your question and this was not the result you want, I apologize.
In case anyone has the same issue as I had... onpress doesn't seem to work here. I had to change it to onclick.

Any way to use JavaScript to *not* set focus on any HTML element?

I have a mobile signup form that contains HTML input elements for the user's username, password, and password confirmation fields. Since this is a mobile web app and I'm trying to conserve screen space, I've elected to forego putting HTML labels above each of these elements and instead utilize placeholder attributes to signal what to enter in each field:.
<input id="id_username" placeholder="Choose a username" type="text" />
<input id="id_password1" name="password1" placeholder="Choose a password" type="password" />
<input id="id_password2" name="password2" placeholder="Confirm password" type="password" />
Initially I added a bit of JavaScript to put the focus on the username field when the user arrives at the page:
<script type="text/javascript">
document.getElementById("id_username").focus()
</script>
This worked fine except that in older versions of the default Android browser, this causes the placeholder to disappear. Since the lack of a placeholder (and label) may cause the user to not be clear on what to enter in that field, I took the JavaScript out. However, even without that JS, I'm noticing that the Android browser still puts the focus in that first form field which again deletes the label. Is there any way that I can code the page so that I'm guaranteed that no browser (including the default Android browser) will put focus on any of these fields? Techniques that wouldn't require additional libraries would be preferable as I'm trying to keep my page size and additional requests to a minimum.
Thanks.
Sometimes it is faster to write some simple functionality by your hands. Look at the example at js fiddle. If you want you can replace jquery with native javascript.
https://jsfiddle.net/ShinShil/y7o8mrwh/2/
var placeholder = 'enter something';
$(document).ready(function() {
$('.placeholder').val(placeholder);
$('.placeholder').focusin(function() {
if($(this).val() == placeholder && $(this).hasClass('opacity')) {
$(this).val('');
$(this).removeClass('opacity');
}
});
$('.placeholder').focusout(function() {
if($(this).val() == '') {
$(this).val(placeholder);
$(this).addClass('opacity');
}
});
});
If your controls are in forms, you can loop over all controls in all forms and call their blur method:
function blurAll() {
[].forEach.call(document.forms, function(form) {
[].forEach.call(form.elements, function(element) {
element.blur();
});
});
}
<body onload="blurAll()">
<form>
<input name="one" placeholder="enter something"><input name="two" placeholder="enter something">
</form>
<form>
<input name="one" placeholder="enter something"><input name="two" placeholder="enter something">
</form>
</body>
Note that for IE8 you'll need a polyfill for Array.prototype.forEach.
Edit
Perhaps a simpler solution is to use document.activeElement:
function blurActive() {
if (document.activeElement && document.activeElement.blur) {
document.activeElement.blur();
}
}
<body onload="blurActive()">
<form>
<input name="one" placeholder="enter something"><input name="two" placeholder="enter something">
</form>
<form>
<input name="one" placeholder="enter something"><input name="two" placeholder="enter something">
</form>
<p>Click on the button, then on an input to give it focus. It will be blurred in 5 seconds.</p>
<button onclick="setTimeout(blurActive,5000);">Blur active in 5 seconds</button>
</body>

My form always submits when the button is clicked, no matter what I do

I have a relatively simple form. I am using jQuery to select the submit button, and as of right now, I'm just trying to display an alert when clicked.
The Problem: The button is using it's default action, no matter what I do. So basically, no alert displays, and I'm stuck with the submitted parameters which are appended to the end of the url in my address bar.
I have tried using e.preventDefault();, e.preventDefault(true);, e.stopImmediatePropogation(), and e.stopImmediatePropogation(true);.
I've even tried putting those in a document.ready() block.
The registration form is in a modal panel, though I don't think that should matter... (Should it?)
I guess now I'll show you the code. I really don't understand why it's not working. I'd appreciate any help:
HTML: http://pastebin.com/bHCC58w4 (full document)
<form id="registerForm">
<a class="close"></a>
<h3>Register Today! - It's FREE!</h3>
<p>Registering only takes seconds, and puts you into direct contact with a designer. On top of all that, you can add documents, images, and other files to your project dashboard. What are you waiting for? It's free!</p>
<img src="images/formfish.png" alt="Goldy the goldfish helps users register. It looks like he stepped out for a minute. Sorry about that!" />
<input type="text" id="name" name="name" placeholder="Your full name." title="We just need your first and last name." class="masterTooltip" />
<input type="email" id="email" name="email" placeholder="Your email." title="We won't send you spam. Pinky swear." class="masterTooltip" />
<input type="text" id="userName" name="userName" placeholder="Your username." title="Your username must be unique." class="masterTooltip" />
<input type="password" id="password" name="password" placeholder="Your password." title="Make your password hard to guess." class="masterTooltip" />
<button id="register">Sign up</button>
</form>
JAVASCRIPT: http://pastebin.com/bD2fYPsh (full document)
$("#register").on("click", function(e){
e.preventDefault();
alert("Hello!");
});
Here is a semi-live version of the site. It's got no working functionality other than the jQuery animations. I don't know if it will help you guys or not: http://graphicgoldfish.com/creativecodefish/
Change the button so it's just a button, not a submit button:
<button id="register" type="button">Sign up</button>
By default, buttons are of the type submit which will cause the form itself to submit.
There are a bit different event handlers. I think you are better off using plain javascript for this:
document.getElementById("register").addEventHandler("click", function(e){
e.preventDefault(); // etc
}

Mimicking a login form...

We have an internal application that requires the same username/password across the board.
However, if the login fails too many times, then the account is locked for that username.
We can't change the lockout because that will affect the public facing site as well.
I have been asked to come up with a way to essentially, click a button and auto-login.
Initial research has brought me to this script... (Credit)
<!doctype html>
<!-- saved from url=(0014)about:internet -->
<html>
<title>Auto Login</title>
</head>
<body>
<form id="loginForm" name="loginForm" method="post" action="http://mail.google.com">
<select name="uni_url" id="logServer" class="validate[required]">
<option class="" value="" fbUrl="" cookieName="" >
Test_en
</option>
</select>
<input id="loginName" name="name" type="text" value="Username" class="" />
<input id="loginPassword" name="password" type="password" value="ExamplePassword" class="" />
<input type="hidden" id="loginKid" name="kid" value=""/>
</form>
<script>document.loginForm.submit();</script>
</body></html>
...but I can't seem to get it to work for me.
So, I found another option where I can create a small html file (form) with a submit button, that does - onload="form1.submit();", and this could basically log me into this website without having to key in any login information.
Not sure where to start with mimicking a login form like this and need a good direction to get started in.
Thoughts?
Let's assume your existing login form looks like this:
<form action="/login.php" method="post" id="loginform">
<input type="text" name="username" />
<input type="password" name="password" />
<input type="submit" />
</form>
On your "auto-login" (which is really an auto-submit) page you want to mimic the same structure as before but:
Add in values to be submitted (static username and password?)
Optionally remove the submit button (if you know your users have JS enabled then you can get rid).
Add some JS that automagically submits the form for you.
That might give us something like this:
<form action="/login.php" method="post" id="loginform">
<input type="text" name="username" value="gvee" />
<input type="password" name="password" value="hunter2" />
</form>
<script type="text/javascript">document.forms[0].submit()</script>
The javascript will essentially look for the first form on the page (forms[0]) and submit that.
Update
Upon further inspection your existing login form is a bit of a funny onion. Instead of submitting the form directly, it's calling a function called doLogin() that sets certain hidden properties.
Therefore, instead of submitting the form, we should mimic the same behaviour (i.e. call doLogin() instead of .submit()).
One key thing here is that you'll want to only call the function after it has been declared. Simplest solution is to put our added bit of script at the very bottom of the HTML.
<script type="text/javascript">doSubmit();</script>

Categories