jQuery.trigger('click') does not work in my code - javascript

I want the file explorer to pop up for user selecting files when user click a button which is a <input id="J_upload_btn" type="button" />.
However the source above only works well on Firefox 4. On Chrome 11/12 and Firefox 3, the selecting-file-box pops up only after you click the button several times.
My jQuery version is 1.5.2.
$('#J_upload_btn').click(function() {
var _id = new Date().getTime(),
_$form = $('#J_pic_form'),
_$input = $('<input id="' + _id + '"' +
' type="file" name="file" class="hide_input">');
_$form.append(_$input);
_$input.trigger('click');
}
});

Unmatched closing curly brace. Just removing it should work.
You cannot reliably access DOM elements before the DOM tree is created. If this code is not wrapped in a function and called after that is the case, simply wrapping it in $(function(){ /* code */ }); is enough for jQuery to call it as soon as the DOM is ready.
In some browsers (including Firefox 3), triggering click events on <input type="file"> elements is restricted for security reasons.
This code works for me in Chrome:
$(function() {
$('#J_upload_btn').click(function() {
var _id = new Date().getTime(),
_$form = $('#J_pic_form'),
_$input = $('<input id="' + _id + '"' +
' type="file" name="file" class="hide_input">');
_$form.append(_$input);
_$input.trigger('click');
});
});

This kind of input is more restricted than others, by security issues. Sure there's a more current method, but the most common method to do this is using an invisible input (with opacity 0, not display:none), and placing a fake button over it, so when you click on the fake button, you're also clicking on the invisible input.

You may want to try not wrapping the input as a jayesh object. If you pass the HTML string to append, then the browser should add a new input field too.
var input = "<input id='"+id+"' />";
_$form.append(input);
Also, have you tried debugging the click in a console to make sure that it is getting fired or the subsequent code has the issue?

If you are tiggering click on the input, a function is expected to run. But as far as I can see, you have not written any function for the click event of _$input.

Related

Full Calendar event resource with on click event

On the latest version of Full Calendar, I have a link wrapped around my event resources. When you double click on the event resource name I would like a modal to pop up.
The problem I'm having is as soon as the calendar loads it loads each of the modals for each of the resources as if I've just double-clicked on them.
Has anybody else come across this and does anybody have any idea on how to fix it?
resourceRender: function(renderInfo) {
if(renderInfo.resource.extendedProps.unassign==false)
renderInfo.el.querySelector('.fc-cell-text').innerHTML = "<a ondblclick=" + showProfileModal('staff', renderInfo.resource.id) + " class='text-staff'>" + renderInfo.resource.title + "</a>";
else
renderInfo.el.querySelector('.fc-cell-text').innerHTML = "<span class='text-red'>" + renderInfo.resource.title + "</span>";
},
The problem is the way you've created the hyperlink:
.innerHTML = "<a ondblclick=" + showProfileModal('staff', renderInfo.resource.id) + " class='text-staff'>"
In that context, showProfileModal() is not part of your HTML string, instead it's treated as actual code to be executed...and so that's what happens, it gets executed.
You're using it as if the result of that function was something to be included in the HTML string. If you want that to be treated as text, something to be added to the HTML declaration, then include it inside the string:
.innerHTML = '<a ondblclick="showProfileModal(\'staff\',\'' + renderInfo.resource.id + '\')\" class=\"text-staff\">'
Demo: https://codepen.io/ADyson82/pen/WNeKYav?&editable=true&editors=001
(Of course if you wanted to make that code less messy without all the character escaping and so on, you could use createElement and addEventListener to create the hyperlink and set the double-click event handler instead.)

how to place a button on crm 2011 form.

