Will this javascript work on mobile? - javascript

I have a script that uses a text input as a radius to find google map locations within that radius. I did not use form. I used JavaScript to pick the value of the input and append it to the url. I use php $_GET to pick the radius and then use it in the search. The strange thing I noticed was that, I found items within the radius on pc but found nothing on mobile. I have no idea what's wrong. But I was suspecting the javascript / jquery not working on mobile and will like to know if it is possible.
And solutions to make it work.
The html + javascript below and then the php.
<p class="caption_j">Radius in <b> MILES </b></p>
<input class="search_n" value="" name="search_dist" type="text" style="width: 85%;"/>
<span class="ow_right search_dist_lens ow_ic_lens ow_cursor_pointer" style="display: block;background-position: center center; background-repeat: no-repeat; width: 26px; height: 26px;"></span>
<script>
var urlsearch = "http://www.website.ml/items/search/type/";
</script>
<script>
$(document).ready(function(){
var text;
////////////////////////////////////////////////
$(':text.search_n').keypress(function(evt){
if(evt.which===13)
{
if($(':text.search_n').val().length > 0)
{
text = $(':text.search_n').val();
location.assign(urlsearch+'nearme?dist='+text);
}
}
});
$('.search_dist_lens').click(function(){
if($(':text.search_n').val().length > 0)
{
text = $(':text.search_n').val();
location.assign(urlsearch+'nearme?dist='+text);
}
});
///////////////////////////////////////////////
});
</script>

Related

positioning doesn't work with Javascript

I am building an "autofill" function. When the user types something in an input field and the system finds this string in the database it should display the string into the input field in grey, similar to what google used to/still have/has.
Therefore I built two input fields, one that's clearly visible:
html:
<input id="email_input" type="text">
<input id="autofill" type="text">
css:
#email_input{
background-color: transparent;
z-index: 100;
}
Then I position the autofill input via JS exactly where email_input is.
function positionAutocompleteInput(){
var top = $('#email_input').position().top;
var left = $('#email_input').position().left;
$('#autofill').css({'top':top});
$('#autofill').css({'left':left});
}
positionAutoFillInput();
The actual autfill I do like this:
function autofill(context){
var input = $('#email_input').val();
var replacement = context[0].email;
replacement = replacement.slice(input.length);
var display = input + replacement;
$('#autofill').val(display)
}
I tried calling positionAutoFillInput(); onInput, so that it gets repositioned with each input. If I look at the positions of both input fields in the console, they both have the same positions.
Both input fields have the same font-size and font-family.
For some reason it still looks off:
Anyone know an answer?
Can you just position them with CSS like this? This way it requires no JavaScript to position it.
#autofill, #email_input {
font-size: 20px;
}
#autofill {
position: absolute;
color: #CCCCCC;
}
#email_input {
position: relative;
z-index: 1;
background: transparent;
}
<h1>Test</h1>
<div>
<input id="autofill" type="text" value="1234567890">
<input id="email_input" type="text">
</div>

HTML Elements inside Contenteditable?

