Console not displaying data

Viewed 514

I am simply trying to display data in my console. For some reason it just flashes the result and refreshes the console. I am running the html file on server.

Code-

<html>
<body>
<form>
    <label>Name:</label>
    <input type="text" id="fname" >
    <label>Email:</label>
    <input type="text" id="email" >
    <input type="submit" value="Submit" id="fetch">
</form>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<script>
$('#fetch').click(function(){
        var str = $("#fname").val();
        console.log(str);
        });
 
</script>
</body>
</html>

I am unable to debug this. Any suggestions?

2 Answers

You need to return false to prevent reloading:

$('#fetch').click(function(){
        var str = $("#fname").val();
        console.log(str);
        return false;
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form>
    <label>Name:</label>
    <input type="text" id="fname" >
    <label>Email:</label>
    <input type="text" id="email" >
    <input type="submit" value="Submit" id="fetch">
</form>

Another way to prevent the default behavior:

$('#fetch').click(function(e){
        e.preventDefault();
        var str = $("#fname").val();
        console.log(str);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form>
    <label>Name:</label>
    <input type="text" id="fname" >
    <label>Email:</label>
    <input type="text" id="email" >
    <input type="submit" value="Submit" id="fetch">
</form>

Clicking the submit button will submit the form, and thus refresh the page, which is the reason why the console is clearing.

Since you're using jQuery, you can add return false; right after your console.log(str);, so the original action (here, the form submission) will be cancelled.

Related