Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why hitting Enter in AngularJS form's text input causes a side effect?

Tags:

angularjs

Live Demo

Consider the following form:

<form>
  <div>
    <label>Status: </label>
    <button ng-repeat="status in statuses"
            class="btn btn-default"
            ng-model="job.status.id" btn-radio="status.id">
      {{ status.name }}
    </button>
  </div>
  <div>
    <label>Name: </label>
    <input type="text" ng-model="job.name">
  </div>
</form>

When focus is on the name field, and Enter is hit, Status is set to "All Good" for some reason. Live Demo

Why is this happening? How could I stop this side effect?

like image 964
Misha Moroshko Avatar asked Jan 06 '14 08:01

Misha Moroshko


1 Answers

From the ngForm docs:

This is because of the following form submission rules in the HTML specification:

If a form has only one input field then hitting enter in this field triggers form submit (ngSubmit)

if a form has 2+ input fields and no buttons or input[type=submit] then hitting enter doesn't trigger submit

if a form has one or more input fields and one or more buttons or input[type=submit] then hitting enter in any of the input fields will trigger the click handler on the first button or input[type=submit] (ngClick) and a submit handler on the enclosing form (ngSubmit)

Default type for the button element is "submit" (<button></button> === <button type="submit"></button>). Hence, when you hit enter, the first button is submitted.

To remedy, just put type="button" on your buttons.

<button 
  ng-repeat="status in statuses"
  class="btn btn-default"
  ng-model="job.status.id" 
  btn-radio="status.id"
  type="button"
>
  {{ status.name }}
</button>
like image 164
Stewie Avatar answered Oct 16 '22 06:10

Stewie