javascript change html in event listener - javascript

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;
}

Related

Javascript function not firing with html onclick

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);

Why isn't my JS function working when I call it through "onchange" in an html form?

Okay, I should preface this by saying I'm pretty new to JS and HTML.
I am attempting to write a simple page that will take the value a user types into the form and use it to make a call to the Spotify api via my findArtist() function. I've set the project up with npm and have the proper dependencies in the node-modules directory and all of that stuff.
Here is my code:
<!DOCTYPE html>
<html lang="en-US">
<head>
<meta charset="UTF-8">
<title>My Title</title>
</head>
<body>
<header>
<h1>My Header</h1>
</header>
<section>
<form>
Search for an artist! <br/>
<input type="text" name="searchrequest" value="" onchange="findArtist()">
</form>
</section>
<script>
function findArtist () {
var artistName = document.getElementsByName("searchrequest")[0].value;
spotifyApi.searchArtists(artistName)
.then(function(data) {
console.log(data.body);
}, function(err) {
console.error(err);
});
}
</script>
</body>
</html>
When I type something in the search bar, I expect to see the call occur in my browsers console, where the JSON should be logged thanks to findArtist(), but nothing happens. Is this because I am attempting to use node when I should be using plain JS? Do I have to setup a server to make the call? I'm rather confused as to what my actual problem is.
I would like to add that I realize using onchange to call my function is going to put me over my api limit, so a suggestion on a better way to call the function would be appreciated as well.
Thanks for the help.
onchange detects changes only after you lose focus or blur from the textbox.
As this answer says oninput might just be the right method to look upto.

reCaptcha not working on firefox

I've problems with reCaptcha, it's implemented as following ...
<head>
<script>
var widget_register;
var onloadCallback = function () {
widget_register = grecaptcha.render('form_recaptcha', {
'sitekey': 'my-own-sitekey'
});
};
</script>
</head>
<script>
function setCaptcha(captcha) {
app.captcha_response = captcha;
}
</script>
<form id="recaptcha" class="design_recaptcha" action="javascript:setCaptcha(grecaptcha.getResponse(widget_register));">
<div id="form_recaptcha"></div>
<input type="submit" hidden/>
</form>
<script src="https://www.google.com/recaptcha/api.js onload=onloadCallback&render=explicit" async defer>
</script>
<paper-button id="register">Register</paper-button>
When the button with the "register" id is clicked, in my javascript the following code is executed.
$('#recaptcha').submit();
Then the function setCaptcha is executed, which gets the reCaptcha response-code as following. You find this code above in the form action tag.
action="javascript:setCaptcha(grecaptcha.getResponse(widget_register));"
The captcha response is then saved to a variable in my app.js.
This setup works in chrome, opera and egde browser. Only browser which it doesn't work is firefox.
Somebody has the same problem? or a solution for me? thx :)
Use an onsubmit attribute rather than in the action tag which is really meant for the post url:
onsubmit="setCaptcha(grecaptcha.getResponse(widget_register)); return false"
If you want the form to actually submit, which I don't think you do in this case, return true instead of false.

Need to implement html button to access REST get resource

Fairly new to REST and web application and would like to create a front-end site with a button and a place where a result is displayed.
I have REST API structured like this:
http://hostserver.com/MEApp/MEService
This returns a value when browsing to it.
Now I would like to implement a GUI so that when you browse to c:\resourcebutton.html
There will be a button and when I click on it, it will call the REST API resource and returns the result. If I understood REST correctly it should work like this.
I have a html code:
<!DOCTYPE html>
<html>
<body>
<p>Click the button to trigger a function.</p>
<button onclick="myFunction()">Click me</button>
<p id="demo"></p>
<script>
function myFunction() {
document.getElementById("demo").innerHTML = "Hello World";
}
</script>
</body>
</html>
How and where should I insert the GET method to call the API? Is it common to use Javascript?
Yes, you have to do this with JavaScript. In fact, you need Ajax.
To simplify things, you should download and include JQuery to your site, and then use something like this:
$.post( "http://hostserver.com/MEApp/MEService", function( data ) {
document.getElementById("demo").innerHTML = data;
//Or, in the JQuery-way:
$('#demo').html(data);
});
The jQuery Source can be found here: http://code.jquery.com/jquery-2.1.1.js
Your html-file would then look like this:
<!DOCTYPE html>
<html>
<head>
<script src="the/Path/To/The/Downloaded/JQuery.js"></script>
<script>
//Usually, you put script-tags into the head
function myFunction() {
//This performs a POST-Request.
//Use "$.get();" in order to perform a GET-Request (you have to take a look in the rest-API-documentation, if you're unsure what you need)
//The Browser downloads the webpage from the given url, and returns the data.
$.post( "http://hostserver.com/MEApp/MEService", function( data ) {
//As soon as the browser finished downloading, this function is called.
$('#demo').html(data);
});
}
</script>
</head>
<body>
<p>Click the button to trigger a function.</p>
<button onclick="myFunction()">Click me</button>
<p id="demo"></p>
</body>
</html>

jQuery and HTML forms

I have an iframe with a HTML form dynamically added. I need the parent page to have a button which submits this form (to a page set in the iframe), but then also is able to receive the return value.
The part I am struggling with is how to receive the return value. Submitting the form is fine, but getting the parent page to receive the return value - like with an AJAX request - is eluding me.
Here is an example of the kind of thing I am trying to achieve:
<html>
<head>
etc...
<script type="text/javascript">
$(doument).ready(function() {
$("#myFormButton").click(function () {
// This is what doesn't exist, a callback with the data
// this is what I would like to acheive somehow...
$("#myForm").submit(function(data) {
// do stuff with the data
});
});
});
</script>
</head>
<body>
<iframe>
etc...
<form action="mypage.ashx">
various inputs...
</form>
etc...
</iframe>
</body>
</html>
Thank you all very much for your help,
Richard Hughes

Categories