Search code examples
javascriptjqueryhtmltextareasweetalert2

sweetalert2 textarea newline confirm the modal


When I try to break line in textarea input type, modal confirmed.

I had added these too, but nothing happen: allowEnterKey: false, focusConfirm: false,

any one had advise for my problem?

Check the code here:

https://jsfiddle.net/piman/f28tn8hq/24/

$('.table button').on('click', function () {
	var replycontent = jQuery("#replyid-7 #reply-content").text();
	swal({
        title: 'my Title',
				type: 'question',
				input: 'textarea',
        inputValue: replycontent,
				showCancelButton: true,
				confirmButtonColor: '#3085d6',
				cancelButtonColor: '#d33',
				confirmButtonText: 'Save',
				cancelButtonText: 'Cancel',
				allowEnterKey: false,
				focusConfirm: false,
				inputValidator: function (value) {
    				return new Promise(function (resolve, reject) {
        				if (value) {
            				resolve()
        				} else {
            				reject('Error!')
        				}
    				})
				}
      }
    ).catch(swal.noop)
});
<link href="https://limonte.github.io/sweetalert2/assets/example.css" rel="stylesheet"/>
<script src="https://limonte.github.io/sweetalert2/dist/sweetalert2.all.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
  <div class="table-responsive">
    <table class="table">
        <tbody>
        <tr id="replyid-7">
                <td>

<p id="reply-content">Any Text here <br>
New line Test</p>
                    <hr>
                    <div class="author-info">by Admin</div>
                
                    <button>EDIT Content</button>
                </td>
           </tr>
        </tbody>
    </table>
</div>


Solution

  • Use the following control. But there is a bug, after pressing enter, cursor goes to end of the textarea.

    $('body').on('keydown','textarea', function(e) {
        if(e.which === 13){
            e.preventDefault();
          var value = e.target.value;
                var start = e.target.selectionStart;
                var end = e.target.selectionEnd;
    
          if(start === end){
            value = value.substring(0, start) + "\n" + value.substring(start, value.length);
          }else{
            value = value.substring(0, start) + "\n" + value.substring(end, value.length);
          }
          //TODO - set curser position to (start + 1)
          e.target.value = value;
        }
    
        return e.which !== 13;
    });
    

    Here is jsfiddle link : https://jsfiddle.net/rosfc6r2/