Sharan
Sharan

Reputation: 33

Using an API to build a QR Code Generator

I've been working on a QR Code Generator that uses this API. For some reason, I'm not able to figure out what's wrong with it. Click here to see it in a JSFiddle.

HTML:

<form>
    <input type="text" id="textInput" placeholder="Enter text here">
    <button type="submit" id="submitButton">Submit</button>
</form>
<!-- This image should display the QR Code. -->
<img id="resultImage" src="" alt="">

JavaScript:

var input = document.getElementById('textInput');
var button = document.getElementById('submitButton');
var image = document.getElementById('resultImage');
button.onclick = function() {
    var resultValue = "http://api.qrserver.com/v1/create-qr-code/?data=" + input.value;
    image.setAttribute("src", resultValue);
}

Upvotes: 0

Views: 1022

Answers (1)

obe
obe

Reputation: 7788

You need to add return false; at the end of the onclick handler, otherwise clicking the button causes the page to refresh before the QR code has time to render (because the button is of type submit)

i.e.

button.onclick = function() {
    var resultValue = "http://api.qrserver.com/v1/create-qr-code/?data=" + input.value;
    image.setAttribute("src", resultValue);
    return false;
 }

Upvotes: 1

Related Questions