ExtJS 3.4 MessageBox buttons YESNO strange behaviour - javascript

I have this problem with MessageBox component in ExtJS 3.4 and I'm searching desperately for a solution.
function supprimerCatalogPreEnregFunction() {
Ext.Msg.show({
msg: document.getElementById('confirmDeleteMessage').value,
buttons: Ext.Msg.YESNO,
icon: Ext.MessageBox.ERROR,
fn : function (btn) {
if (btn == 'yes') {
document.getElementById('deleteForm:deleteCatalogPreEnreg').onclick();
}
}
});
}
The problem is that my btn return value 1, not 'yes' or 'no' as i expect. And it drives me crazy because I've trying a lot of solutions and I can't understand why this happens.
This function is a handler for a new Ext.Button.
The button is part of a new Ext.Panel, buttons:[...].
I can't understand why the button has that strange value and it frustrates me a lot.
Can a missing comma produce this behaviour? Although, I didn't found a missing comma.
L.E:
I've researched more and I looked more carefully in my code and, helped by debugger, I found that my function
function (btn){}
receives as arguments on position 0: value 1, on second position receives Window (my current location) and the third argument is the one wich should've been received by my component, and it looks like ["yes", "", Object{}] etc.
And i think this is the argument I need, where 0st position is the value of my btn, but I don't know where the other arguments come from to know what I need to do to in order to make it work.
As I'm still a little confused, I'll update this with a general explanation about how I've implemented this handler.
So, at Ext.onReady I load a function init()
Then, in this function i made a var deleteButton = new Ext.Button
This button has a handler which is my initial function from question
The deleteButton is added to a new Ext.Panel with buttons:[deleteButton, etc]
This panel is added as item to a Ext.TabPanel
And, finally, TabPanel is added to a ViewPort.

The Sencha Documentation shows the implementation like:
// Prompt for user data and process the result using a callback:
Ext.Msg.prompt('Name', 'Please enter your name:', function(btn, text){
if (btn == 'ok'){
// process text value and close...
}
});
Running the following code using ExtJs 3.4:
Ext.onReady(function(){
Ext.BLANK_IMAGE_URL = '/js/ext-3.4.0/resources/images/default/s.gif';
Ext.Msg.show({
msg: "test",
buttons: Ext.Msg.YESNO,
icon: Ext.MessageBox.ERROR,
fn : function (btn, text) {
if (btn == 'yes') {
console.log(btn, text);
}
}
});
});
Output (Firebug console):
yes (an empty string)
So your code should be working. I would check to see if there are any global overrides being loaded and test it in isolation

Looking at the source it seems that the first param is the button clicked (Ext.Msg.YESNO which may give you a truthy result) but the second parameter passed is the text value you are looking for:
var handleButton = function(button){
buttons[button].blur();
if(dlg.isVisible()){
dlg.hide();
handleHide();
//here the arguments are button, activeTextEl.dom.value and opt... so look at the second argument in your callback
Ext.callback(opt.fn, opt.scope||window, [button, activeTextEl.dom.value, opt], 1);
}
};
I'd try changing your code to:
function (btn, btnTxt) {
if (btnTxt == 'yes') {
document.getElementById('deleteForm:deleteCatalogPreEnreg').onclick();
}
}

First of all, thank you very much for replies.
It seemed that the problem was from a script that I was included it in my jsf page.
And that messed up parts of my code and that's why my component had a strange bahviour.
I solved it by removing that script and let the function as I posted it initially.

Related

javascript window['func'] with parameters returning undefined instead of function