I have a contenteditable tag, and I want my users to be able to type code into it. However, when I type into the contenteditable tag, my code shows up as text rather than an actual element. Is there a way for a user to create a full, working HTML element in a contenteditable box? I know it is possible for the client to insert code using javascript, but what about users who do not have access to javascript? How could users get code such as buttons inside a contenteditable box?
<p contenteditable="true">Try typing code in here as user, code will only be text...</p>
Is there a javascript way to accomplish this without JQUERY?
EDIT
I spent a long time searching for answers on Google, but nothing came up. The best solution I've gotten at this point has been #Dekel's comment on CKEditor. If there is another solution, I want to hear it. If there isn't, I'm sticking to CKEditor. I don't have much time, so I need a solution fast.
MORE EDIT =D
I recently developed my own answer to my question by looking at #Brandon's .replace answer (which only worked for client-coding, not user-coding) and modifying it to work with user-coding.
This isn't pretty, but you could make it work if you are looking to add HTML only. Otherwise an inline editor might work best.
var el = document.querySelector('p')
el.addEventListener('blur', function() {
var map = {amp: '&', lt: '<', gt: '>', quot: '"', '#039': "'"}
var html = this.innerHTML.replace(/&([^;]+);/g, (m, c) => map[c]);
this.innerHTML = html;
});
<p contenteditable="true">Try typing <b>code</b> in here as user, code will only be text...</p>
This answer is similar to #Brandon's idea, but is much more simple.
https://jsfiddle.net/azopqLe4/
<iframe width="100%" height="300" src="//jsfiddle.net/azopqLe4/embedded/js,html,result/dark/" allowfullscreen="allowfullscreen" frameborder="0"></iframe>
function convertit() {
var convet = document.getElementById("convet");
var text = convet.innerHTML;
var newtext;
newtext = text.replace(/</g, "<").replace(/>/g, ">");
convet.innerHTML = newtext;
}
//this version runs onrightclick =D
<p contenteditable="true" oncontextmenu="convertit();" id="convet">
Type some code here, then right-click... =D
</p>
In the second snippet, I typed <b>Test</b>, right-clicked it, and it became Test! My answer works through simple array replacement methods, although it is frustrating and time-wasting to keep right-clicking all the time. To prevent the actual contextmenu from popping up, just add .preventDefault().
You can't insert code, but you can insert DOMElements with JS. No need for jQuery.
var element=document.createElement("button");
element.innerHTML="Hello";
document.getElementById("yourContentEditable").append(element);
The idea with this would be to have a button to prompt for the code and insert it. Something like this:
(It is very ugly and buggy but it's just an example I just wrote)
var editorSelection=null;
function openCodePopup() {
//Store cursor position before editor loses focus
editorSelection=getEditorSelection();
//Open the popup
document.querySelector("#codePopup").style.display="block";
var ta=document.querySelector("#userCode");
ta.value="";
ta.focus();
}
function closeCodePopup() {
document.querySelector("#codePopup").style.display="none";
}
function insertCode() {
var code=document.querySelector("#userCode").value;
closeCodePopup();
if(code=="") return;
insertIntoEditor(html2dom(code));
}
function getEditorSelection() {
//TODO make crossbrowser
//TODO (VERY IMPORTANT) validate if selection is whitin the editor
var sel=window.getSelection();
if(sel.rangeCount) return sel.getRangeAt(0);
return null;
}
function insertIntoEditor(dom) {
if(editorSelection) {
editorSelection.deleteContents();
editorSelection.insertNode(dom);
} else {
//Insert at the end
document.querySelector("#editor").append(dom);
}
}
function html2dom(code) {
//A lazy way to convert html to DOMElements, you can use jQuery or any other
var foo=document.createElement('div'); //or you could use an inline element
foo.contentEditable=false;
foo.innerHTML=code;
return foo;
}
#editor {
height: 180px;
overflow: auto;
border: 1px solid #ccc;
}
#toolbar {
position: relative;
}
#codePopup {
position: absolute;
left: 10px;
top: 15px;
background-color: #fff;
border: 1px solid #ccc;
padding: 5px;
display: none;
}
#userCode {
display: block;
width: 200px;
height: 100px;
}
<div id="toolbar">
<button onclick="openCodePopup()"></></button>
<div id="codePopup">
<textarea id="userCode" placeholder="Type code here"></textarea>
<button onclick="insertCode()">Ok</button>
<button onclick="closeCodePopup()">Cancel</button>
</div>
</div>
<div contenteditable="true" id="editor"></div>
With the same idea you could create other options to convert element (example, text->link, etc.).

how to create resizeable div as search engine

