Simulate Textbox Click to get focus - javascript

I am trying the following code to fire click event on a textbox while clicking on a button as the focus() function is not working in IE8
function simulateClick(elm) {
var evt = document.createEvent("MouseEvents");
evt.initMouseEvent("click", true, true, window,
0, 0, 0, 0, 0, false, false, false, false, 0, null);
var canceled = !elm.dispatchEvent(evt);
if(canceled) {
// A handler called preventDefault
// uh-oh, did some XSS hack your site?
} else {
// None of the handlers called preventDefault
// do stuff
}
}
This code works fine if the element is of type checkbox but not textbox, is there anything I might need to add?

This is the code for focus
function ResponseEnd(sender, args) {
if (args.get_eventArgument().indexOf("Filter") != -1) {
var grid = document.getElementById("<%= radGridEnquiries.ClientID %>");
var label = $(grid).children("table").children("tbody").children(".rgRow").children("td:has(span)").children("span")[0];
if (label != null) {
label.focus();
}
else {
var noRecTemp = $(grid).children("table").children("tbody").children("tr.rgNoRecords").children("td:has(div)").children("div");
noRecTemp.focus();
}
}
if (postInProgress)
postInProgress = false;
}
The real scenario is I have some textboxes set as filters in a Telerik RadGrid and having no filter icons but when the user posts a filter and the request is finished in IE8 the filter textbox is still with focus preventing the user to input new filters unless clicks on the textbox manually again
P.S. Sorry if this post is seen as answer but couldn't update this question with proper indented code. Thanks

Related

How to add attribute to class with js?

