-1

im new to html and javascript. I seem to be having problems on my button click. If the username / password are empty it is ment to set the border for there inputbox to red, then let me fill them in again. Problem is that when the input boxes are empty and when i click the button the input boxes get set red for half a second then the webpage ends up at index.html? not sure why i was watching the console in google chrome and it shows

login_button Clicked
index.js:34 username == null
index.js:41 password  == null
Navigated to file:////index.html?

Button Click

$('#login_button').click(function () {
    console.log("login_button Clicked");
    var username = $('#login_username').val();
    var password = $('#login_password').val();

    if (username == "") {
        console.log("username == null");
        $('#login_username').css({
            "border": '#FF0000 1px solid'
        });
    }

    if (password == "") {
        console.log("password  == null");
        $('#login_password').css({
            "border": '#FF0000 1px solid'
        });
    }

    if (username && password) {
        console.log("Login");
    }
});

i get this in chrome Exception : DOMException: Failed to execute 'querySelectorAll' on 'Element': '*,:x' is not a valid selector.

ravugode
  • 1
  • 1

4 Answers4

0
$('#login_button').click(function (e) {
    e.preventDefault();

    console.log("login_button Clicked");
    var username = $('#login_username').val();
    var password = $('#login_password').val();

    if (username == "") {
        console.log("username == null");
        $('#login_username').css({
            "border": '#FF0000 1px solid'
        });
    }

    if (password == "") {
        console.log("password  == null");
        $('#login_password').css({
            "border": '#FF0000 1px solid'
        });
    }

    if (username && password) {
        console.log("Login");
    }
});

You should just need to catch the event and prevent the default action

topched
  • 765
  • 3
  • 11
0

in your button you probably do not change the type, so by default it is submitting the form for you. Either you prevent the submit by using preventDefault function or you change default behaviour of the button using the type attribute

type="button"

n00b
  • 1,832
  • 14
  • 25
0

You aren't event.preventDefault so when you click the link (I'm guessing the SRC="#" or SRC="/") it is going to the link location.

First 2 lines should be:

$('#login_button').click(function (e) { e.preventDefault();

EliMaine
  • 1
  • 2
0

Either add return false or add event.preventDefault(); to prevent form to submit when data is empty or wrong.

See the difference between both: event.preventDefault() vs. return false

if (username == "") {
        console.log("username == null");
        $('#login_username').css({
            "border": '#FF0000 1px solid'
        });
      return false;
 }
Community
  • 1
  • 1
Rohit
  • 1,794
  • 1
  • 8
  • 16