Javascript indexOf condition not behaving as expected - javascript

I have a javascript function that runs on window.onload:
if(window.onload) {
var curronload = window.onload;
var newonload = function() {
curronload();
formatICCID_IMEI();
};
window.onload = newonload;
} else {
window.onload = formatICCID_IMEI;
function formatICCID_IMEI() {
var IMEI = $find("<%=cbIMEI.ClientID %>");
alert(IMEI.get_textBoxControl().value);
alert(IMEI.get_textBoxControl().value.indexOf("."));
if (IMEI.get_textBoxControl().value.indexOf(".") > -1) {
alert("Hi!");
}
}
I'm using this more elaborate way of calling my function from this link because if I just use window.onload or document.onload, my control (cbIMEI) is not found. Using this more elaborate method, I don't have that problem. However, my function formatICCID_IMEI is acting strangely. I don't know if it's due to the way I'm calling formatICCID_IMEI, or just something in formatICCID_IMEI that I'm not seeing. If I comment out
if (IMEI.get_textBoxControl().value.indexOf(".") > -1) {
alert("Hi!");
the first and second alerts tell me that
IMEI.get_textBoxControl().value = 351937.04.230880.7
and that
IMEI.get_textBoxControl().value.indexOf = 6
all as expected. HOWEVER, if I comment out the two above alert lines and uncomment the IF condition, the line
alert("Hi!");
never runs. If I uncomment all lines, none of the alerts run. The same behavior holds true if I'm in debug mode. If the condition is uncommented, my cursor never gets to my function at all. What the heck?

You have no close bracket for the if(window.onload) condition - is that intentional?
Since you're using jQuery, why are you not just using the standard $(document).ready stuff?
function formatICCID_IMEI() {
var IMEI = $find("<%=cbIMEI.ClientID %>");
alert(IMEI.get_textBoxControl().value);
alert(IMEI.get_textBoxControl().value.indexOf("."));
if (IMEI.get_textBoxControl().value.indexOf(".") > -1) {
alert("Hi!");
}
}
$(document).ready(formatICCID_IMEI);

Related

JavaScript - getElementById doesn't work on specific page

I want to automate clicking the agree button to Google's cookie policies.
(I clean cookies after closing a tab, and I don't want to create a google account, so I get asked every time I use google)
There is a div element with the ID "introAgreeButton" that I'm trying to access with my script:
<div role="button" id="introAgreeButton" [...]></div>
However, document.getElementById('introAgreeButton') always returns null.
My first thought was that the element wasn't loaded by the time my function was executed. But it doesn't work if I execute it on window.onload, or even if I run it in a loop until the element is definitely there:
window.onload = function() {
var x = document.getElementById('introAgreeButton')
console.log(x)
}
Output:
null
function loop() {
var x = document.getElementById('introAgreeButton')
if (x) {
console.log('success')
} else {
loop()
}
}
Output:
null
null
null
...
Can be tested on https://www.google.com/search?hl=en&q=test
Anyone have an idea why this is and how to solve it?
Edit: I execute the script via the browser extension TamperMonkey
You can use setInterval to check if element is rendered in DOM like this :
document.addEventListener('DOMContentLoaded', function () {
var intervalID = null;
function checkElementInDOM () {
var element = document.getElementById('introAgreeButton');
if (element) {
clearInterval(intervalID);
// DO YOUR STUFF HERE ...
}
}
intervalID = setInterval(checkElementInDOM, 100);
});
To be used intelligently, however, so as not to have a setInterval which works continuously. Maybe think about adding a maximum number of attempts.

Onload Javascript/jQuery Not Working In HTML

Java script in Html is as follows.
$(document).ready(function () {
var found = {{.found}}
window.alert("hiiii");
if (foundRecords==true) {
document.getElementById("abc").style.display = "block";
}
return
});
This should get loaded during the time of html loading. But it's not at all loading. I didn't find anything wrong in this simple peace of code.
if you want to get elements with class found {{.found}}
window.onload = function()
{
var found = document.getElementsByClassName("found");
if (found) {
document.getElementById("abc").style.display = "block";
}
}
If you use jQuery to load that function it will take a slight change:
$(document).ready(function () {
// get the class found and assign it to a variable found
var found = $('.found') // it was {{.found}} producing an error
window.alert("hiiii");
// where does foundRecords come from? it is up to you to clear this
if ( foundRecords == true ) {
document.getElementById("abc").style.display = "block";
}
// what is the return good for?
// it would be better to return true or false
// or leave it away
return;
});
Check the jsFiddle:
http://jsfiddle.net/bx0e18L4/
Now it alerts the message, but still has the problem with the variable foundRecords. Take care for that.
EDIT:
According to your comments above the variable foundRecords should be found, so the critical line should be:
if ( found == true ) { // processing }

$(document).ready(function(){ code }); not getting called

I know this has been asked multiple times, but neither of the answers seem to help me.
I've been almost two days trying to get around this but I haven't been able to figure out what's going on.
I have the following code:
alert('Before document.ready');
$(document).ready(function () {
alert('Actual document.ready');
addNumberValidation($("#quantity"), $("#quantityError"));
addNumberValidation($("#price"), $("#priceError"));
$("#form").submit(function(){
var quantityValid = validar( $("#quantity"), $("#quantityError") );
var priceValid= validar( $("#price"), $("#priceError"));
var formValid = quantityValid && priceValid;
return formValid ;
});
});
function addNumberValidation(mainElement, errorElement) {
mainElement.keyup(function () {
validate($(this), errorElement);
});
}
function validate( mainElement, errorElement) {
var regex = /^[0-9]+$/;
var result = false;
if ( mainElement.val().match(regex)) {
errorElement.text('');
result = true;
} else {
errorElement.text('Must be a number');
result = true;
}
return result;
}
The script is getting loaded correctly because the "Before document.ready" alert is getting called correctly. Also, jQuery is getting loaded as well because other js code is executing properly.
My console shows no error whatsoever and the script under the sources tab in Chrome is complete.
I documented the functions to see if there was something wrong with that and it still didn't work.
Any insights of what could be going on?
Found the issue. Another library was making a conflict that avoided the document.ready to get called

How do I get a ready function and another function to play nicely in document.ready?

In my post.js, I have this:
var ready;
ready = function() {
// This is the Sidebar toggle functionality
var toggleSidebar = $(".togglesidebar");
var primary = $("#primary");
var secondary = $("#secondary");
toggleSidebar.on("click", function(){
if(primary.hasClass("col-sm-9")){
primary.removeClass("col-sm-9");
primary.addClass("col-sm-12");
secondary.css('display', 'none');
}
else {
primary.removeClass("col-sm-12");
primary.addClass("col-sm-9");
secondary.css('display', 'inline-block');
}
});
};
$(document).ready(ready);
Which works MOST of the time. There are times when the toggleSidebar doesn't toggle (e.g. when you go to a different page and come back to the main where the main button is...it doesn't toggle. I have to refresh the page before it starts working again...I suspect this is related to Turbolinks though)...but that's a side issue. That's not the core issue here.
I also have this:
counter = function() {
var body_value = $('#post_body').val();
var title_value = $('#post_title').val();
if (body_value.length == 0) {
$('#wordCountBody').html(0);
return;
}
if (title_value.length == 0) {
$('#wordCountTitle').html(0);
return;
}
var regex = /\s+/gi;
var wordCountBody = body_value.trim().replace(regex, ' ').split(' ').length;
var wordCountTitle = title_value.trim().replace(regex, ' ').split(' ').length;
$('#wordCountBody').html(wordCountBody);
$('#wordCountTitle').html(wordCountTitle);
};
$(document).on('ready page:load', function () {
$('#count').click(counter);
$('#post_body, #post_title').on('change keydown keypress keyup blur focus', counter);
});
Which doesn't work at all. In fact, whenever I put my cursor in the #post_title textfield in my JS console, I get this error:
Uncaught TypeError: Cannot read property 'length' of undefined
Which I suspect is related to the above.
What could be causing this?
Also, I am not sure if the order of these statements in my post.js file actually matters, I changed the order for the purposes of this question - so it is more clear.
However, in my actual post.js, the order is:
var ready;
ready function() declaration
counter function() declaration
$(document).ready(ready);
$(document).on('ready page:load', function () {
$('#count').click(counter);
$('#post_body, #post_title').on('change keydown keypress keyup blur focus', counter);
});
All of this feels wrong, I just don't know how to combine them and clean this up.
Thoughts?
Then, it is clear that body_value is undefined and that happens because $('#post_body').val() returns undefined and that can happen if #post_body doesn't exist or if it isn't a form object that has a .val() method. I think we'd have to see your HTML to advise further, but it appears that #post_body does not exist.

Office 365 on iPad - SP.SOD.executeFunc not executing function

I've written a function which is loading correctly (see the hokey alert at the top) which goes on to call SP.SOD.executeFunc to check if the device is an ipad then call SetFullScreenMode(true);
window.onload = function () {
alert('has loaded');
SP.SOD.executeFunc('sp.js', 'SP.ClientContext', goToFullScreen);
function goToFullScreen() {
alert('never gets called on an iPad'); // doesn't matter if isiPad is correct, this should at least happen
var isiPad = navigator.userAgent.indexOf('iPad') != -1;
if(isiPad) {
SetFullScreenMode(true);
}
}
};
It works just fine in Chrome and IE8 but doesn't work in iPad so executeFunc has any specific browser requirements. The "has loaded" message appears but nothing else executes.
Any suggestions?
Seems like the problem with the script not executing was my fault, I needed to prompt the script to notify pending functions. Not clear why this doesn't work on the iPad specifically, but there you go.
For info, the script that works is;
window.onload = function () {
SP.SOD.executeOrDelayUntilScriptLoaded(goToFullScreen, 'sp.js');
function goToFullScreen() {
var isiPad = navigator.userAgent.indexOf('iPad') != -1;
if(isiPad) {
SetFullScreenMode(true);
}
}
SP.SOD.notifyScriptLoadedAndExecuteWaitingJobs("sp.js");
};

Categories