So I am trying to autofill the discount code section on a page. The class I am calling is button before. If I try to press enter it isn't applying the code, because the value wasn't saved somehow. However, filling it out manually addes this attribute to the class: after entering code manually. The site I am trying to apply discount on is luisaviaroma.com you can try the FF25 code, if you are interested in helping me with some code. I figured out that simply adding a space after the code my hand is solving the issue, is there a way to make this space press automated to (inside of js)?
function test() {
var element = document.querySelector("div[data-attribute='promo-code-input']")
var input = document.querySelector("input[name='promo-code-input']");
//element.setAttribute('class', 'InputText__baseCls___Hg_ik4cV2- InputText__focus___5q7tEpbHwI InputText__filled___1s5BW_63Y3');
element.classList.add("InputText__filled___1s5BW_63Y3");
console.log(element)
input.focus();
setTimeout(function () {
input.focus();
input.value='FF25';
let event = document.createEvent("HTMLEvents");
event.initEvent('change', true, false);
element.dispatchEvent(event);
element.blur();
}, 300)
input.select();
Although there is a KeyboardEvent the spec recommends input for text inputs.
In this case setting the bubbles attribute to true does the trick.
function test(val) {
var input = document.querySelector("input[name='promo-code-input']");
var inputEvent = new Event('input', {
bubbles: true,
})
input.focus();
input.value = val;
input.dispatchEvent(inputEvent)
console.log(input)
}

Having trouble with Javascript autocomplete library when getting data with getJSON

I'm running into issues with the following code:
var setupSearch = {
searchSuggest: function(field) {
$.getJSON('/get-all-journals', {'url':'on'}, function(data) {
var SHCount = Number($.cookie('SHCount'));
var SHArray = new Array();
for (i=1; i <= SHCount; i++) {
SHArray.push($.cookie('SH'+i));
}
$(field).ddautocomplete(removeDuplicate(SHArray), data.response.docs, {
matchContains: true,
max: 5,
cacheLength: 5000,
selectFirst: false,
scroll: false,
formatResult: function(str) { return str; },
formatItem2: function(item) {
return item.journal_display_name;
},
formatMatch2: function(item) {
return item.journal_display_name;
},
formatResult2: function(item) {
return item.journal_display_name;
}
});
});
},
searchForm: function(form) {
var field = form.find('textarea');
// Setup query field for default text behavior
// setupField(field);
setupSearch.searchSuggest(field);
field.autogrow();
field.keydown(function(e) {
if (e.keyCode == 13) {
form.submit();
return false;
}
});
// Make all forms submitting through Advanced Search Form
form.submit(function(e) {
e.preventDefault();
setupSearch.submitSearch(form, field);
});
},
submitSearch: function(form, field) {
if (advancedSearch.checkMinFields() || (!field.hasClass('defaultText') && field.val() != '')) {
// Sync the refine lists
// syncCheckboxLists($('#refineList input'), $('#advancedRefineList input'));
form.find('button').addClass('active');
$('#advancedSearchForm').submit();
} else {
$('#queryField').focus();
}
},
When I try to use the autocomplete drop-down by hitting enter, it seems to hit a "race condition" where the form will submit what I've typed rather than what autocomplete places into the textfield. Is there some way I can control the order of events so that the form.submit() will use what autocomplete fills into the text field?
The actual autocomplete dropdown menu is most likely represented as a styled list (or some other element) that is floated to be positioned below the textbox. On submit, have your function wait (a second or two max) for the autocomplete menu to be either destroyed or hidden. This will ensure that the plugin has time to fill in the textbox before the data is submitted.
EDIT
Try something like this:
$("#myDropdown").bind("autocompleteclose", function(){
// Continue with submitting your form
});
Use that where you would submit your form, and put the submitting code inside the callback. That way, it will wait for the autocomplete to close before submitting the form. You will want to add some kind of timeout to this to prevent it from submitting after a long delay (not sure when something like this might happen, though).

Javascript click function

I've got some code which works fine in IE but unfortunately not in Google Chrome/Firefox.
It relies upon calling a click() event on a button from javascript. Reading around it seems that this is an IE specific extension (doh). Is there any way I can do a similar thing in chrome + firefox? To clarify, it's executing the click event on a specific button, not handling what happens when the user clicks on a button.
Thanks
The code for those who asked for it:
function getLinkButton(actionsDiv)
{
var hrefs = actionsDiv.getElementsByTagName("a");
for (var i=0; i<hrefs.length; i++)
{
var id = hrefs[i].id;
if (id !=null && id.endsWith("ShowSimilarLinkButton"))
{
return hrefs[i];
}
}
return null;
}
function doStuff()
{
//find the specific actions div... not important code...
var actionsDiv = getActionsDiv();
var linkButton = getLinkButton(actionsDiv);
if (linkButton != null)
{
if (linkButton.click)
{
linkButton.click();
}
else
{
alert("Cannot click");
}
}
}
I don't really want to use jQuery unless absolutely necessary
I think you're looking for element.dispatchEvent:
function simulateClick() {
var evt = document.createEvent("MouseEvents");
evt.initMouseEvent("click", true, true, window,
0, 0, 0, 0, 0, false, false, false, false, 0, null);
var cb = document.getElementById("checkbox");
var canceled = !cb.dispatchEvent(evt);
if(canceled) {
// A handler called preventDefault
alert("canceled");
} else {
// None of the handlers called preventDefault
alert("not canceled");
}
}
I read your question as "I'm trying to fire the onclick event for my button", whereas everyone else seems to have read it as "I'm trying to handle an onclick event for my button". Please let me know if I've got this wrong.
Modifying your code, a proper x-browser implementation might be:
if (linkButton != null)
{
if (linkButton.fireEvent)
linkButton.fireEvent("onclick");
else
{
var evt = document.createEvent("MouseEvents");
evt.initMouseEvent("click", true, true, window,
0, 0, 0, 0, 0, false, false, false, false, 0, null);
linkButton.dispatchEvent(evt);
}
}
onclick attribute should be crossbrowser:
<input type="button" onclick="something()" value="" />
EDIT
And there was this question that seems to be about the same problem: setAttribute, onClick and cross browser compatibility
onclick="methodcall();" works for me fine...
you can use onClick attribute or if you need more functionality have a look at jQuery and events it offers: http://api.jquery.com/category/events/

disabling modal popup in jqgrid

I want to create a custom message without using the modal popup in jqgrid. Is there a way to disable it? Or is there a way to change the contents of the modal?
Can you be more specific? If you want your own modal dialog, you could just add an event handler (on an Edit button, for example) that when fired will open your own custom dialog. You can use the jQuery UI dialog for this purpose, and just have it open to your own custom form.
Update
After inspecting the jqGrid source code, info_dialog is the function that is used to display this particular dialog. There is a separate call to display the "Loading..." popup. Offhand there does not seem to be a simple way to disable info_dialog. However, you could modify the jqGrid source to accomplish what you need. You could either:
Return immediately from info_dialog - which may be extreme because it could report other errors you need - or,
Find and comment out the call that is displaying this particular ajax error. There is some trial-and-error involved, but with only 18 calls to this function it will not take you long to track down. In fact, start by commenting out this instance, since it is called from the error function of an ajax call:
info_dialog(a.jgrid.errors.errcap,e.status+" : "+e.statusText+"<br/>"+u,a.jgrid.edit.bClose);
Obviously such a modification is a last resort, but once it works you might consider rolling a patch for the jqGrid team to disable the alert.
Search for div.loadingui div.msgbox { ... } somewhere in css files. I think editing this css class will get the job done.
i have changed the z-index of modal popup on runtime once you can access to it you can do any customization
editoptions: { size: 20, maxlength: 10,
dataEvents: [
{ type: 'keypress',
fn: function (e) {
if (e.keyCode == 13) {
**$("#info_dialog").css('z-index', '100000');**
}
}
}
]
} }
Also, if you can do it on another place if you have server response such as error
onCellSelect: function (rowid, iCol, aData) {
currentRow = rowid;
if (rowid && rowid !== lastsel) {
if (lastsel) jQuery('#ppGrid').jqGrid('restoreRow', lastsel);
$("#ppGrid").jqGrid('editRow', rowid, true, null, null, null, {}, reload,OnError);
lastsel = rowid;
}
else if (rowid && rowid === lastsel)
{ $("#ppGrid").jqGrid('editRow', rowid, true, null, null, null, {}, reload,OnError); }
}
Yes you can do it. you can make visible property to false [$("#info_dialog").visible(false);] of the modal box, and you can call what ever your custom modal box.
editrules: { custom: true, custom_func: validate_edit }
function validate_edit(posdata, colName) {
var message = "";
if (posdata != '' && $.isNumeric(posdata))
return [true, ""];
if (posdata == '')
message = colName + " field is required"
if (!$.isNumeric(posdata))
message = posdata + " is not a number";
alert(message);
$("#info_dialog").visible(false);
return [false, ""];
}
I know this is out of the topic, but have you tried SlickGrid https://github.com/mleibman/SlickGrid/wiki/examples

ASP.NET Post-Back and window.onload

I got a function which checks if some input fields are changed:
var somethingchanged = false;
$(".container-box fieldset input").change(function() {
somethingchanged = true;
});
And a function which waits on window.onload and fires this:
window.onbeforeunload = function(e) {
if (somethingchanged) {
var message = "Fields have been edited without saving - continue?";
if (typeof e == "undefined") {
e = window.event;
}
if (e) {
e.returnValue = message;
}
return message;
}
}
But if I edit some of the fields and hit the save button, the event triggers, because there is a post-back and the fields have been edited. Is there anyway around this, so the event does not fire upon clicking the save button?
Thanks
When I do this pattern I have a showDirtyPrompt on the page. Then whenever an action occurs which I don't want to go through the dirty check I just set the variable to false. You can do this on the client side click event of the button.
The nice thing about this is that there might be other cases where you don't want to prompt, the user you might have other buttons which do other post backs for example. This way your dirty check function doesn't have to check several buttons, you flip the responsability around.
<input type="button" onclick="javascript:showDirtyPrompt=false;".../>
function unloadHandler()
{
if (showDirtyPrompt)
{
//have your regular logic run here
}
showDirtyPrompt=true;
}
Yes. Check to see that the button clicked is not the save button. So it could be something like
if ($this.id.not("savebuttonID")) {
trigger stuff
}

Categories