I'm trying to do an autocompleter in mootools 1.11. Everything works fine but i just cant check if
this.selectel.getNext()
is null or whatever. Firebug outputs [li] for every element and [null] for the non existing element i output via getNext();
I saw that some people are just doing:
if(this.selectel.getNext()) {...
but thats not working here because i always get the null object. Something terribly stupid must be going on here...
Here comes some code around the problem:
this.selectel = $$('ul.results').getFirst();
...
onCommand: function(e, mouse) {
if (e.key && !e.shift) {
switch (e.key) {
case 'up':
this.selectel.getPrevious().addClass('active');
if(this.selectel) this.selectel.removeClass('active');
this.selectel = this.selectel.getPrevious();
e.stop();
return;
case 'down':
var test = this.selectel.getNext();
console.log(typeof(test));
if(this.selectel.getNext() != null) { // not working
this.selectel.getNext().addClass('active');
if(this.selectel) this.selectel.removeClass('active');
this.selectel = this.selectel.getNext();
}
e.stop();
return;
}
}
your are calling getNext() twice.
replace these lines:
if(this.selectel.getNext() != null) { // not working
this.selectel.getNext().addClass('active');
if(this.selectel) this.selectel.removeClass('active');
this.selectel = this.selectel.getNext();
}
with:
if(el = this.selectel.getNext() != null) { // not working
el.addClass('active');
if(this.selectel) this.selectel.removeClass('active');
this.selectel = el;
}
Related
I have been fighting this problem all day. Heres a snippet of my code, 5 lines down in the else if is where things get screwy. I am also new to Javascript so that may be the reason I am unable to spot the mistake, but from what I have seen elsewhere, this code should work. Also the comments on lines 5 and 6 are swapped.
if (msg.payload.License_Plate !== null) {
// This portion checks for a valid number plate
if (readlpr == dblpr); { // we have a direct match, open the gate
opengate = 1; // will send open signal to gpio
} else if(readlpr !== null); { // from here on, we are checking for a partial plate match
validdigits = 0; // make sure we have data before continuing, as may be a rfid match
{
if (!context.count); { // check to see if counter already used, if not initialise it
context.count = 0;
Image of error message
You have a few errors:
if (readlpr == dblpr); {
...
} else if(readlpr !== null); {
...
if (!context.count); {
And also an extra opening-brace.
These shouldn't have a semi colon on the end:
if (readlpr == dblpr) {
...
} else if(readlpr !== null) {
...
if (!context.count) {
In the end it should look something like this:
if (msg.payload.License_Plate !== null) {
if (readlpr == dblpr) {
opengate = 1;
} else if(readlpr !== null) {
validdigits = 0;
// { <!-- Remove this as well, it's an extra brace
if (!context.count) {
context.count = 0;
For a website there is this function under sources with the code:
betSlipView.prototype.stakeOnKeyUp = function(_key) {
var model = ob.slip.getModel(),
defval = ob.cfg.default_bet_amount;
selector = toJqId(["#stake-", _key].join('')),
stake_box = $(selector),
spl = stake_box.val();
if(spl != defval) {
spl = ob.slip.cleanFormatedAmount(spl);
if(spl === '' || isNaN(spl)) {
spl = 0;
$(selector).val('');
}
model.setBetStake(_key, spl);
$(toJqId(['#ob-slip-estimate-', _key].join(''))).html(
model.getBet(_key, 'pretty_returns')
);
} else {
$(selector).val(defval);
model.setBetStake(_key, defval);
$(toJqId(['#ob-slip-estimate-', _key].join(''))).html(
model.getBet(_key, 'pretty_returns')
);
}
//Update bonus amount
try {
var offers = model.getBet(_key, 'offers');
}
catch(err) {
var offers = "";
}
if(offers !== "" && typeof offers['STLWIN'] !== "undefined") {
this._handleAccumulatorBonusElements(_key, offers['STLWIN']);
};
// potential returns for this bet
this.updateTotals();
};
I cannot figure out how to (if possible) call this function directly from the console. Firstly, when I try to write betSlipView in the console, it cannot be found. Consequently if I copy the code to the console to define the function, betSlipView is still not found and if I try to change the function name, there are some names in the function body that cannot be found either. I wish to call this function with certain arguments, is this possible?
The whole code can be found here https://obstatic1.danskespil.dk/static/compressed/js/ob/slip/crunched.pkg.js?ver=0305f181cb96b61490e0fd2adafa3a91
I've been working to scrape some webpage that is using the OWASP CRSFGuard project for protection. The library seems to be causing one of my requests to get a 401 so I started digging through their code and noticed the following;
function isValidDomain(current, target) {
var result = false;
/** check exact or subdomain match **/
if(current == target || current == 'localhost') {
result = true;
} else if(true == false) {
if(target.charAt(0) == '.') {
result = current.endsWith(target);
} else {
result = current.endsWith('.' + target);
}
}
return result;
}
From what I can tell, there must be instances where this code is executed; result = current.endsWith('.' + target);. Given true == false is inherently false, how would the code reach that statement? Is this some JS oddity (I know we're not using the strict === equality, but seriously...)?
Answer: It will never reach that code block.
function isValidDomain(current, target) {
var result = false;
/** check exact or subdomain match **/
if (current == target || current == 'localhost') {
result = true;
} else if (true == false) {
if (target.charAt(0) == '.') {
result = current.endsWith(target);
} else {
result = current.endsWith('.' + target);
}
}
return result;
}
var trueFalse = document.getElementById('trueFalse');
trueFalse.innerHTML = isValidDomain('true', 'false') ? 'WTF!' : 'All is good in the JS World';
trueFalse.addEventListener('click', function(e) {
trueFalse.innerHTML = (true == false) ? 'WTF!' : 'All is good in the JS World Still';
});
<div id="trueFalse"></div>
I would say that Blazemonger is most likely correct.
That else if probably had some other condition at some point, and for whatever reason, they decided they didn't want that block of code to execute anymore, so they changed the condition to something that is always false.
It's also not entirely uncommon to see programmers use 1 === 0 as an indication for false. Why they would want to do this is anybody's guess.
I have the following JavaScript function which is failing in internet explorer 9 on the line which declares the variable filesattached.
function VesselDetails() {
insurancestart = $('#ctl00_ContentPlaceHolder1_datetimepickerinsstart').val();
insuranceend = $('#ctl00_ContentPlaceHolder1_datetimepickerinsend').val();
filesattached = $("input:File")[0].files.length;
//set up JS objects
$('#ctl00_ContentPlaceHolder1_datetimepickerinsend').datetimepicker({ format: 'd/m/Y H:i a' });
$('#ctl00_ContentPlaceHolder1_datetimepickerinsstart').datetimepicker({ format: 'd/m/Y H:i a' });
//subscribe to change events
$('#ctl00_ContentPlaceHolder1_datetimepickerinsstart').change(function () {
insurancestart = $("ctl00_ContentPlaceHolder1_datetimepickerinsstart").val();
});
$('#ctl00_ContentPlaceHolder1_datetimepickerinsend').change(function () {
insuranceend = $("ctl00_ContentPlaceHolder1_datetimepickerinsend").val();
});
$("input:File").change(function () {
filesattached = $("input:File")[0].files.length;
});
ins_client();
}
The ins_client method looks like this:
function ins_client(sender, e) {
if (pagemode == 'EditVessel') {
e.IsValid = true;
}
if (pagemode == 'NewVessel') {
if (insurancestart !== '' && insuranceend !== '' && filesattached > 0) {
e.IsValid = true;
}
else {
e.IsValid = false;
}
}
}
This all works perfectly well in chrome and ie 11 but the length property is returning an undefined for ie 9. I am using the length because I only want the page to be valid for a new vessel request once a document has been submitted, is there another way of doing this which will work in ie 9 onwards and chrome, apologies if this has already been answered elsewhere but I cannot find a workaround anywhere that enables this to continue working in the same way but in ie9 onwards and chrome.
I replaced:
filesattached = $("input:File")[0].files.length;
With:
var areFilesAttached = document.getElementById('ctl00_ContentPlaceHolder1_fuAttachment').value ? true : false;
Within the VesselDetails function.
Then replaced the if statement within ins_client with the following:
if (pagemode == 'NewVessel') {
if (insurancestart !== '' && insuranceend !== '' && areFilesAttached == true) {
e.IsValid = true;
}
else {
e.IsValid = false;
}
}
This was an alternative approach which enabled me to check whether or not a file had been provided without using the files.length property which is not compatible with IE9.
I'm afraid this can't be achieved, IE9 does not support HTML5 File API and therefore it returns undefined value for files property.
Take a look at FILE API
Using pure JavaScript without any library like jQuery, how could I detect if a variable holds a DOM Class or ID?
For example if I pass into a function a value that could be...
var mySelector = ".class-name";
or
var mySelector = "#id-name";
Then based on if mySelector holds a Class or ID I would run
document.getElementsByClassName
or
document.getElementsById
What would be the best way to do this without the use of a library like jQuery or another library?
Take a look at document.querySelector or document.querySelectorAll, instead. Both of those can find elements by ID or class (as well as other selectors). querySelector will return 1 element, querySelectorAll will return all elements.
var mySelector = ".class-name", // "#id-name" will also work fine.
elements = document.querySelectorAll(mySelector);
Note that this doesn't work in IE < 8 (see http://caniuse.com/#search=querySelectorAll). A polyfill would be the best way to handle it to add IE7 support.
You can use this simple if/else statement to differentiate. This would also allow you to run other code based on whether it's a class or an ID you are referencing.
var mySelector = ".class-name";
if(mySelector.charAt(0) == ".")
{
document.getElementsByClassName(mySelector.substring(1));
}
else if(mySelector.charAt(0) == "#")
{
document.getElementsById(mySelector.substring(1));
}
The first way I think is check a first symbol of stroke.
Something like:
var $ = function( string ) {
var result;
switch (string.substr(0,1)) {
case '.': result = document.getElementsByClassName(string); break;
case '#': result = document.getElementById(string); break;
default: result = document.getElementsByTagName(string); break;
}
return result;
}
var mySelector = ".class-name";
console.log( $(mySelector) );
Just because you only want a selector and not the entire jQuery library, doesn't mean you have to roll your own own. jQuery uses the Sizzle selector engine, and you could just as easily use it yourself without the overhead of full jQuery:
http://sizzlejs.com/
I'm not an advanced user, but some time ago I created this little script:
https://gist.github.com/caiotarifa/cc7d486292f39157d763
var __;
__ = function(selector, filter) {
'use strict';
var response;
function filtering(selectors, filter) {
switch (filter) {
case "first":
return selectors[0];
break;
case "last":
return selectors[selectors.length - 1];
break;
default:
return selectors[filter];
break;
}
}
selector = selector.trim();
if (typeof filter === "string") { filter = filter.trim(); }
if (selector.indexOf(' ') < 0 && selector.indexOf('.', 1) < 0 && selector.indexOf('#', 1) < 0) {
switch (selector.substr(0, 1)) {
case '.':
response = document.getElementsByClassName(selector.substr(1));
if (response.length === 1) { filter = "first"; }
if (typeof filter !== "undefined") { response = filtering(response, filter) }
break;
case '#':
response = document.getElementById(selector.substr(1));
break;
default:
response = document.getElementsByTagName(selector);
if (response.length === 1) { filter = "first"; }
if (typeof filter !== "undefined") { response = filtering(response, filter) }
break;
}
} else {
if (typeof filter !== "undefined") {
switch (filter) {
case "first":
response = document.querySelector(selector);
break;
case "last":
response = document.querySelectorAll(selector);
response = response[response.length - 1];
break;
default:
response = document.querySelectorAll(selector);
response = response[filter];
break;
}
} else {
response = document.querySelectorAll(selector);
if (response.length === 1) { response = response[0]; }
else if (response.length < 1) { response = false; }
}
}
return response;
};
It's simple to use it:
__("div")
Or passing some filter like:
__("div", "first")
I didn't make a benchmark test with it. I hope it can help you.