str.split() inside $(document).ready() does not work? - javascript

http://jsfiddle.net/MQHkA/2/
$(document).ready(function() {
var mystring="fusioncharts,om,bdutt";
var arr = mystring.split(','); //array returned
for(var i = 0; i < arr.length; i++) {
alert(arr[i]);
}
}
Would the above code work ?
EDIT---
Well the real code block is this :
handle1 = getUrlVars();
if(handle1 == '') {
$("input#handle1").val('barackobama');
$("input#handle2").val('aplusk');
$("input#handle3").val('charliesheen');
handle1 = 'barackobama,aplusk,charliesheen';
} else {
alert(handle1); // this says fusioncharts,om,bdutt
var queryvals = [];
queryvals = handle1.split(',');
alert('length'+queryvals.length); // *** this says nothing ***
for(var i = 0; i < queryvals.length; i++) {
alert(queryvals[i]); // *** nothing here too.. ****
}
}
And the entire block is in a $(document).ready()...
Must be some simple error which I'm unable to spot..

you are missing the closing parentheses other than that it works fine
$(document).ready(function() {
var mystring="fusioncharts,om,bdutt";
var arr = mystring.split(','); //array returned
for(var i = 0; i < arr.length; i++) {
alert(arr[i]);
}
}); // this one is missing on yours

Yes, but you have to close off your example with
);
http://jsfiddle.net/gMU9t/

You forgot to close your parentheses and already have sounded the alarm. Debug your code before asking. Javascript functions work fine. You need to be more attentive.

Related

For loop is being escaped due to use of .parentNode

When I delete parentNode from the code below, the forloop is not escaped. Any thoughts as to why parentNode is doing this?
Edit: I've corrected the syntax noted in the comments.
for (var i=0; i < itemlist.length; i++) {
var newprice = basepricearray[i]*multiplier;
var newprice2 = Number(newprice).toFixed(2);
var wrapper = itemlist[i].parentElement;
if (basepricearray[i] == "0.00") {
wrapper.classList.remove("hidepricing100");
var costbox = itemlist[i].parentNode;
costbox.innerText = "Free";
}
}
Thank you!

How to create a function to be re-used for later within another function

