m0a
m0a

Reputation: 1005

Mimic 'Paste' function into Input Text

I have an <input type=text> that wants user to paste a URL into it. However, I want the site to provide a default URL in it, but changing the value isn't enough-- the site needs to mimic the paste event as if the user pasted the default URL in themselves.

So, is there a way to pseudo-paste a URL into an input text using jQuery? In the example code I have it so when user pastes an alert 'Hi' pops up, but what I want is when I hit play in the JSFiddle (or load the site in other words) there will be www.example.com pasted in (via the code) and 'Hi' will come up automatically in response.

https://jsfiddle.net/9c47r2qt/1/

$("#test").bind("paste", function() {
  alert('hi');
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="text" id="test" class="myInput" value="This is some default text" />

Edit: To be clear, I do not want data from the User's clipboard; in fact that would ruin things. I want the site to act as if the code is pasting data.

Upvotes: 1

Views: 212

Answers (2)

charlietfl
charlietfl

Reputation: 171669

Just trigger() the paste event to run the event handler.

$("#test").on("paste", function() {
  console.log('New value pasted:', this.value);
}).val('some new string').trigger('paste');
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="text" id="test" class="myInput" />

Upvotes: 1

Always Helping
Always Helping

Reputation: 14570

You can simply use .val() function to assign a default value or paste (Current URL) when the site loads. It will show an alert Pasted the default URL

In your paste function you can use .on instead of .bind (its deprecated now). When the user actually paste something the alert shows User Pasted Something

To get the default current URL you can use window.location.href function.

Run snippet below to see working.

$(document).ready(function() {

  //Load the default URL
  $('.myInput').val(window.location.href)
  //Alert on load
  alert('Pasted the default URL')

  //Paste function - User
  $("#test").on("paste", function() {
    alert('User Pasted Something');
  });
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="text" id="test" class="myInput" />

Upvotes: 1

Related Questions