skip to Main Content

I’d like to know how to initiate the certain javascript functions to make a label red or have a pop up saying an empty field etc with the twitter bootstrap.

I have a form like so:

  <form role="myForm" id="sign-up-form" method="post" action="/sign-up">
    <div class="form-group">
      <label for="exampleInputEmail1">Email</label>
      <input type="email" class="form-control" id="exampleInputEmail1" name="email">
    </div>
    <div class="form-group">
      <label for="exampleInputPassword1">Password</label>
      <input type="password" class="form-control" id="exampleInputPassword1">
    </div>
    <input type="submit" value="Next: Connect Shopify" class="btn btn-success">
  </form>

I have a route like so:

app.post("/sign-up", function (req, res) {

    console.log(req.body);
    res.render('sign-up');
});

I’d like to know how to handle the form validation. Like if a space is empty, with Bootstrap javascript, I can make it red or have a pop up. How can I do this?

2

Answers


  1. You could use the onChange event on the form to call a validation function. Then change the css use the .style() method.

    Login or Signup to reply.
  2. So,here’s what I am getting from your question. You want JS function to

    • validate input
    • change ui of label
    • or add a pop-up to alert that user has left that field blank

    This all can be done simply by JavaScript or JQuery.

    If we follow template (HTML) you provided in your question then, below script will do what you want. I have also added necessary comments to help you out.

    <input id="submit" type="submit" value="Next: Connect Shopify" class="btn btn-success" onClick="submit()">
    

    This is a very basic function to give you an idea how you can change style using javascript and see some field’s value.

    function submit() {
      if (document.getElementById('exampleInputEmail1') === '' || typeof document.getElementById('exampleInputEmail1') === 'undefined') {
        document.getElementById('exampleInputEmail1').style.color = 'red';
        return;
      } else if (document.getElementById('exampleInputPassword1') === '' || typeof document.getElementById('exampleInputPassword1') === 'undefined') {
        document.getElementById('exampleInputEmail1').style.color = 'red';
        return;
      }
      return;
    }
    

    However, I would suggest you should use Jquery to do these kind of things. And also you can use required attribute in input fields to make sure user must add something in the field.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search