I want to place a button on CRM 2011 form.
function create_button(fldName, btnLabel, btnWidth, evt)
{
try{
fldName = "inmate_button_submit";
btnLable="Click Me";
// btnWidth="200px";
var btn = '<button class="ms-crm-Button" onclick="evt()" style="width:50px" id="' + fldName + '" onmouseover="Mscrm.ButtonUtils.hoverOn(this);" onmouseout="Mscrm.ButtonUtils.hoverOff(this);" >Click Me</button>';
var ctrl = null;
try {
ctrl = Xrm.Page.ui.controls.get(fldName).get_chromeElement()[0];
} catch (e) {
ctrl = Xrm.Page.ui.controls.get(fldName)._control.get_element();
}
// Add the new button
ctrl.innerHTML += btn;
// Hide the textbox
ctrl.children[0].style.display = 'none';
ctrl.children[1].style.display = 'none';
// Hide the label
Xrm.Page.ui.controls.get(fldName).setLabel(btnLable);
// Add Event to the newly created button
ctrl.children[0].attachEvent('onclick', evt);
}
catch(e){alert(e.description);}
}
function evt()
{
alert("You have clicked me!!");
}
The above is my following code which places the button on the form. When i click on the button, after showing the alert crm gives me the following error.
ERROR
An error has occurred.
Try this action again. If the problem continues, check the Microsoft Dynamics CRM Community or you for solutions or contact....
I have no idea why this is happening. Any help guys?
Keep in mind that using getElementById is going to be unsupported and may not work (does not work in Outlook 2007) in some browsers.
I would recommend placing this is in a web resource, or utilizing the ribbon for this functionality. Would either of those meet your requirements?
If you use your js as a webresource then you shouldnt have any problems.
Or you can even trigger the function OnLoad
Please see following :
http://www.mscrmconsultant.com/2012/07/insert-custom-button-on-crm-form-using.html
i will recommend add custom webresource ( HTML page which contanis javascript functionality on in onload event ) if you need access to form, use window.parent.document.Xrm.Page ....
2 things might cause this issue:
evt function is not accessible to your button
Resolution: try registering the evt function in global scope i.e.
evt = function() { alert("…"); }
or
window.evt = function() {}
2. Your button is using the same field name as the placeholder field.
This might cause internal issues.
Resolution: Try giving your button another (bogus) id instead i.e. fieldname + "_button"
Have you tried the 3rd party applications...
http://crmvisualribbonedit.codeplex.com/
Call the function from a web resource.
NOTE: Remember to add $ to reference the web resource location
Example $webresource:ButtonScript.js

Prevent closure in jQuery/JavaScript

