Home > Mobile >  Jquery .val() on input returns [object Undefined]
Jquery .val() on input returns [object Undefined]

Time:03-01

I want to append an with href to Google's favicon fetcher with the value from an input when the button is clicked.

The result I want to achieve is:

<img href="https://s2.googleusercontent.com/s2/favicons?domain=https://google.com/">

The actual result:

<img href="https://s2.googleusercontent.com/s2/favicons?domain=[object Undefined]">

https://jsfiddle.net/u5tp79a4

<!DOCTYPE html>

<html>

<head>
    <title>Upload Image</title>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
    <script src="upload.js"></script>
    <style>
        #e-favicon {
            height: 100px;
            width: 100px;
        }
    </style>
</head>
<body>
    <input type="text" id="input">
    <button id="button">Get favicon</button>
    <div id="e-favicon"></div>
</body>

</html>
const element = "#e-favicon";
const button = "#button";
const input = "#input";

$(document).ready(function() {
    console.log("js loaded");

    $(button).on('click', function () {
        const favicon = "https://s2.googleusercontent.com/s2/favicons?domain="   toString($(input).val());
        console.log("button click");
        console.log(favicon);

        $(element).append('<img href="'   favicon   '">');
    });
});

CodePudding user response:

Converting to string is what is causing an unexpected result. You don't need to convert .val() to string since it returns a string value:

$(button).on('click', function () {
    const favicon = "https://s2.googleusercontent.com/s2/favicons?domain="   $(input).val();
    //...
});
  • Related