2

How can we change the following code to work when the button is clicked. As of right now it's configured to a submit button, which the button is not.

Button:

<button class="btn btn-primary"  ng-click="login()">Log in</button>

JavaScript:

 dpd.users.me(function(user) {
  if (user) {
    location.href = "/";
  }
  });
 $('form').submit(function() {
  var username = $('#username').val();
  var password = $('#password').val();
  dpd.users.login({username: username, password: password},  function(session, error) {
    if (error) {
      alert(error.message);
    } else {
      location.href = "/welcome.html";
    }
  });
  return false;
 });

Controller:

  $scope.showLogin = function(val) {
$scope.loginVisible = val;
if (val) {
  $scope.username = '';
  $scope.password = '';
  }
 };

 $scope.login = function() {
dpd.users.login({
  username: $scope.username,
  password: $scope.password
  }, function(session, error) {
  if (error) {
    alert(error.message);
    } else {
    $scope.showLogin(false);
    getMe();

    $scope.$apply();
  }
    });
  };

2 Answers 2

3

In order to run the code that currently exists within the 'form.submit' function, you'll need to change the jQuery selector and event it is tied to, or wrap the login info in a form, and change your button to a submit button:

<input type="submit" value="Log In" />

If you don't want to wrap the login data in a form, change the jQuery as follows:

$('form').submit(function() { // this should change to the following
$('button.btn-primary').on('click', function() {

you may also consider giving your button an ID:

<button id="login_button" class="btn btn-primary>Log in</button>

And then you can use the ID as your jQuery selector:

$('#login_button').on('click', function() {

for more info about the 'on' event handler: https://api.jquery.com/on/

Sign up to request clarification or add additional context in comments.

Comments

1
<form ng-submit="login()"><!-- /* input items */ --></form>

Use ng-submit for submit buttons. Avoid using jQuery, and define a $scope.login function in your controller

3 Comments

Thanks for the response! What would I add to my button to make it work? Here is what I have... <input type="submit" id="submit" class="btn btn-primary" value="Submit" /> and I added my controller to the post above. Thanks so much again
input type="submit" on the button is what you need to make it work - so you're good!
this has other advantages like working well with html5's required attributes for non-optional input fields (it checks for those inputs to be filled out before executing $scope.login() )

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.