0

I am new to JavaScript recently moved from python.
I am coding fine with my coffee , but this code throws an error, saying that : 'function' is declared but its value is never read. What's wrong with my code. I had also inscribed this script in my index.html and in this tag.
=> <button type="submit" id="login" onclick="sendCred()">

import net from 'net';

var socket = new net.Socket();

function sendCred(){

    // sending the credentials to the python server on ("localhost", 8000)

    var net = require('net');
    var host = 'localhost'
    var port = 8000

    var username = this.username.value;
    var password = this.password.value;
    var socket = new net.Socket();

    socket.connect(port, host, ()=> {
        socket.write(username + "." + password);
    });

    socket.on('data', (data) => {
        console.log(`${data}`);
        socket.destroy();
    });

    // authenticating the process;
    if (user === "Gautam"){
        if (passw === "Admin"){
            document.write("Auth SuccessFul")
        }else{
            var textField = document.querySelector("#error");
            var error = "you've entered a wrong password, click "
            redrctHtml = error + "\n<a href=\"#\">here</a>" + " to change password";
            textField.innerHTML = redrctHtml;
        }
    }
};```

Nick Parsons
  • 45,728
  • 6
  • 46
  • 64
  • You're inside of a [module](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Modules#other_differences_between_modules_and_standard_scripts) so `sendCred` isn't available outside of the module (unless you're exporting it) and so can't be used in your HTML with `onclick`. You should be adding your click event handler using `.addEventListener()` from within your module – Nick Parsons May 21 '22 at 13:13
  • Can you please send the code... I didn't understand what are you saying – gautam_wingsinger May 21 '22 at 13:19
  • There are multiple ways to add a click handler on an element. You've added it with `onclick=`. I'm saying that you can't use that because `sendCred` is not accessible from within your HTML. You need to add your click handler another way. The other (more common) way is to use `.addEventListener("click", sendCred)` on your `button` element. You can get it using `.querySelector()` similar to how you've retrieved `textField`, but you want to grab `#login` instead. Here are the docs for [addEventListener()](https://developer.mozilla.org/en-US/docs/Web/API/EventTarget/addEventListener) – Nick Parsons May 21 '22 at 13:23

0 Answers0