I'm trying to do something that seems (to me, at least) to be a fairly easy, common thing to do.
Here's the HTML for what I've got on a web page:
<div class="allergiesDiv">
<div>
<span class="editButton">Allergies</span><br />
</div>
<span>Allergies</span>
</div>
</div>
I turn the first <span> into a jQuery button with $('.editButton').button().
(I have many of these pairs on the page.)
What I am trying to do is the following:
When the button is clicked, it loads a jQuery Dialog with the value of the span that follows it loaded into a <textarea>. (BONUS: When the dialog is loaded, I'd like the <textarea> to be focused and all text inside highlighted.)
The user is able to edit the value and then click 'OK'.
When the user clicks 'OK', the Dialog is dismissed and the new value that was entered is used to replace the old value for the span.
Here's the code I'm trying to use (this works OK in IE, but breaks in Mobile Safari and Chrome for PC):
NOTE: I've been chopping the code up some to try to get each problem isolated. I have had this working, at least in IE.
// How I get the button and bind to the click event
$('.editButton')
.button({icons: {primary:'ui-icon-pencil'} })
.click(EditClicked);
// 'Edit' button click handler
function EditClicked() {
var span = $(this).parent().next().children().first();
var text = span[0].innerText;
var dialog = $('<div>').prop('title', 'Edit: ' + $(this).text());
var textArea = $('<textarea>').css('width', '98%').prop('rows', '4').html(text);
textArea.appendTo(dialog);
var windowWidth = $(window).width();
var buttonTop = $(this).button().offset().top;
$(dialog).dialog({
modal: true,
minWidth: windowWidth / 2,
position: ['center',buttonTop],
buttons: {
'Ok' : function () {
OKClicked(span);
},
'Cancel' : function () {
$(this).dialog('close').remove();
}
}
});
textArea.focus().select();
}
// Dialog 'OK' button click handler
function OKClicked(span) {
var text = $(this).find('textarea')[0].innerText;
span.html(text);
$(this).dialog('close').remove();
}
This is currently broken when it gets to var buttonTop..., with the error message of "button is undefined". I haven't yet figured out why that is (I used to have a variable in that method named 'button', but it's gone now. Not sure if that's a caching issue.)
Other than that, can anyone see what's wrong with my process? It seems like I've got some kind of misunderstanding with closure, but I'm not yet good enough with JavaScript to understand how to get the kink out of this code.
what about
var buttonTop = $(this).offset().top;
I am not sure, that $('<div>') is properly syntax for jQuery. Try to use $('div') instead.
When you use $(this).button() - you try to call button method of $(this) object. Seems like a bug.

JavaScript to output form fields to a textarea ends with textarea being outputted but then immediately clearing itself?

Here's a brief rundown of my issue:
I have a JavaScript function that gets the value of a bunch of form fields, then combines them into another variable called outputArea, and then I use the same function to change the value of a textarea called "outputArea" to the value I created for outputArea in the JScript (document.thisForm.outputArea.value = outputArea).
but when I press the "Make My Notes" button that calls the function, it grabs the variables, hits my alert to dump the variables to make sure its working, then outputs to the form field I want it to... however, IMMEDIATELY after the function completes, it clears itself. By itself, I mean the whole form clears, including the outputArea.
I've checked my source numerous times and there are 0 references to a reset button or anything that should be clearing these values after the function is called, so I'm at a loss.
Below is my function:
<script type="text/javascript">
function getNotes() {
var spokeTo = document.thisForm.spokeWith.value;
var problemWith = document.thisForm.problemWith.value;
var resolvedBy = document.thisForm.resolvedWith.value;
var thisTech = document.thisForm.techName.value;
var liveChat = document.thisForm.onLiveChat.value;
var passTo = document.thisForm.passTo.value;
var fSpace = ". ";
var fSign = " - ";
alert(spokeTo + problemWith + resolvedBy + thisTech);
outputValue = 'Spoke with: ' +spokeTo + fSpace + problemWith + resolvedBy + passTo + fSign + thisTech;
document.thisForm.outputArea.value = outputValue;
alert('DISMISS');
}
the button that calls the function is simply:
<input type="submit" class="button" value="Make My Notes!" onClick="javascript:getNotes();" tabindex="4" style="margin-right:1em;" />
and the output field:
<textarea name="outputArea" id="outputArea" onClick="this.select();" readonly="yes"></textarea>
I added the alert('DISMISS'); in an attempt to see if I could (temporarily) stop the form from clearing itself by forcing the user to press OK to the alert, but strangely enough, it calls that Alert BEFORE it calls the document.thisForm.outputArea.value = outputValue, which I don't understand. After it calls it and outputs, it immediately clears EVERY form field. This is currently the only javascript function on the whole page, and there are no reset buttons anywhere in sight.
I've done this tons before and actually have an application with a similar method running and working fine right now, so I'm completely baffled. What in the heck am I doing wrong here?
I greatly appreciate anyone taking time looking into this for me. Cheers!
This actually looks to me like your page is refreshing itself because the button is performing a submit action. Change your onClick event to this:
onClick="getNotes(); return false;"
Because this is generating a POST request (probably to itself), the page is loading as if for the first time.

input type="file" javascript click simulation

I'm wondering why this example works this in Chrome 10, but doesn't work in Fx 3.6?
IFAIK, exactly input type="file" click doesn't work there...
Could anyone explain, why?
Hey Alex Ivasyuv,
Read your problem and took a look at the page you have pointed.
You have directed click event of the button to the click event of right? As I think that's not quite possible everywhere. The file input type handles the popups and uploads itself..
And seems you cannot trigger the popup file upload window of just by calling click() event. At least it's not possible in the browsers like Firefox, opera, chrome etc. But it's possible in IE right? (IE always behave strangely anyway..!)
I found some articles that may help to figure this out. check them. You'll solve the problem...!
01. https://stackoverflow.com/questions/210643/in-javascript-can-i-make-a-click-event-fire-programmatically-for-a-file-input-e
02. https://stackoverflow.com/questions/2048026/open-file-dialog-box-in-javascript
Regards,
ADynaMic
I was Googling this recently and decided to come up with my own solution.
For those of you looking for a solution please see my repo - Fancy Upload jQuery Plugin
This is a small plugin for jQuery but you are welcome to snip it up or use it as your code base - whatever! It just styles up your standard upload button and gives you a lot more room for customisation.
The code for this plugin can be seen below. It can be called on any file upload element using $('INPUT[type=file]').fancyUpload();
$.fn.fancyUpload = function(data) {
// generate unique ID for upload box and determine default text to use
var uploadBox = $(this);
var uniqID = Math.floor( Math.random() * 999999 );
var defText = (data == "" || data == undefined || data.defaultText == "" || data.defaultText == undefined) ? 'Click here to add an Attachment' : data.defaultText;
// hide the original upload box and replace with fancyUpload
uploadBox.hide();
uploadBox.before('<input class="fancyUpload" type="text" value="' + defText + '" id="uploadID'+uniqID+'" />').wrap('<div />');
var newUploadBox = $('INPUT[type=text]#uploadID'+uniqID);
// handle clicks on new upload box
newUploadBox.click(function (e) {
var _this = $(this);
// blur the text box because we dont want to focus on it and emulate click on file upload
_this.blur().siblings('div:first').children('INPUT[type=file]').click().bind('change', function (e) {
// determine resulting file name by getting last element in full file path
var filename = $(this).val().split("\\");
filename = filename[filename.length-1];
// set file name on emulated text box
_this.attr({ 'value' : (filename == "" || filename == undefined) ? defText : 'Attachment: ' + filename }).addClass('fileOn');
// handle form field resets (reset to defText)
_this.parents('FORM:first').find('INPUT[type=reset]').click(function () {
_this.attr({ 'value' : defText }).removeClass('fileOn');
});
});
});
};
<label><input type="file" name="fuckedfile" id="fuckedfile" style="display:none">
CLICK!</label><br/>
On Android (for security reasons) the click handler that originally received the user's click must be the same logic that sends a click to a file input element. Thus the file input element can be hidden (for example, if you want to trigger an upload from a menu selection).
For example, following code (contained in JsFiddle:):
jQuery(function($) {
$('#capture').on('click', function(e) {
$('#file')[0].click();
});
});

Categories