jQuery - IF ELSE - Not reading any variables - javascript

PROBLEM:
UPDATE: I have found that its not just with returned data from a post. Literally every if else statement disregards my variables almost entirely.
I have tried to do something extremely simple to verify my statement above.
When the code below is executed, nothing happens. I added consol.log() in before my if statement ( in place of the alert ) to make sure that its getting the data to the DOM and it is.
HTML
<input type='submit' name='Confirm' class='button' value='Confirm' >
<input type='submit' name='Cancel' class='button' value='Cancel' >
JS
$( '.button' ).on( 'click' , function() {
var btnName = $( this ).attr( 'name' ) ;
var cancel = "Cancel" ;
var confirm = "Confirm" ;
alert( btnName + cancel + confirm ) ;
if ( btnName == cancel ) {
//some function here . .
} else if ( btnName == confirm ) {
//some function here . .
}
EDIT If I run the code below, then the alert is always Cancel... What the fudge.
$( '.button' ).on( 'click' , function() {
var btnName = $( '.button' ).attr( 'name' ) ;
if ( btnName == "Cancel" ) {
alert( 'Cancel' ) ;
} else if ( btnName == "Confirm" ) {
alert( 'Confirm' ) ;
}
Not matter what i click, the functions in the if statement don't run. The weird part is, when it hits alert( btnName + cancel + confirm ) ; The data that is alerted in the browser is accurate, as in, if I click name='Confirm' the alert output looks like ConfirmCancelConfirm...

I assume you have an error:
function( data ) {
if ( returnedData == "Company Added" ) { //right here
$( '#navAdmin' ).click() ;
} else {
alert( data ) ;
}
}
It should be
function( data ) {
if ( data == "Company Added" ) {
$( '#navAdmin' ).click() ;
} else {
alert( data ) ;
}
}

I tried your JS code.
if ( btnName != cancel ) {
// This function is normal
} else {
// This function is also work
}
That's work on my machine and browser. and your (if else else if code is also work).
Chrome 44.0.2403.157 (64-bit)

Finally found my problem
I don't know where it's happening, but when I assign a variable, for example;
$( '.button' ).on( 'click' , function() {
var btnName = $( this ).attr( 'name' ) ;
}
For some reason there was a bunch of whiteSpace being added before the string.
Started Working With:
$( '.button' ).on( 'click' , function() {
var btnName = $( this ).attr( 'name' ) ;
var trimmedData = ( btnName ).trim() ;
if ( trimmedData == "Confirm" ) {
alert( "Confirm" ) ;
} else if ( trimmedData == "Cancel" ) {
alert( "Cancel" ) ;
}
I put this into my $.post function and it is working as well. I don't know where the extra space is coming from, any other thoughts are welcome. Please Let me know if I am doing something horribly wrong here..

Related

To find who's binded to an event and use if and else if with javascript

I have a function called in multiple ways.
function func1(){
if(){ //called by an onclick event
alert("!");
}else if(){ //called by another function -
alert("?"); //ex) - $(document).ready(function(){ func1()}
}
is there any way to determine if the function is bound by which event and use it with my if and else if lines? Please help.
There's several options. I use both depending on the situation.
1) Seperate the event handlers from the other function and use a parameter.
<button id="button_validate_form">Validate</button>
<button id="button_submit_form">Sumbit</button>
const doWork = function doWork( event, context ) {
if ( context === 'event_validate_form' ) alert( '!' );
else if ( context === 'event_submit_form' ) alert( '?' );
else alert( 'undefined event' );
};
document.querySelector( '#button_validate_form' ).addEventListener( 'click', event => doWork( event, 'event_validate_form' ) );
document.querySelector( '#button_submit_form' ).addEventListener( 'click', event => doWork( event, 'event_submit_form' ) );
2) Same story, but instead of adding a parameter to the function, use a data attribute on the actual DOM node.
<button id="button_validate_form" data-context="event_validate_form">Validate</button>
<button id="button_submit_form" data-context="event_validate_form">Sumbit</button>
const doWork = function doWork( event ) {
const context = event.target.getAttribute( 'data-context' );
if ( context === 'event_validate_form' ) alert( '!' );
else if ( context === 'event_submit_form' ) alert( '?' );
else alert( 'undefined event' );
};
document.querySelector( '#button_validate_form' ).addEventListener( 'click', event => doWork( event, 'event_validate_form' ) );
document.querySelector( '#button_submit_form' ).addEventListener( 'click', event => doWork( event, 'event_submit_form' ) );

Default Tab Navigation is not working in Mozilla

Normal Navigation of Tab button get stuck over this text box in Mozilla Firefox browser. On Tab key press it's not moving to next element. Working fine in IE and Chrome. Can anyone assist me to fix this?
<div class="editor-field">
<div>
<input id="Rentaljeepshop" class="ui-autocomplete-input" type="text" value="Budget Rent A Car" name="Rentaljeepshop" maxlength="50" isautocomplete="true" autocomplete="off" role="textbox" aria-autocomplete="list" aria-haspopup="true"></input>
/div>
</div>
My Jquery is:
(function( $, undefined ) {
$.widget( "ui.autocomplete", {
options: {
appendTo: "body",
delay: 300,
minLength: 1,
position: {
my: "left top",
at: "left bottom",
collision: "none"
},
source: null
},
_create: function() {
var self = this,
doc = this.element[ 0 ].ownerDocument;
this.element
.addClass( "ui-autocomplete-input" )
.attr( "autocomplete", "off" )
// TODO verify these actually work as intended
.attr({
role: "textbox",
"aria-autocomplete": "list",
"aria-haspopup": "true"
})
.bind( "keydown.autocomplete", function( event ) {
if ( self.options.disabled ) {
return;
}
var keyCode = $.ui.keyCode;
switch( event.keyCode ) {
case keyCode.PAGE_UP:
self._move( "previousPage", event );
break;
case keyCode.PAGE_DOWN:
self._move( "nextPage", event );
break;
case keyCode.UP:
self._move( "previous", event );
// prevent moving cursor to beginning of text field in some browsers
event.preventDefault();
break;
case keyCode.DOWN:
self._move( "next", event );
// prevent moving cursor to end of text field in some browsers
event.preventDefault();
break;
case keyCode.ENTER:
case keyCode.NUMPAD_ENTER:
// when menu is open or has focus
if ( self.menu.element.is( ":visible" ) ) {
event.preventDefault();
}
//passthrough - ENTER and TAB both select the current element
case keyCode.TAB:
if ( !self.menu.active ) {
return;
}
self.menu.select( event );
break;
case keyCode.ESCAPE:
self.element.val( self.term );
self.close( event );
break;
default:
// keypress is triggered before the input value is changed
clearTimeout( self.searching );
self.searching = setTimeout(function() {
// only search if the value has changed
if ( self.term != self.element.val() ) {
self.selectedItem = null;
self.search( null, event );
}
}, self.options.delay );
break;
}
})
.bind( "focus.autocomplete", function() {
if ( self.options.disabled ) {
return;
}
self.selectedItem = null;
self.previous = self.element.val();
})
.bind( "blur.autocomplete", function( event ) {
if ( self.options.disabled ) {
return;
}
clearTimeout( self.searching );
// clicks on the menu (or a button to trigger a search) will cause a blur event
self.closing = setTimeout(function() {
self.close( event );
self._change( event );
}, 150 );
});
this._initSource();
this.response = function() {
return self._response.apply( self, arguments );
};
this.menu.element.hide();this.menu = $( "<ul></ul>" )
.addClass( "ui-autocomplete" )
.appendTo( $( this.options.appendTo || "body", doc )[0] )
// prevent the close-on-blur in case of a "slow" click on the menu (long mousedown)
.mousedown(function( event ) {
// clicking on the scrollbar causes focus to shift to the body
// but we can't detect a mouseup or a click immediately afterward
// so we have to track the next mousedown and close the menu if
// the user clicks somewhere outside of the autocomplete
var menuElement = self.menu.element[ 0 ];
if ( event.target === menuElement ) {
setTimeout(function() {
$( document ).one( 'mousedown', function( event ) {
if ( event.target !== self.element[ 0 ] &&
event.target !== menuElement &&
!$.ui.contains( menuElement, event.target ) ) {
self.close();
}
});
}, 1 );
}
// use another timeout to make sure the blur-event-handler on the input was already triggered
setTimeout(function() {
clearTimeout( self.closing );
}, 13);
})
.menu({
focus: function( event, ui ) {
var item = ui.item.data( "item.autocomplete" );
if ( false !== self._trigger( "focus", null, { item: item } ) ) {
// use value to match what will end up in the input, if it was a key event
if ( /^key/.test(event.originalEvent.type) ) {
self.element.val( item.value );
}
}
},
selected: function( event, ui ) {
var item = ui.item.data( "item.autocomplete" ),
previous = self.previous;
// only trigger when focus was lost (click on menu)
if ( self.element[0] !== doc.activeElement ) {
self.element.focus();
self.previous = previous;
}
if ( false !== self._trigger( "select", event, { item: item } ) ) {
self.element.val( item.value );
}
self.close( event );
self.selectedItem = item;
},
blur: function( event, ui ) {
// don't set the value of the text field if it's already correct
// this prevents moving the cursor unnecessarily
if ( self.menu.element.is(":visible") &&
( self.element.val() !== self.term ) ) {
self.element.val( self.term );
}
}
})
.zIndex( this.element.zIndex() + 1 )
// workaround for jQuery bug #5781 http://dev.jquery.com/ticket/5781
.css({ top: 0, left: 0 })
.hide()
.data( "menu" );
if ( $.fn.bgiframe ) {
this.menu.element.bgiframe();
}
},
destroy: function() {
this.element
.removeClass( "ui-autocomplete-input" )
.removeAttr( "autocomplete" )
.removeAttr( "role" )
.removeAttr( "aria-autocomplete" )
.removeAttr( "aria-haspopup" );
this.menu.element.remove();
$.Widget.prototype.destroy.call( this );
},
What is this code means ? I guess the code given below is not complete.
case keyCode.TAB:
if ( !self.menu.active ) {
return;
}
self.menu.select( event );
break;
Suggestion: Check your firebug console, if there will be any kind of JavaScript error, it will be displayed over there.

Catching ⌘+1 in Safari JavaScript

I'm writing a Safari 6 extension which adds a few keyboard shortcuts. One of the things I'd like to do is catch when the user presses ⌘+1 ⌘+2, etc. Right now, Safari seems to not fire any event when this happens. Here's a Fiddle: http://jsfiddle.net/Xe9YQ/ to show the code, and here's the JS:
$( 'body' ).bind( 'keypress', function ( event ) {
var modifier = '';
if ( event.metaKey ) {
modifier += 'cmd-';
}
if ( event.ctrlKey ) {
modifier += 'ctrl-';
}
if ( event.altKey ) {
modifier += 'alt-';
}
if ( event.shiftKey ) {
modifier += 'shift-';
}
$( 'body' ).html( modifier + event.keyCode );
});
If you try "⌘+j", "⌘+t", or even "⌘+0" and "⌘+shift+5" you'll see correct output. From this, it seems that it's not a problem of overriding browser shortcuts, and not a problem of using the numerical row.
Is anyone familiar with this problem? Is this a known bug? I'd appreciate any advice.
You have to use the keydown event in combination with preventDefault(), because ⌘ combinations may have bindings already (in Chrome, for example ⌘ + 1 switches to the first tab).
$( 'body' ).bind( 'keydown', function ( event ) {
var modifier = '';
if ( event.metaKey ) {
event.preventDefault();
modifier += 'cmd-';
}
if ( event.ctrlKey ) {
modifier += 'ctrl-';
}
if ( event.altKey ) {
modifier += 'alt-';
}
if ( event.shiftKey ) {
modifier += 'shift-';
}
$( 'body' ).html( modifier + event.keyCode );
});

IE event don't catch element

I'm writing a script which prevents form clicking, but i can't make it work in IE7 - 8, maby anyone know why it is?
I try to use ev = e || window.event; but nothing good happens.
Please help, and thanks in future.
(function( button ) {
$( document ).click(function( e ) {
ev = e || event;
var clickedEl = ev.srcElement || ev.target;
var parentClass = $( button ).attr( 'class' ).split(' ')[0];
if ( clickedEl !== button && $( clickedEl ).parents( '.' + parentClass ).
length == 0 && !$( clickedEl ).hasClass( parentClass ) ) {
// DO SOMETHING
}
});
})($('.category_select')[0]);
Because you're using jQuery, an event object will be passed to the callback, regardless of the browser. Though it's important to note that you won't be receiving the "pure" event object: it's wrapped in a jQuery object. To get the true event object, do this:
var trueEvent = e.originalEvent;
That should do the trick, mind you: you won't have the jQuery stopPropagation method in IE8, you'll have to correct for that manually by using .returnValue = false and .cancelBubble = true
(function( button )
{
$( document ).click(function( e )
{
var ev = e.originalEvent,//this is all you need to do, plus ev is a variable, declare it as such,
clickedEl = ev.srcElement || ev.target,//separate var declarations by comma
parentClass = $( button ).attr( 'class' ).split(' ')[0];
if ( clickedEl !== button && $( clickedEl ).parents( '.' + parentClass ).length == 0 && !$( clickedEl ).hasClass( parentClass ) )
{
// DO SOMETHING
}
});
})($('.category_select')[0]);
That should workI also had a look at the jQuery reference this is what it says on the jQuery event object

Check First Char In String

I have input-box. I'm looking for a way to fire-up alert() if first character of given string is equal to '/'...
var scream = $( '#screameria input' ).val();
if ( scream.charAt( 0 ) == '/' ) {
alert( 'Boom!' );
}
It's my code at the moment. It doesn't work and I think that it's because that browser doesn't know when to check that string... I need that alert whenever user inputs '/' as first character.
Try this out:
$( '#screameria input' ).keyup(function(){ //when a user types in input box
var scream = this.value;
if ( scream.charAt( 0 ) == '/' ) {
alert( 'Boom!' );
}
})
Fiddle: http://jsfiddle.net/maniator/FewgY/
You need to add a keypress (or similar) handler to tell the browser to run your function whenever a key is pressed on that input field:
var input = $('#screameria input');
input.keypress(function() {
var val = this.value;
if (val && val.charAt(0) == '/') {
alert('Boom!');
}
});

Categories