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.
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" />
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" />
Related
I've implement localization in my application, all this stuff is saved inside a php file. So I can easy do this:
<input class="form-control" type="text" required="" placeholder="username" oninvalid="this.setCustomValidity('<?php echo $this->lang->line('field_required'); ?>')"></input>
Now if I doesn't enter any text I can see the custom message, but if I fill the input I see again the popup as the form can't get the text inside.
It's a bug of Bootstrap?
EXAMPLE
https://jsfiddle.net/DTcHh/23662/
Using the onvalid won't work in some browsers like Safari or IE below 10. Use a custom event notifier for attaching the function.
Note: As you mentioned in the comment you can print the message from the data-invalid-message attribute from php and catch it using jQuery by .data('invalidMessage').
SEE WORKING EXAMPLE:
var myobj = jQuery('input.form-control');
myobj.on('keyup keypress blur change input', function() {
var messg = ($(this).data('invalidMessage'));
if (this.validity.typeMismatch) {
this.setCustomValidity(messg);
} else {
this.setCustomValidity('');
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<link href="https://netdna.bootstrapcdn.com/bootstrap/3.0.0/css/bootstrap.min.css" rel="stylesheet" />
<script src="https://netdna.bootstrapcdn.com/bootstrap/3.0.0/js/bootstrap.min.js"></script>
<form>
<input class="form-control" type="email" required placeholder="username" data-invalid-message="custom message from php here">
<button type="submit">
go
</button>
</form>
a workaround that I've found is:
onkeyup="this.setCustomValidity('');
the bug will be gone now.
TL&DR
Check element.validity.typeMismatch and then element.setCustomValidity('custom error msg') or element.setCustomValidity('') if there's no mismatch. You should listen on both keyup and blur events.
Explanation in Mozilla Developer documentation about setCustomValidity: https://developer.mozilla.org/en-US/docs/Web/Guide/HTML/Forms/Data_form_validation#Customized_error_messages.
But just keyup won't work properly if focus is not inside the input box we're modyfing.
Our previous example won't transfer the current state of the input box
if the user mouses away and clicks elsewhere on the page. We update
the component's values property only when the user presses Enter while
the focus is inside the input box.
Let's fix that by listening to the input box's blur event as well.
Above is from Angular 2 docs: User Input, paragraph "On blur" https://angular.io/docs/ts/latest/guide/user-input.html.
Simplified example
Below is example from Mozilla documentation with added blur keyEvent listener. Yup, refactoring needed, but mine version in Angular 2 looks vastly different and so probably will yours.
<form>
<label for="mail">I would like you to provide me an e-mail</label>
<input type="email" id="mail" name="mail">
<button>Submit</button>
</form>
And then
var email = document.getElementById("mail");
email.addEventListener("keyup", function (event) {
if (email.validity.typeMismatch) {
email.setCustomValidity("I expect an e-mail, darling!");
} else {
email.setCustomValidity("");
}
});
email.addEventListener("blur", function (event) {
if (email.validity.typeMismatch) {
email.setCustomValidity("I expect an e-mail, darling!");
} else {
email.setCustomValidity("");
}
});
I have a 'parent' page that is using the following bit of code to pull in a form from a different page on the same domain. There are reasons why I can't just place the form directly on the 'parent'.
<script type="text/javascript">
jQuery("#ai_temp_profile_edit").load(
"https://example.com/form/ #profile-edit-form",
function() {}
).hide().fadeIn(1000);
</script>
The form that is pulled in looks like this:
<form action="https://example.com/form/" method="post" id="profile-edit-form" class="standard-form base" target="hiddenFrame">
<label for="field_1">Name</label>
<input id="field_1" name="field_1" type="text" value="Joey-Jojo Jr. Shabadoo">
<input type="submit" name="profile-group-edit-submit" id="profile-group-edit-submit" value="Save Changes " />
<input type="hidden" name="field_ids" id="field_ids" value="1" />
<input type="hidden" id="_wpnonce" name="_wpnonce" value="a62f8d5fec" />
<input type="hidden" name="_wp_http_referer" value="/form/" />
</form>
When 'submit' is clicked, https://example.com/form/ is opened in a hidden iframe and the user name gets properly saved. This all works well.
I would like the user name on the currently loaded 'parent' page to update via jquery, so that the user has some immediate visual feedback that the name change has taken place.
My approach has been to try and take the value out of the 'field_1' input when 'submit' has been clicked, and pass that variable onto a div in the parent page with an id of 'display_name'.
$(document).ready(function(){
function nameUpdate(){
$("#profile-group-edit-submit").click(function () {
var updateName = $("#field_1").val();
$("#display_name").text(updateName);
});
}
nameUpdate();
});
I've also tried adding window.parent.
before the the #display_name selector section and it didn't change anything.
I've used this approach on another button/div combo on the same page and it works, the difference is that that particular button is in an iframe, not loaded by jquery. So I'm guessing my problem is related to that fact.
I've googled around, but have run out of ideas of how to phrase my question, what to look for, etc...
Any help would be greatly appreciated. Thanks!
Edit: For clarity, the div w/ id #display_name won't update.
Use jquery to handle the form submission.
$(document).ready(function(){
$('#profile-edit-form').submit(function(){
var updateName = $("#field_1").val();
$("#display_name").text(updateName);
});
});
EDIT:
Due to your loading the form dynamically you need to bind the submit function after the load. So...
$(document).ready(function () {
var formLoaded = function () {
$('#profile-edit-form').submit(function () {
var updateName = $("#field_1").val();
$("#display_name").text(updateName);
});
};
$("#ai_temp_profile_edit").load(
"https://example.com/form/ #profile-edit-form",
formLoaded
).hide().fadeIn(1000);
});
If I am understanding it correctly, your problem is "display_name" field is not getting updated with the latest value.
If this is the problem then can you try below thing?
Instead of
$("#display_name").text(updateName);
try using-
$("#display_name").val(updateName);
As per the documentation on jQuery site Val() works well with form Elements whereas text won't.
More on Val() method- https://api.jquery.com/val/#val2
I'm having a strange behaviour with this code:
<script type="text/javascript">
function get()
{
alert("gggg");
jQuery.get (
"http://localhost:8080/c/portal/json_service",
{
serviceClassName: "com.liferay.test.service.TrabajadorServiceUtil",
serviceMethodName: "findByName",
servletContextName: "TrabajadorPlugin-portlet",
serviceParameters: "[param]",
param : document.getElementById("nombre")
}
);
}
</script>
<div>
<form>
<input type="text" id="nombre" value="<%=searching%>"/>
<input type="button" value="Submit" onClick="javascript:get()"/>
</form>
</div>
Liferay portal gets blocked when the button "Submit" is pressed. The pop-up with the message "gggg" is showed, but after click ok on it, the page becomes blocked.
If I remove the line 'param : document.getElementById("nombre")', it doesn't block.
Can anyone explain me where is the error, or the reason of this behaviour?
Thanks in advance,
Rafa
The problem is that you're trying to pass an entire DOM element as the value for param, which jQuery isn't going to like. What type of element has ID nombre, and what property from that element do you want? If it's some kind of input, you likely want the value property, so you'd do:
param : document.getElementById("nombre").value
Updated Answer:
Thinking this through a little more, you should probably do this in a different way altogether. You're sending the data when the user clicks on the submit button, but remember if a user hits enter while typing in the input text box the form will submit but your code will not catch that.
A more robust solution would be to do it this way instead:
<div>
<form id="nombre_search">
<input type="text" id="nombre" value="<%=searching%>"/>
<input type="submit" value="Submit"/>
</form>
</div>
<script type="text/javascript" charset="utf-8">
$(document).ready(function() {
$("#nombre_search").submit(function(){
$.get("http://localhost:8080/c/portal/json_service", {
serviceClassName: "com.liferay.test.service.TrabajadorServiceUtil",
serviceMethodName: "findByName",
servletContextName: "TrabajadorPlugin-portlet",
serviceParameters: "[param]",
param : $("#nombre").val()
});
return false;
});
});
</script>
Changes to your code:
Added an id to the form.
Made the submit button a submit button instead of just a button.
Placed code inside $(document).ready block.
Code runs when form is submitted not when button is clicked.
Hope this helps,
Sandro
I have a html form, with a custom file upload field. And by that I mean that I have moved the actual file field beyond the borders of the page with css, that I have a custom input field and button in place, and that I have a jquery click event attached to that custom button to trigger the file input dialog.
It all works fine, in every browser.
But I need to submit the form through javascript. And I got somewhere that IE remembers my actions with javascript as a malicious manipulation of the file input field and blocks my access with an error "access denied" when I invoke document.formName.submit().
Is there a way around this, because I have gone completely mad by trying to search for a solution. I seriously don't want to use the default file input field, as every browsers renders it differently and messes up my design..
code:
<form name="thisForm" onsubmit="return false;" enctype="multipart/form-data" method="post" action="index.cfm/somepage">
<input type="file" class="hidden" name="hidden" id="hidden" />
<input type="text" name="shown" id="shown" />
<button id="button">browse..</button>
<input type="submit" id="submitForm" />
</form>
<script>
$('button').click(function(){
$('#shown').val($('#hidden').val());
});
$('submitForm').click(function(){
validateForm();
});
function validateForm()
{
//regular expression validation against all other input fields in the form
//not the file input field
validateVAT();
}
function validateVAT()
{
//connect to external service to check VAT
submitForm();
}
function submitForm()
{
document.thisForm.submit();
}
</script>
UPDATE:
I just tried to first upload the file, before submitting the form, through ajax, but that also gave me the acces denied error.. >_>
I was having the same problem, and I solved it by using a styled <label> tag with a slight workaround in Firefox.
http://jsfiddle.net/djibouti33/uP7A9/
The Goals:
allow user to upload a file by using standard html file input control
hide standard html file input control and apply own styling
after user selects file to upload, automatically submit the form
The Browsers:
Firefox, Chrome, IE8/9, Safari
IE7 didn't work, but it might if you add it to the workaround detailed below.
The Initial Solution:
Hide the file input by positioning it offscreen. Important not to display:none as some browsers won't like this.
Add another styled element to the page (link, button).
Listen for a click on that element, then programmatically send a click to the file input to trigger the native 'file explorer'
Listen for the file input's onchange event (occurs after a user chooses their file)
Submit the form
The Problem:
IE: if you programmatically send a click to a file input in order to activate it (2), programmatically submitting the form (5) will throw a security error
The Workaround Solution:
Same as above
Take advantage of the accessibility features built in to the label tag (clicking on a label will activate it's associated control) by styling
a label tag instead of a link/button
Listen for the file input's onchange event
Submit the form
For some reason Mozilla browsers won't activate a file input by clicking on it's label.
For Mozilla, listen for the click on the label and send a click event to the file input to activate it.
Hope this helps! Check out the jsfiddle for details on the html/js/css used to make it all work.
I found the answer myself, After 2 days of crazy trial&error. I hope I can help somebody with this..
I removed the hidden file input field from my coldfusion page and replaced it by an iframe tag. That iframe tag linked to another coldfusion page, containing another form with the removed file input field.
Now when I use javascript to click the file input field, which is still hidden from view, it still gives the browse file dialog without a hitch. But when I use javascript to submit the form, through the iframe, miraculously, it submits the form in the iframe, making it possible to upload the file in some serverside scripting of your preference.
iframe code:
<form id="formFileUpload" class="formFileUpload" name="formFileUpload" method="post" action="../actions/act_upload_file.cfm" autocomplete="off" enctype="multipart/form-data">
<input type="file" class="buttonFileHidden" id="inputFile" name="partnersLogo" />
</form>
iframe itself:
<iframe src="admin/dsp_file_upload.cfm" id="ifu" name="ifu" class="buttonFileHidden">
</iframe>
javascript click & submit:
ifu.document.formFileUpload.partnersLogo.click();
ifu.document.formFileUpload.submit();
If you're like me, and you don't want to use an iframe, and you weren't too keen on the label solution mentioned above, you can just position the original button above the styled button with an opacity of 0.
Using the example above, you would still have:
<input type="file" class="hidden" name="hidden" id="hidden" />
<input type="button" name="shown" id="shown" value="Add File" />
But .hidden would be defined like so:
.hidden {
position: absolute;
left: -150px;
opacity: 0;
filter: alpha(opacity=0);
}
Config: Set the opacity to 0.5 (or =50) to see the transparent element and tweak the left positioning.
Arguably just as hacky as the answers above, but a bootstrap-friendly solution, and in my case, the only one that worked.
I found a weird solution to solve this problem.
It thought about the js click thread. If it goes out of this thread, there no more security issues.
I chose to use window.setTimeout. see sample below:
<script type="text/javascript">
$(function () {
$("#<%= this.fuDoc.ClientID %>").bind('change', uploadFile);
$("#<%= this.btnUpload.ClientID %>").click(chooseFile);
});
function chooseFile() {
$("#<%= this.fuDoc.ClientID %>").click();
}
function uploadFile() {
var fu = $("#<%= this.fuDoc.ClientID %>");
if (fu.val() != "") {
window.setTimeout(function () {
<%= this.ClientScript.GetPostBackEventReference(this.btnUpload, "") %>;
}, 100);
}
}
</script>
<asp:FileUpload ID="fuDoc" runat="server" style="display: none;" />
<asp:Button runat="server" ID="btnUpload" Text="upload" OnClick="btnUpload_Click" />
<asp:Label ID="lbltext" Text="" runat="server" />`
then, no more acces denied!
This is an old post but the problem still arises. This may not be working because jQuery kindly fails silently. I was having this problem and wondering why my hidden form would not submit and the file get uploaded. I started off by using jQuery, but then I went vanilla. It still didn't work but looked as though an exception was being thrown in my .click() function.
Running
try {
document.getElementById('formid').submit();
} catch (e) {
alert(e);
}
showed that we indeed were throwing an error, and quick research showed that this was because IE DOES NOT SUPPORT SIMULATED CLICKS ON A FILE INPUT. This means that when the form went to be posted, IE would refuse to post the form
Excuse the bold caps, but I know many people will see text and not read it
Have you tried
$('button').click(function(){
$('form[name=thisForm]').submit()
});
You need to change onsumbit='return false;' to onsubmit='return validateForm()'.
Then have validateForm() return true if the form passes your validation checks, or false if it does not.
The onsubmit='return false' is preventing the form from submitting via document.thisForm.submit(); as well as when the user clicks the submit button.
I commented these lines in j query.form.js then every thing works fine for me. Don't ask me the reason even i don't have the solution for that but it works for sure.
if (io.contentWindow.document.execCommand) {
try { // #214
io.contentWindow.document.execCommand('Stop');
} catch(ignore) {}
}
On my company's internal ticket tracking website, we have a form that we use to update or note changes in the ticket. When a client updates the ticket, I need to modify a text area, input, and click submit. I want to create a single button that will handle this repetitive task using a chrome extension.
In my extensions content.js script, I have the following which isn't getting the job done.
var blueButtonDom = document.createElement('a');
blueButtonDom.setAttribute('href','#');
blueButtonDom.setAttribute('onClick','clickHandler();return true');
function clickHandler() {
$('textarea[id$="PrivateNotes"]').val('blue');
$('input[id$="BillTime"]').val('1');
$('input[id$="btnSave2"]').click();
}
Any input from you all would be greatly appreciated.
Thanks much,
Joe Chin
jQuery:
$(document).ready(function() {
var $myLink = $('Automagical');
$myLink.click(function() {
$('#PrivateNotes').val('blue')
$('#BillTime').val('1');
$form.submit();
});
$('#myForm').prepend($myLink);
});
html:
<form id="myForm">
<textarea id="PrivateNotes"></textarea>
<input id="BillTime" type="text" />
<input id="btnSave2" type="submit" />
</form>
http://jsfiddle.net/pxfunc/T9bgw/
UPDATED to include $(document).ready()