I'am developing search engine to my App, and as part of it the user can search multiple phrase here is some example -
When the input line is full like that:
It's height should be adjusted and the text cursor should get to the next line.
The problem is, that it's look like that in the third line my alogrithm is no longer work and it's look like that:
The structure of my the search input is like that
Html:
<div id=s"earchDiv">
<input id="searchInput">
</input>
</div>
JS:
var sDiv = document.getElementById('searchDiv');
var sInput = document.getElementById('searchInput');
var currH = $(sDiv).height();
$(sDiv).css('height', sDiv.scrollHeight + 'px');
var h = 40 - ($(sDiv).height() % 40);
if ($(sDiv).height() % 40 != 0)
$(sDiv).css('height', ($(sDiv).height() + h) + 'px');
which mean that acuttaly the div height is shoud be adjusted.
Someone have some idea or algorithm that can work at that situation?
First of all you have an error in your html:
<div id=s"earchDiv">
<input id="searchInput">
</input>
</div>
should be like this:
<div id="searchDiv">
<input id="searchInput">
</input>
</div>
after that ... i dont see why you use JS to style when you can directly use CSS to style the searchDiv like below:
.searchDiv {
display: block;
width: 100%;
height: auto; // this is important
min-height: 40px; // change this as you wish
}
You can do this via CSS.
#searchDiv{
overflow:hidden; /* the parents of searchdiv should not have fixed height. */
}

Not wrapping the 'value' in the input box?

I have this simple code:
<input type="text" value="Some Extremely Really Long Word" />
How do I make sure the value (in this case 'Some Extremely Really Long Word') shows up completely (ie. is not clipped).
I tried to apply the style: overflow:visible and display:nowrap but it didn't work.
I don't want to apply a style like: width: 200px because I don't know how long the words will be.
Fiddle: http://jsfiddle.net/TfKbp/3/
I've used this in the past to dynamically expand the width of a text INPUT to the width of its contents. Basically, you create a SPAN with the exact same font family, font size, etc. and use the keypress event to add the characters, measure its size, and resize the INPUT.
EDIT 1
To dynamically size the text box for its initial value requires just a little more code...
HTML
<input id="txtLong" type="text" value="What does the fox say? Ring-ding-ding-ding-dingeringeding! Gering-ding-ding-ding-dingeringeding! Gering-ding-ding-ding-dingeringeding! What the fox say?" />
<span id="spanLong" style="display: none;"></span>
JavaScript
var txtLong = $("#txtLong");
var spanLong = $("#spanLong");
spanLong.text(txtLong.val());
txtLong.css("width", spanLong.width());
txtLong.keypress(function(e){
if (e.which !== 0 && e.charCode !== 0) {
var char = String.fromCharCode(e.keyCode | e.charCode);
spanLong.text(txtLong.val() + char);
txtLong.css("width", spanLong.width());
}
});
CSS
input, span {
padding: 2px 3px;
font-size: 11px;
font-family: Sans-serif;
white-space: pre;
}
New and Improved Fiddle
EDIT 2
Since you're looking for a way to select text by clicking on it, I thought I'd also point out that you don't necessarily need an INPUT to do that. Check out this JSFiddle. And as an added bonus, it doesn't use JQuery. I know you were kinda opposed to that.
EDIT 3
I found a way to simply resize a textbox to the width of its initial value using only plain JavaScript by adapting this blog post.
HTML
<input type="text" id="txtLong" value="Some very long text that all needs to show"/>
<span id="ruler"></span>
JavaScript
String.prototype.visualLength = function()
{
var ruler = document.getElementById("ruler");
ruler.innerHTML = this;
return ruler.offsetWidth;
}
window.onload = function() {
var txtLong = document.getElementById("txtLong");
var width = txtLong.value.visualLength();
txtLong.setAttribute("style", "width:" + width + "px");
}
CSS
#ruler {
visibility: hidden;
white-space: nowrap;
}
#txtLong, #ruler {
font-family: sans-serif;
font-size: 11pt;
}
JSFiddle
There is no declarative way (that I know of) to do this, but it is fairly easy to do using jQuery. What you essentially need to do is make a second element (not an input) that contains all the same styling as the input. Then measure the width of the second element, and set width of the input to that new width.
Here's how you'd do that:
HTML:
<input type='text' value='Some Extremely Really Long Word' id='my-input' />
jQuery:
$(document).ready(function() {\
var $input = $('#my-input'),
$clone = $('<div></div>');
$clone.html($input.val());
$clone.css({
whiteSpace: 'nowrap',
font: $input.css('font'),
paddingLeft: $input.css('padding-left'),
paddingRight: $input.css('padding-right')
});
$clone.appendTo($('body'));
$input.css({
width: $clone.width();
});
$clone.remove();
})