I'm trying to pass json to a function, which in turn takes the json and displays dynamic ui-modal dialog. When I try to pass the button events(functions) , thy are getting executed and returning undefined how can I pass reference to the function instead of actual function. Sorry for my english the code below explains much better:
//heres my ui model function
function showDialog(json) {
var dialog_id = json.id;
if(typeof($(dialog_id)[0]) === "undefined") {
$(body).append("<div id='dialog-confirm'></div>");
}
$(dialog_id).html(json.confirmationText);
$(dialog_id).dialog({
modal: true,
title: json.title,
height: 250,
width: 400,
buttons:json.buttons
});
}
//here is the function which calls
showDialog({"id":"#dialog-confirm","title":"blaa","confirmationText":'randomtext',"buttons":[{"text":"Cancel","click":window["noAction"]},{"text":"Confirm","click":window["doAction"]('pram1','param2')}]});
var noAction = function(){$('#dialog-confirm').dialog('close');}
var doAction = function(param1,param2){//do some logic};
noAction function is working correctly. (when the model is called and cancel is clicked the dialog disappears)
doAction function is getting evaluated when the function showDialog is called and is returning undefined (verified in console). How can I bind doAction to confirm button. (ie, when Confirm is clicked I want to call doAction).
P.S: I know how to do it with custom on click handlers but I think it would be a work around but not the actual solution.
Any help is greatly appreciated. Thanks in advance!
try
showDialog({..., "buttons":[...,{"text":"Confirm","click":function(){doAction(param1,param2);} }]})

Pass function to alertify.js

Im knocking my head to this scripts and I cant get my function to be displayed inside the Aletify.js alerts.
Some help will be incredibly helpful ;-)
The Function:
Oshoplang = {
// System Message Text
RemoveError: '<p>This item has now been removed from your cart.\n\nThank you.',
Added: 'Has now been added to your cart',
OutOfStock: '<p>This item is not currently available or is out of stock.</p>',
PreOrder: '<p>Your pre-order has been made successfully.\n\nThank you.</p>',
InvalidQuantity: '<p>It looks like you entered an invalid quantity.\n\nPlease try again.</p>',
}
window.alert = function() {};
$("#confirm-else").on('click', function() {
reset();
$('#e-content').addClass('blur');
alertify.alert(Oshoplang, function(e) {
if (e) {
alertify.success("OK");
$('#e-content').removeClass('blur');
location.reload();
} else {
alertify.error("You've clicked Cancel");
}
});
return false;
});
I normally don't get a message on the run, but this way but i believe i'm close somewhere :-)
Not sure if you're still having this issue, but I believe that the alertify.alert function doesn't have any callbacks, as it's just a way to show a message. You're probably looking for the alertify.confirm instead.
The message is also not showing up because the first argument to alertify.alert or alertify.confirm needs to be a string. In your example, you're passing an object.
I've set up a demo of your code which has been adjusted to work on here on JSFiddle.
For what it's worth, the code sample is using an older version of alertify (0.3) and it has been updated, so that version 1 which is now out would have a somewhat adjusted syntax.

Cannot switch between classes with jQuery

I've got a problem with switching between element classes - probably sth stupid, but I couldn't find the answer.
In my system I display a list of items. Now I want to be able to promote items, so that they appear at the top of the list. I created some backend infrastructure which works ok and added things to my frontend: a star (a span with star bg) next to every item's title and a jQuery script which is supposed to:
listen to 'click' event - when I click on a star
get some data- attributes from the span
post them to my controller
the controller checks if I'm allowed to promote items and replies 'true' or 'false'
if 'true' then I switch between 'gold-star' and 'silver-star' classes of the item
For some reason the classes don't switch - only when I refresh the page I can see the effect. I tried debugging with Firebug - it gets to the toggle line, but then nothing happens.
Here's the code:
<span class="silver-star promote">
$(".promote").bind("click", function() {
var $this = $(this);
var itemId = $this.attr("data-id"),
isPromoted = true;
if ($this.hasClass("gold-star")) {
isPromoted = false;
}
$.post('/promoteitems', { itemId: itemId, isPromoted: isPromoted }, function(allowPromotion) {
if (allowPromotion == true) {
$this.toggleClass("silver-star").toggleClass("gold-star");
}
});
});
Thanks in advance!
When you are getting a response back it might not recognise it as a boolean simple test would be to check response as string
From your comment on the question:
...the allowPromotion value is 'True' (with a capital T)...
That tell us it's a string, not a boolean. You don't want to just do if (allowPromotion), because that will toggle the classes even if you get back "False".
Instead:
if (allowPromotion == "True") { // Note the quotes and capital T
// ...toggle the classes
}
Or if you want to allow for possibly getting back something with a lower-case T at some point in the future:
if (/^\s*true\s*$/i.test(allowPromotion)) {
// ...toggle the classes
}
That's over-engineering it a bit (it'll work with "True", "true", " True " [note the spaces], and even an actual boolean true)...

Returning a value to another function