I got this code:
$(document).ready(function(){
$(".nextForm").on('click',(function(){
//check criteria
if(selectedSlots.length < 1 ||$("#positionAppliedFor").get(0).value.length < 1 ||$("#maxAmountOfHours").get(0).value.length < 1){
//error messages and array
var errorForSlots= "<h5>Select at least one availability slot</h5>";
var errorForPosition = "<h5>Enter the position you wish to apply for<h5>";
var errorForHours = "<h5>Enter the amount of hours you would like to work<h5>";
var errors = [];
//add errors to array
if(selectedSlots.length < 1){errors.push(errorForSlots)};
if($("#positionAppliedFor").get(0).value.length < 1){errors.push(errorForPosition)};
if($("#maxAmountOfHours").get(0).value.length < 1){errors.push(errorForHours)};
//create message
var div = "<div id=\"sectionError\">";
if($("#sectionError").length > 0){$("#sectionError").html('')};
$(div).appendTo($(this).get(0).parentNode);
for(var i = 0; i < errors.length; i++){
$(errors[i]).appendTo($("#sectionError"));
console.log(errors[i]);}
$("</div>").appendTo($(this).get(0).parentNode);
} else {
$("#applicationDetails").slideUp();
$("#personalDetails").slideDown();
if($("#sectionError").length > 0){$("#sectionError").remove()};
}
console.log("function finished");
}));
It all works perfectly, however, I am trying to figure out how to create a function for
//create message
var div = "<div id=\"sectionError\">";
if($("#sectionError").length > 0){$("#sectionError").html('')};
$(div).appendTo($(this).get(0).parentNode);
for(var i = 0; i < errors.length; i++){
$(errors[i]).appendTo($("#sectionError"));
console.log(errors[i]);}
$("</div>").appendTo($(this).get(0).parentNode);
I am planning to re-use this for few other sections on my form and rather than copy/paste I would like to get some help on making my code tidier.
I did try:
function myFunction(){
//message code here
}
$(document).ready(function(){
$(".nextForm").on('click',(function(){
//check criteria
...
//add errors
...
//call func
myFunction();
(I also tried this.myFunction();)
...
}));
});
However, that ended up in TypeError and I don't know where to begin...
I am also concerned about the "this" in my message code so I am also not sure how to address that in my new function...
Admitedly I am a newbie at this and I do not exactly understand all the ins and outs, hopefully you will be able to help.
Maybe there is a better way of doing this?
Let me know your thought either way!
Thanks.
I have created a small reusable framework same as how jQuery is doing behind the scene to expose reusable functions. I didn't tested the append function properly,I just explaining how you can create your own reusable plugin to reuse across the project.
You can change the parameters and method name that you want to expose based on your functionality.
Also I would suggest you to move this code to a javascript file as a plugin and drag after the jquery script.
(function (global, $) {
//you can pass the jQuery object in to this IIFE
var DisplayError = function (elementId) {
return new DisplayError.init(elementId);
}
DisplayError.prototype = {
appendError: function (errors) {
var div = "<div id=\"" + this.elementId + " \">";
if ($(this.elementId).length > 0) {
$(this.elementId).html('')
};
$(div).appendTo($(this.elementId).get(0).parentNode);
for (var i = 0; i < errors.length; i++) {
$(errors[i]).appendTo($(this.elementId));
}
$("</div>").appendTo($(this.elementId).get(0).parentNode);
}
};
DisplayError.init = function (elementId) {
var self = this;
self.elementId = elementId;
}
DisplayError.init.prototype = DisplayError.prototype;
global.DisplayError = global.DisplayError = DisplayError;
}(window, jQuery));
You can write the code for clear the html directly in init function to ensure the element is clearing while initialize the instance itself.
You can invoke the method like below ,
var displayError=DisplayError("#sectionError")
displayError.appendError(["errorId"])
or
DisplayError("#sectionError").appendError(["errorId"])
Hope this helps
New Function
function generateMessage(arg1) {
//create message for each section
console.log("generating message");
var div = "<div id=\"sectionError\">";
if ($("#sectionError").length > 0) {
$("#sectionError").html('')
}
;$(div).appendTo($(arg1).parent());
for (var i = 0; i < errors.length; i++) {
$(errors[i]).appendTo($("#sectionError"));
console.log(errors[i]);
}
$("</div>").appendTo($(arg1).parent());
}
Changed old function
$(document).ready(function() {
$("#adbutnext").on('click', (function() {
//check criteria
if (selectedSlots.length < 1 || $("#positionAppliedFor").get(0).value.length < 1 || $("#maxAmountOfHours").get(0).value.length < 1) {
//error messages and array
var errorForSlots = "<h5>Select at least one availability slot</h5>";
var errorForPosition = "<h5>Enter the position you wish to apply for<h5>";
var errorForHours = "<h5>Enter the amount of hours you would like to work<h5>";
errors = [];
//add errors to array
if (selectedSlots.length < 1) {
errors.push(errorForSlots)
}
;if ($("#positionAppliedFor").get(0).value.length < 1) {
errors.push(errorForPosition)
}
;if ($("#maxAmountOfHours").get(0).value.length < 1) {
errors.push(errorForHours)
}
;
generateMessage(this);
} else {
$("#applicationDetails").slideUp();
$("#personalDetails").slideDown();
if ($("#sectionError").length > 0) {
$("#sectionError").remove()
}
;
}
console.log("function finished");
}
));
});

How can I get the text to which a Nested Style is applied in InDesign

I am trying to write a script that will convert all characters to lowercase if a particular nested style is applied. I can't seem to figure out the correct syntax to get the text.
I originally tried the following, which worked to an extend, but lowercased the entire paragraph rather than only the text that has the character style applied:
function lowerCaseNest(myPStyle, myCStyle){
var myDocument = app.documents.item(0);
//Clear the find/change preferences.
app.findTextPreferences = NothingEnum.nothing;
app.changeTextPreferences = NothingEnum.nothing;
//Set the find options.
app.findChangeTextOptions.caseSensitive = false;
app.findChangeTextOptions.includeFootnotes = false;
app.findChangeTextOptions.includeHiddenLayers = false;
app.findChangeTextOptions.includeLockedLayersForFind = false;
app.findChangeTextOptions.includeLockedStoriesForFind = false;
app.findChangeTextOptions.includeMasterPages = false;
app.findChangeTextOptions.wholeWord = false;
app.findTextPreferences.appliedParagraphStyle = myPStyle;
var missingFind = app.activeDocument.findText();
var myDoc = app.documents[0];
for ( var listIndex = 0 ; listIndex < missingFind.length; listIndex++ ) {
for (i = missingFind[listIndex].nestedStyles.length-1;i>=0; i--) {
for (j = missingFind[listIndex].nestedStyles[i].parent.characters.length-1;j>=0; j--) {
if (missingFind[listIndex].nestedStyles[i].parent.characters[j].contents.appliedCharacterStyle(myCStyle)) {
var myString = missingFind[listIndex].nestedStyles[i].parent.characters[j].contents;
if (typeof(myString) == "string"){
var myNewString = myString.toLowerCase();
missingFind[listIndex].nestedStyles[i].parent.characters[j].contents = myNewString;
}
}
}
}
app.findTextPreferences = NothingEnum.nothing;
app.changeTextPreferences = NothingEnum.nothing;
}
I then tried playing around with appliedNestedStyles, but can't seem to figure out how to retrieve the text that the nested style is applied to.
Could anyone help with this?
Thanks!
John
Unless I am wrong the appliedNestedStyle can be looked after in the F/C dialog by targeting the applied characterStyle:
GREP
Find : .+
Format : character style => myCharStyle
then
var found = doc.findGrep();
…
I actually took a different tack, and figured out something that works:
function lowerCaseNest(myPStyle, myCStyle){
for (var i = 0; i < app.activeDocument.stories.length; i++){
for (var j = 0; j < app.activeDocument.stories[i].paragraphs.length; j++){
var myP = app.activeDocument.stories[i].paragraphs[j];
if (myP.appliedParagraphStyle.name==myPStyle) {
for (k=0; k<myP.characters.length; k++) {
if(typeof(myP.characters[k].appliedNestedStyles[0]) != 'undefined'){
if(myP.characters[k].appliedNestedStyles[0].name == myCStyle) {
var myC = myP.characters[k].contents;
if (typeof(myC)=='string'){
var myNewString = myC.toLowerCase();
myP.characters[k].contents = myNewString;
}
}
}
}
}
}
}
}
Still would be interested in knowing if there's an easier way to handle this, as I'm afraid this may take longer to run on long documents, since it's dealing with every paragraph individually.

Console.log not working within my function

So I'm trying to test my code out by applying a console.log in different parts of it. But when I try it in a certain function, it doesn't work. I've tried putting alerts within that function as well to see whether its just a problem with console.log, but alerts don't seem to run either.
Here's my code
var mqrule;
var lines;
var width;
console.log("Nothing");
//HASHMAP BEGINNING HERE
var newKey, newValue;
var MQHash = {};
MQHash[newKey] = newValue;
(function () {
console.log("Nothing");
//FROM HERE, CONSOLE.LOG DOESN'T SEEM TO BE WORKING.
var mqEvents = function (mediaChangeHandler) {
var sheets = document.styleSheets,
numSheets = sheets.length,
mqls = {},
mediaChange = function (mql) {
console.log(mql);
}
if (mediaChangeHandler) {
mediaChange = mediaChangeHandler;
}
for (var i = 0; i < numSheets; i += 1) {
var rules = sheets[i].cssRules,
numRules = rules.length;
console.log("RULES: " + rules);
for (var j = 0; j < numRules; j += 1) {
if (rules[j].constructor === CSSMediaRule) {
mqrule = rules[j].cssText;
console.log(mqrule);
lines = (mqrule).split('\n');
console.log(lines[1]);
mqls['mql' + j] = window.matchMedia(rules[j].media.mediaText);
mqls['mql' + j].addListener(mediaChange);
mediaChange(mqls['mql' + j]);
}
}
}
}
//IT STARTS TO WORK AGAIN FROM HERE THOUGH.
window.mqEvents = mqEvents;
}());
handleMediaChange = function (mql) {
console.log();
var medias = mql.media;
}
Any Suggestions? Thanks in advance. Sorry if this question isn't worded properly!
OK I've figured it out thanks to you guys! I needed to call the function, which I so stupidly had forgotten to do, so I had added;
mqEvents(handleMediaChange);
at the bottom to call mqEvents.
Thanks all!

Javascript doesn't work when have another one

I searched but I didn't find the answer.
I have a code that change the color of my wordpress template blocks and posts randomly. Actually it changes the classes of these blocks and so the colors. You can see the code here:
function inArray(array , exist) {
var rslt = false;
for (var j = 0; j < array.length; j++)
{
if (array[j] == exist)
{
rslt = true;
}
}
return rslt;
}
var colored = Array();
function changeColor(target) {
var blocks = document.getElementsByClassName(target);
var blockLength = blocks.length;
for (var i = 0; i < blockLength; i++)
{
if (colored.length >= 9)
{
colored = [];
}
var rand = 0;
while (rand == 0 || inArray(colored , rand))
{
rand = Math.floor(Math.random()*10)%10;
}
colored.push(rand);
blocks[i].className = target+' color'+rand ;
}
}
window.onload = function() {
changeColor('block');
changeColor('post');
}
the code you seen placed in an external file named 'colors.js' and included by:
<script src="<?php bloginfo('template_url'); ?>/scripts/colors.js"></script>
in my wordpress template.
the code works correctly til I add another code like this:
<script>var _mxvtmw_position = 'left', _mxvtmw_domain = 'icomp.ir'</script>
<script src="http://iwfcdn.iranwebfestival.com/js/mx.vtmw.min.js?12688" async="async"></script>
Why? And how can i fix this problem?
Thank you.
EDIT:
DEMO: http://tuts.icomp.ir/
IN CASE blocks.length IS 1 YOU HAVE TO ADD ONE MORE IF CONDITION
if (blocks.length==undefined){
//code
}

Categories

Resources