Jessicascn
Jessicascn

Reputation: 161

How to close my modal with the key enter + onclick

I have a modal that takes an input and display it on the screen, it works fine when I press the button "Save". But I'd like it to work when I press the key enter. I've found a few answers but it doesn't really suit my code as I want both the onClick and press enter. I've also tried to change the button for a "submit" type but it doesn't work well. Is there a quick and simple way to do that with my current code ?

    function addMovie() {
    
      var i = document.getElementById('addedMovie');
      var d = document.createElement('div');
      d.id = "new-movie";
      d.innerHTML = "<p>" + "<img src='../images/movie.png'>" + i.value + "</p>";
      var p = document.getElementById('related-movies');
    
      p.appendChild(d);
    
    }
      <div class="modal-content">
          <div class="modal-header">
            <button type="button" class="close" data-dismiss="modal">&times;</button>
            <h4 class="modal-title">Add a movie</h4>
          </div>
          <div class="modal-body">
            <input type="text" placeholder="Movie title" name="movies[]" class="modal-input" id="addedMovie">
          </div>
          <div class="modal-footer">
            <button type="button" class="btn btn-login" data-dismiss="modal" onClick="addMovie();clearModal()">Save</button>
          </div>
        </div>

Or is there a simpler a way to do that (by submiting the input in the modal and display it on the div of my choice for example ? because at the moment I am just taking the value inside the input but I don't think I am saving it into a variable)

Thanks a lot for your help !

Upvotes: 2

Views: 5978

Answers (2)

CodeHacker
CodeHacker

Reputation: 2138

Add an onkeypress event listener to the textbox and check for enter key pressed Here is the plunker

 <input onkeyup="save(event)" type="text" placeholder="Movie title" name="movies[]" class="modal-input" id="addedMovie">

Javascript

function save(e){
 var key = 'which' in e ? e.which : e.keyCode;
 if (key == 13) {
   addMovie()
 }
}

Upvotes: 0

Surabhi K
Surabhi K

Reputation: 144

Add a check for enter key press -

 <div id="modal" class="modal-content"> ...
   <input type="text" placeholder="Movie title" name="movies[]" class="modal-input" id="addedMovie" onkeypress="check(event)">
 </div>

function check(e) {
  if(e.key === "Enter") {
    addMovie();
    $('#modal').modal('hide');
  }
} 

Upvotes: 0

Related Questions