open file select dialog with javascript [duplicate]

I'd like to make a click event fire on an <input type="file"> tag programmatically.
Just calling click() doesn't seem to do anything or at least it doesn't pop up a file selection dialog.
I've been experimenting with capturing events using listeners and redirecting the event, but I haven't been able to get that to actually perform the event like someone clicked on it.
I have been searching for solution to this whole day. And these are the conclusions that I have made:
For the security reasons Opera and Firefox don't allow to trigger file input.
The only convenient alternative is to create a "hidden" file input (using opacity, not "hidden" or "display: none"!) and afterwards create the button "below" it. In this way the button is seen but on user click it actually activates the file input.
Upload File
You cannot do that in all browsers, supposedly IE does allow it, but Mozilla and Opera do not.
When you compose a message in GMail, the 'attach files' feature is implemented one way for IE and any browser that supports this, and then implemented another way for Firefox and those browsers that do not.
I don't know why you cannot do it, but one thing that is a security risk, and which you are not allowed to do in any browser, is programmatically set the file name on the HTML File element.
You can fire click() on any browser but some browsers need the element to be visible and focused. Here's a jQuery example:
$('#input_element').show();
$('#input_element').focus();
$('#input_element').click();
$('#input_element').hide();
It works with the hide before the click() but I don't know if it works without calling the show method. Never tried this on Opera, I tested on IE/FF/Safari/Chrome and it works. I hope this will help.
THIS IS POSSIBLE:
Under FF4+, Opera ?, Chrome:
but:
inputElement.click() should be called from user action context! (not script execution context)
<input type="file" /> should be visible (inputElement.style.display !== 'none') (you can hide it with visibility or something other, but not "display" property)
just use a label tag, that way you can hide the input, and make it work through its related label
https://developer.mozilla.org/fr/docs/Web/HTML/Element/Label
For those who understand that you have to overlay an invisible form over the link, but are too lazy to write, I wrote it for you. Well, for me, but might as well share. Comments are welcome.
HTML (Somewhere):
<a id="fileLink" href="javascript:fileBrowse();" onmouseover="fileMove();">File Browse</a>
HTML (Somewhere you don't care about):
<div id="uploadForm" style="filter:alpha(opacity=0); opacity: 0.0; width: 300px; cursor: pointer;">
<form method="POST" enctype="multipart/form-data">
<input type="file" name="file" />
</form>
</div>
JavaScript:
function pageY(el) {
var ot = 0;
while (el && el.offsetParent != el) {
ot += el.offsetTop ? el.offsetTop : 0;
el = el.offsetParent;
}
return ot;
}
function pageX(el) {
var ol = 0;
while (el && el.offsetParent != el) {
ol += el.offsetLeft ? el.offsetLeft : 0;
el = el.offsetParent;
}
return ol;
}
function fileMove() {
if (navigator.appName == "Microsoft Internet Explorer") {
return; // Don't need to do this in IE.
}
var link = document.getElementById("fileLink");
var form = document.getElementById("uploadForm");
var x = pageX(link);
var y = pageY(link);
form.style.position = 'absolute';
form.style.left = x + 'px';
form.style.top = y + 'px';
}
function fileBrowse() {
// This works in IE only. Doesn't do jack in FF. :(
var browseField = document.getElementById("uploadForm").file;
browseField.click();
}
Try this solution: http://code.google.com/p/upload-at-click/
If you want the click method to work on Chrome, Firefox, etc, apply the following style to your input file. It will be perfectly hidden, it's like you do a display: none;
#fileInput {
visibility: hidden;
position: absolute;
top: 0;
left: -5000px;
}
It's that simple, I tested it works!
$(document).one('mousemove', function() { $(element).trigger('click') } );
Worked for me when I ran into similar problem, it's a regular eRube Goldberg.
WORKING SOLUTION
Let me add to this old post, a working solution I used to use that works in probably 80% or more of all browsers both new and old.
The solution is complex yet simple. The first step is to make use of CSS and guise the input file type with "under-elements" that show through as it has an opacity of 0. The next step is to use JavaScript to update its label as needed.
HTML The ID's are simply inserted if you wanted a quick way to access a specific element, the classes however, are a must as they relate to the CSS that sets this whole process up
<div class="file-input wrapper">
<input id="inpFile0" type="file" class="file-input control" />
<div class="file-input content">
<label id="inpFileOutput0" for="inpFileButton" class="file-input output">Click Here</label>
<input id="inpFileButton0" type="button" class="file-input button" value="Select File" />
</div>
</div>
CSS Keep in mind, coloring and font-styles and such are totally your preference, if you use this basic CSS, you can always use after-end mark up to style as you please, this is shown in the jsFiddle listed at the end.
.file-test-area {
border: 1px solid;
margin: .5em;
padding: 1em;
}
.file-input {
cursor: pointer !important;
}
.file-input * {
cursor: pointer !important;
display: inline-block;
}
.file-input.wrapper {
display: inline-block;
font-size: 14px;
height: auto;
overflow: hidden;
position: relative;
width: auto;
}
.file-input.control {
-moz-opacity:0 ;
filter:alpha(opacity: 0);
opacity: 0;
height: 100%;
position: absolute;
text-align: right;
width: 100%;
z-index: 2;
}
.file-input.content {
position: relative;
top: 0px;
left: 0px;
z-index: 1;
}
.file-input.output {
background-color: #FFC;
font-size: .8em;
padding: .2em .2em .2em .4em;
text-align: center;
width: 10em;
}
.file-input.button {
border: none;
font-weight: bold;
margin-left: .25em;
padding: 0 .25em;
}
JavaScript Pure and true, however, some OLDER (retired) browsers may still have trouble with it (like Netscrape 2!)
var inp = document.getElementsByTagName('input');
for (var i=0;i<inp.length;i++) {
if (inp[i].type != 'file') continue;
inp[i].relatedElement = inp[i].parentNode.getElementsByTagName('label')[0];
inp[i].onchange /*= inp[i].onmouseout*/ = function () {
this.relatedElement.innerHTML = this.value;
};
};
Working jsFiddle Example
It works :
For security reasons on Firefox and Opera, you can't fire the click on file input, but you can simulate with MouseEvents :
<script>
click=function(element){
if(element!=null){
try {element.click();}
catch(e) {
var evt = document.createEvent("MouseEvents");
evt.initMouseEvent("click",true,true,window,0,0,0,0,0,false,false,false,false,0,null);
element.dispatchEvent(evt);
}
}
};
</script>
<input type="button" value="upload" onclick="click(document.getElementById('inputFile'));"><input type="file" id="inputFile" style="display:none">
I know this is old, and all these solutions are hacks around browser security precautions with real value.
That said, as of today, fileInput.click() works in current Chrome (36.0.1985.125 m) and current Firefox ESR (24.7.0), but not in current IE (11.0.9600.17207). Overlaying a file field with opacity 0 on top of a button works, but I wanted a link element as the visible trigger, and hover underlining doesn't quite work in any browser. It flashes on then disappears, probably the browser thinking through whether hover styling actually applies or not.
But I did find a solution that works in all those browsers. I won't claim to have tested every version of every browser, or that I know it'll continue to work forever, but it appears to meet my needs now.
It's simple: Position the file input field offscreen (position: absolute; top: -5000px), put a label element around it, and trigger the click on the label, instead of the file field itself.
Note that the link does need to be scripted to call the click method of the label, it doesn't do that automatically, like when you click on text inside a label element. Apparently the link element captures the click, and it doesn't make it through to the label.
Note also that this doesn't provide a way to show the currently selected file, since the field is offscreen. I wanted to submit immediately when a file was selected, so that's not a problem for me, but you'll need a somewhat different approach if your situation is different.
JS Fiddle: http://jsfiddle.net/eyedean/1bw357kw/
popFileSelector = function() {
var el = document.getElementById("fileElem");
if (el) {
el.click();
}
};
window.popRightAway = function() {
document.getElementById('log').innerHTML += 'I am right away!<br />';
popFileSelector();
};
window.popWithDelay = function() {
document.getElementById('log').innerHTML += 'I am gonna delay!<br />';
window.setTimeout(function() {
document.getElementById('log').innerHTML += 'I was delayed!<br />';
popFileSelector();
}, 1000);
};
<body>
<form>
<input type="file" id="fileElem" multiple accept="image/*" style="display:none" onchange="handleFiles(this.files)" />
</form>
<a onclick="popRightAway()" href="#">Pop Now</a>
<br />
<a onclick="popWithDelay()" href="#">Pop With 1 Second Delay</a>
<div id="log">Log: <br /></div>
</body>
Here is pure JavaScript solution to this problem. Works well across all browsers
<script>
function upload_image_init(){
var elem = document.getElementById('file');
if(elem && document.createEvent) {
var evt = document.createEvent("MouseEvents");
evt.initEvent("click", true, false);
elem.dispatchEvent(evt);
}
}
</script>
This code works for me. Is this what you are trying to do?
<input type="file" style="position:absolute;left:-999px;" id="fileinput" />
<button id="addfiles" >Add files</button>
<script language="javascript" type="text/javascript">
$("#addfiles").click(function(){
$("#fileinput").click();
});
</script>
My solution for Safari with jQuery and jQuery-ui:
$("<input type='file' class='ui-helper-hidden-accessible' />").appendTo("body").focus().trigger('click');
There are ways to redirect events to the control but don't expect to be able to easily fire events to the fire control yourself as the browsers will try to block that for (good) security reasons.
If you only need the file dialog to show up when a user clicks something, let's say because you want better looking file upload buttons, then you might want to take a look at what Shaun Inman came up with.
I've been able to achieve keyboard triggering with creative shifting of focus in and out of the control between keydown, keypress & keyup events. YMMV.
My sincere advice is to leave this the alone, because this is a world of browser-incompatibility-pain. Minor browser updates may also block tricks without warning and you may have to keep reinventing hacks to keep it working.
I was researching this a while ago because I wanted to create a custom button that would open the file dialog and start the upload immediately. I just noticed something that might make this possible - firefox seems to open the dialog when you click anywhere on the upload. So the following might do it:
Create a file upload and a separate element containing an image that you want to use as the button
Arrange them to overlap and make the file element backgroud and border transparent so the button is the only thing visible
Add the javascript to make IE open the dialog when the button/file input is clicked
Use an onchange event to submit the form when a file is selected
This is only theoretical since I already used another method to solve the problem but it just might work.
I had a <input type="button"> tag hidden from view. What I did was attaching the "onClick" event to any visible component of any type such as a label. This was done using either Google Chrome's Developer Tools or Mozilla Firefox's Firebug using the right-click "edit HTML" command. In this event specify the following script or something similar:
If you have JQuery:
$('#id_of_component').click();
if not:
document.getElementById('id_of_component').click();
Thanks.
Hey this solution works.
for download we should be using MSBLOB
$scope.getSingleInvoicePDF = function(invoiceNumberEntity) {
var fileName = invoiceNumberEntity + ".pdf";
var pdfDownload = document.createElement("a");
document.body.appendChild(pdfDownload);
AngularWebService.getFileWithSuffix("ezbillpdfget",invoiceNumberEntity,"pdf" ).then(function(returnedJSON) {
var fileBlob = new Blob([returnedJSON.data], {type: 'application/pdf'});
if (navigator.appVersion.toString().indexOf('.NET') > 0) { // for IE browser
window.navigator.msSaveBlob(fileBlob, fileName);
} else { // for other browsers
var fileURL = window.URL.createObjectURL(fileBlob);
pdfDownload.href = fileURL;
pdfDownload.download = fileName;
pdfDownload.click();
}
});
};
For AngularJS or even for normal javascript.
This will now be possible in Firefox 4, with the caveat that it counts as a pop-up window and will therefore be blocked whenever a pop-up window would have been.
Here is solution that work for me:
CSS:
#uploadtruefield {
left: 225px;
opacity: 0;
position: absolute;
right: 0;
top: 266px;
opacity:0;
-moz-opacity:0;
filter:alpha(opacity:0);
width: 270px;
z-index: 2;
}
.uploadmask {
background:url(../img/browse.gif) no-repeat 100% 50%;
}
#uploadmaskfield{
width:132px;
}
HTML with "small" JQuery help:
<div class="uploadmask">
<input id="uploadmaskfield" type="text" name="uploadmaskfield">
</div>
<input id="uploadtruefield" type="file" onchange="$('#uploadmaskfield').val(this.value)" >
Just be sure that maskfied is covered compeltly by true upload field.
You can do this as per answer from Open File Dialog box on <a> tag
<input type="file" id="upload" name="upload" style="visibility: hidden; width: 1px; height: 1px" multiple />
Upload
I found that if input(file) is outside form, then firing click event invokes file dialog.
Hopefully this helps someone - I spent 2 hours banging my head against it:
In IE8 or IE9, if you trigger opening a file input with javascript in any way at all (believe me I've tried them all), it won't let you submit the form using javascript, it will just silently fail.
Submitting the form via a regular submit button may work but calling form.submit(); will silently fail.
I had to resort to overlaying my select file button with a transparent file input which works.
This worked for me:
<script>
function sel_file() {
$("input[name=userfile]").trigger('click');
}
</script>
<input type="file" name="userfile" id="userfile" />
Click
it's not impossible:
var evObj = document.createEvent('MouseEvents');
evObj.initMouseEvent('click', true, true, window);
setTimeout(function(){ document.getElementById('input_field_id').dispatchEvent(evObj); },100);
But somehow it works only if this is in a function which was called via a click-event.
So you might have following setup:
html:
<div onclick="openFileChooser()" class="some_fancy_stuff">Click here to open image chooser</div>
<input type="file" id="input_img">
JavaScript:
function openFileChooser() {
var evObj = document.createEvent('MouseEvents');
evObj.initMouseEvent('click', true, true, window);
setTimeout(function()
{
document.getElementById('input_img').dispatchEvent(evObj);
},100);
}
You can use
<button id="file">select file</button>
<input type="file" name="file" id="file_input" style="display:none;">
<script>
$('#file').click(function() {
$('#file_input').focus().trigger('click');
});
</script>
To do so you can click an invisible, pass-through element over the file input :
function simulateFileClick() {
const div = document.createElement("div")
div.style.visibility = "hidden"
div.style.position = "absolute"
div.style.width = "100%"
div.style.height = "100%"
div.style.pointerEvents = "none"
const fileInput = document.getElementById("fileInput") // or whatever selector you like
fileInput.style.position = "relative"
fileInput.appendChild(div)
const mouseEvent = new MouseEvent("click")
div.dispatchEvent(mouseEvent)
}

Categories