I am battling to get my javascript function to fire when a button is clicked on my html page.
My html code snippet:
<!DOCTYPE html>
<html>
<head>
<title>VLA SYSTEM</title>
Logout
<script
type ="text/JavaScript" src="logout.js"></script>
</head>
<body>
<form>
<script
type ="text/JavaScript" src="regGen.js"></script>
<script
type="text/JavaScript" src="submit.js"></script>
<input type="button" name="btnAssign" value="Assign Owner To Registration Number..." onclick="submit()">
My javascript code snippet:
function submit() {
window.alert("Information Captured And Stored To Database!");
}
The idea is that, when the user clicks on the button, the alert should fire informing the user that information has been captured, however, I am unable to get this alert to appear.
Any advice would be greatly appreciated.
The problem is that, unintuitively, inline handlers essentially implicitly use with (this) for the element that triggered the event, and for the parent element, and so on:
<form>
<input type="button" name="btnAssign" value="Assign Owner To Registration Number..."
onclick="console.log(submit === document.querySelector('form').submit)"
>
</form>
And form.submit is a built-in function will submit the form.
Either use a different function name, like doAlert:
onclick="doAlert()"
and
function doAlert() {
window.alert("Information Captured And Stored To Database!");
}
Or attach the listener properly using Javascript instead (inline handlers are pretty bad practice, and can result in unintuitive behavior like you're seeing):
document.querySelector('input[name="btnAssign"]).addEventListener('click', submit);
Related
So I have an HTML document with jQuery Mobile and a form element like so:
<head>
<!-- Include jQuery Mobile stylesheets -->
<link rel="stylesheet" href="lib/jquery.mobile-1.4.5.min.css">
<!-- Include the jQuery library -->
<script type="text/javascript" src="lib/jquery-1.11.3.min.js"></script>
<!-- Include the jQuery Mobile library -->
<script type="text/javascript" src="lib/jquery.mobile-1.4.5.min.js">
</script>
</head>
<body>
<form onsubmit="myFunction()" id="myForm">
<input type="text">
</form>
<button type="submit" form="myForm">Submit</button>
<script>
function myFunction() {
//does somethign with form values
}
</script>
</body>
When the form is submitted, I want JavaScript to handle to field values (through a function called by onsubmit. I don't want to send it over to another document. That is why I have left out the action attribute. However, when I hit submit, jQuery Mobile gives me the following message: "error loading page" (see the picture). What can I do? I need the form to be submitted because I need the form to validate the fields when the button is clicked. That's why I can't just make a button that onclick calls a function that grabs the values of the fields.
Any help is much appreciated!!
Thanks in advance!
You could try preventing the event generated by submitting the form and returning false from js so that the js function gets called but the form does not get submitted
<form onsubmit="myFunction(event)" id="myForm">
<!-- ^^^^^ -> pass the event -->
<input type="text">
</form>
<button type="submit" form="myForm">Submit</button>
<script>
function myFunction(e) {
//^ get the event so we can prevent
e.preventDefault();
//does somethign with form values
return false;
}
</script>
I've been trying to understand jQuery delegation by writing a short script, but I encountered 2 problems.
<!DOCTYPE html>
<html>
<head>
<script src="jquery.min.js"></script>
</head>
<body>
<input type="text" id="text" />
<div id="msg"></div>
<script>
function showMsg() {
if ($("#text").val() === "") {
$("#msg").html("Your input is empty");
} else {
$("#msg").html("You have entered something")
}
}
$("#text").on("blur", showMsg());
</script>
</body>
1). This event delegation doesn't work as expected, the message "Your input is empty" always shows itself indefinitely. How to fix this?
2). In the showMsg() function I have to explicitly use $("#text") for the script to work, if I use $(this) it won't work. What if I have a lot of input fields that need to use this function, is it possible to uniformly define the function so that those input fields can use it without having to change anything in the function?
All you need to do is change
$("#text").on("blur", showMsg());
to
$("#text").on("blur", showMsg);
This will also fix your $(this) problem. You can set that back now.
I'm starting to experiment with building Chrome extensions (first exposure to HTML and Javascript as well) and got stuck on a basic task. I have the popup.html file, which is what the user sees. What I'd like to do is have some placeholder text that is initially displayed to the user. The popup will also have a button so that when the user clicks on the button the placeholder text is replaced with something else.
Here is what I tested:
popup.html:
<!doctype html>
<html>
<head>
<title>Test Extension</title>
<script src="popup.js"></script>
</head>
<body>
<form id="testForm">
<input id="testButton" type="submit" value="testButton" />
</form>
<h3 id="textHeader">This will change.</h3>
</body>
</html>
popup.js:
function changeText() {
document.getElementById('textHeader').innerHTML = 'Changed!';
}
document.addEventListener('DOMContentLoaded', function () {
document.getElementById('testForm').addEventListener('submit', changeText);
});
When I debug the script, I see the initial addEventListener call which calls changeText and causes the text in the popup to change to 'Changed!'. However, I then see a second call of the addEventListener, which then reverts back to the original popup.html form. The net effect is that 'Changed!' only appears for a brief instant.
Is there a way to make changes to the HTML file in an event listener permanent to get the intended behavior? I realize that I really need to gain an understanding of the DOM model and how Javascript can interact with it in the browser. I'm looking for a book or some other resource to consult (the Mozilla Developer Network site looked like a good authoritative source, but seemed kind of sparse), but in the meantime was hoping to gain at least some additional understanding by working through this simple example. Thanks!
EDIT:
Thank you everyone for the prompt responses! Disabling the form submissions makes sense. I'm adding this edit to my question post because the original task I was trying to achieve did in fact need to make use of a form.
What I'm trying to do is take in input from the user through a form, query an external site (ex: Wikipedia) for the phrase that user typed in, and then display in the popup content that's taken from the query.
Here is a skeleton outline of what I attempted:
popup.html:
<!doctype html>
<html>
<head>
<title>Test Extension</title>
<script src="popup.js"></script>
</head>
<body>
<form id="WikipediaForm">
<input type="text" id="userQuery" size="50"/>
<input id="submitQuery" type="submit" value="Ask Wikipedia" />
</form>
<h3 id="WikipediaResponse">placeholder</h3>
</body>
</html>
popup.js:
function changeText() {
var req = new XMLHttpRequest();
askURL = 'http://en.wikipedia.org/wiki' + encodeURIComponent(document.getElementById('userQuery').value);
req.open("GET", askURL, false);
req.onload = function (e) {
if (req.readyState === 4) {
if (req.status === 200) {
document.getElementById('WikipediaResponse').innerHTML = req.responseText; // i'm just dumping everything for now
}
} else {
console.error(req.statusText);
}
}
};
req.send(null);
}
document.addEventListener('DOMContentLoaded', function () {
document.getElementById('WikipediaForm').addEventListener('submit', changeText);
});
This again also faces the same issue that I saw with the previous example where the response flashes for an instant before reverting back to the placeholder text. However, I can't follow the earlier answers now because I need the form to be submitted. What is the usual way of changing content in an event listener for a form?
On another note, I'm using the synchronous XMLHttpRequest call, which I know isn't recommend. But when I used the asynchronous call it didn't seem to go through and I couldn't figure out how to fix that, so that's another problem I'm also working on.
Use:
function changeText() {
document.getElementById('textHeader').innerHTML = 'Changed!';
//Returning false will prevent that the form submission completes
return false;
}
But if your form is never going to send data anywhere, you don't need a form at all (unless you're going to use a reset button for your fields). So you can just add type="button" to your element.
<body>
<input id="testButton" type="button" value="testButton" />
<h3 id="textHeader">This will change.</h3>
</body>
You need to return false from the event handler to prevent the normal form submission after the handler runs:
function changeText() {
document.getElementById('textHeader').innerHTML = 'Changed!';
return false;
}
Something is wrong here, and all the suggestions I've tried from others with similar questions don't seem to work.
I have two files: myPage.html and myCode.gs in google scripts. I have deployed the html file as a web app, and I have figured out (with help) how to make the onclick event for the 'submit' button to trigger the emailTech function from the myCode.gs file just fine.
Now I want to insert the value from the text box in the html file into the email that is called from the onClick event. I have tried document.getElementById('textBoxId').value, but I get the following error "Reference Error: "document" is not defined. " What gives?
myPage.html file:
<html>
<head>
<title>Test Page</title>
</head>
<body>
<input type="button" onClick="google.script.run.emailTech();" value="Submit" />
<input type="text" value=" " id = "textBox" name = "textBox" />
</body>
<script type="text/javascript">
</script>
</html>
myCode.gs file:
function doGet() {
return HtmlService.createHtmlOutputFromFile('myPage');
}
function emailTech(){
var nameBox = document.getElementById('textBox').value;
var message = "This is the text box value" + nameBox;
MailApp.sendEmail("123#xyz.com", "This is the subject", message );
}
The error message is correct - in your Apps Script function emailTech(), there is no variable in scope that's named document.
You've got two different ways of deploying Apps Script WebApps mixed up. Since you're using the HTML Service (and your user interface is an html file), you can't use the UI Service methods (like getElementById()) to access input values. So, you'll do something different.
To tie the submit button and input field together, use a form, enclosed in <form> tags. The submit button will still have an onclick function, but now it will be a javascript function embedded in your HTML, which will pass all the input from the form to your emailTech() function.
In your apps-script-side handler, you'll receive the form input as an Object, with the fields from the form as key-value pairs. The key is the name from the field.
The general solution is described in this answer. Here's a version that fits your code. I've left out the success and failure handling that Arun shows. You should build in error checking before deploying this in real life, of course.
Code.gs
function doGet() {
return HtmlService.createHtmlOutputFromFile('myPage');
}
function emailTech(form){
var nameBox = form.techEmail;
var message = "This is the text box value" + nameBox;
MailApp.sendEmail("email#somewhere.com", "This is the subject", message );
}
myPage.html
<html>
<head>
<title>Test Page</title>
</head>
<body>
<form>
<input type="text" value=" " name="techEmail" />
<input type="button" onClick="formSubmit()" value="Submit" />
</form>
</body>
<script type="text/javascript">
function formSubmit() {
google.script.run.emailTech(document.forms[0]);
}
</script>
</html>
I'm having trouble in displaying my title input only "onclick" event.
When we mouseouver the input box, it will display the title, but i just want this to happen when I click on the input box.
My idea is displaying a title saying "value copied", cause I have a function on "onclick" event that copy the input (read only) value to the clipboard, and when it's done I want to let the user know that this happen displaying that information.
Is that even possible?
(this is for a windows gadget)
Thank you to everyone.
Try .focus()
<!DOCTYPE html>
<html>
<head>
<style>span {display:none;}</style>
<script src="http://code.jquery.com/jquery-1.9.1.js"></script>
</head>
<body>
<p><input type="text" /> <span>focus fire</span></p>
<p><input type="password" /> <span>focus fire</span></p>
<script>
$("input").focus(function () {
$(this).next("span").css('display','inline').fadeOut(1000);
});
</script>
</body>
</html>
http://api.jquery.com/focus/