I am new to jQuery. I have created a form where I hide some fields. I have created a function on the click of a button field. Here in this function definition I unhide the hidden fields one being my text field and another a button. I code that I use is:
finishOrder: function() {
document.getElementById("create-pwd").style.display = "block"
document.getElementById("finish-ok").style.display = "block" // this is my another button
// do further processing
},
Now on the click of another button (please see the comment "this is my another button") I call another function like this:
FinishcheckPassword: function() {
var pas = document.getElementById("pos-password")
var user = new db.web.Model("res.users").get_func("read")(this.session.uid, ['password']).pipe(function(result) {
if(pas.value == result.password){
return true
});
},
After the if condition returns true value, I want to the control to be transferred to the first function where I can do further processing. Is it possible, if yes how can this be achieved? Any help will be appreciated.
Sure, something like this:
$('#finish-ok').click(function(){
if(FinishcheckPassword()){
finishOrder();
}
}
Of course, this is probably not exactly the right code for you. The fact that you are assigning all your functions with : rather than = suggests that they are inside of some larger object. Therefore, they'd have to be called like myObject.finishOrder(). But the general approach of what I wrote above will work.
As a couple side notes, you have tagged the question with jQuery and refer to it in your post, but there isn't actually a single line of jQuery in your code.

checkbox event handler throws error for click event in chrome, safari works fine with keyboard event

i have a list of dynamically created check boxes. when the state of the check box changes, a function is executed. the function runs perfectly in firefox 3.6 perfectly whether the user clicks the check box, or uses keyboard input to change the check box. in chrome or safari, the function executes fine using the keyboard, but errors out with a mouse click. i cannot seem to find why the code acts differently from a mouse click vs a keyboard entry.
here is what i believe is the pertinent code:
var q_id = $j('label:contains("SCORP Statewide Need ")').attr('for');
console.log(q_id); //writes out answer id a_721
an ajax post will create a list of check boxes:
if(found == true){
output+="<div name='"+q_id+"'><input type='checkbox' name='"+q_id+"' id='"+q_id+"."+i+"' class='check' checked='checked' onChange='saveStateNeed("+q_id+")' value='"+list[i]+"'/>";
}else{
output+="<div name='"+q_id+"'><input type='checkbox' name='"+q_id+"' id='"+q_id+"."+i+"' class='check' onChange='saveStateNeed("+q_id+")' value='"+list[i]+"'/>";
}
output+=" <label name='l_"+q_id+"' for='"+q_id+"."+i+"' id='l_"+q_id+"."+i+"'>"+ list[i] +"</label></div>";
output+="<div class='clearboth'></div><br/>";
$j('##div_'+q_id).append(output);
all this is generated perfectly in all browsers.
the error is in the callback saveStateNeed();
function saveStateNeed(list){
console.log('in saveStateNeed');
console.log(list);// prints out an array of the checkboxes [input#a_721.0.check Non-motorized trails, input#a_721.1.check Sports a...ayfields, input#a_721.2.check Land Acq...projects, input#a_721.3.check Picnicki...cilities, input#a_721.4.check Nature s...wildlife]
// **in safari i get function()** but it still works with keyboard, fails with click
// the next assignment $me fails.
var $me = $j('input [name="'+list+'"]');
var isChecked = $me.context.activeElement.checked;
var $value = $me.context.activeElement.attributes['value'].nodeValue;
console.log($me); out puts the object selected as an expandable firebug object []
console.log($value); outputs label for object: Picnicking/day use facilities
console.log(isChecked); outputs true false
if(isChecked){
}else{
}
$j.ajax({
type: "POST",
url: });
}
this is all kind of convoluted, im just hoping someone knows why i would get a different result from a click then a keyboard entry, when the same code is actually being executed.
i really hope this isnt all too convoluted.
thanks for taking a look at this, and i really appreciate any comments or suggestions you might have.
cheers.
You might have better luck if you attach the checkbox behavior as a delegated event instead of explicit assignment.
It looks like you're using jQuery, so you can do that like so:
$j('input.check').live('change', function(event) {
var jThis = $j(this);
// grab id from checkbox
var ID = jThis.attr('id').split('.')[0];
saveStateNeed(ID, jThis.attr('checked'));
return true;
});
Also: are you certain that the error is in the event handler, and not in the saveStateNeed function?
EDIT: Based on your updates, here's what I've got. First, note the minor change to the function above; now it passes two values. Second, if you want to act on a checkbox being toggled, modify saveStateNeed to accept two values: an ID and a boolean. Like so:
function saveStateNeed(ID, bChecked) {
console.log('checkbox ' + ID + ' is ' + (bChecked) ? 'checked' : 'not checked');
if(bChecked) {
// do something
} else {
// do something else
}
}

Categories