need direction on how to update this code, language, tutorial? - javascript

I can usually Google and find my answer, but I have no idea with this issue on where to even start. If someone could point me in the right direction here as to what language and syntax is being used here, I'd appreciate it.
This is saying "if input1 = 'option1', then output text1 into span1 and if not, input text2.
I'm sorry this is so basic, but need to learn how to edit this but I'm lost without a tutorial or guide.
$('#span1').html(input1='option1'?'text1':'text2');
This is kind of a repost from an earlier question I had where I was accused of trying to get free coding advice so I've made this as basic as possible. I'm not looking for free coding here - if someone could give me a hint as to where I could find more information, I'd appreciate it.

This is a snippet of jQuery - a javascript framework.
$('#span1').html(input1='option1'?'text1':'text2');
$ This is the jQuery "object", and passing a selector argument to it will return a jQuery-wrapped object that you can chain methods to.
#span1 selector argument (may as well be CSS)
input1='option1'?'text1':'text2' Will output "text1" or "text2" depending on wether or not the variable option1 evaluates to true. It's very likely, as u_mulder points out, that this is going to fail. Use two == or three === for comparisons!
html(...) The html method chained onto the output of the selector accepts the new value to write to that element's contents in the DOM.
Suggested reading:
What is a jQuery Object?
Which equals operator (== vs ===) should be used in JavaScript comparisons?
http://api.jquery.com/html/
https://api.jquery.com/category/selectors/

Was able to do it not using that code but a code I'm more familiar with like this:
if(pay_type == 'onetime') {
$('#bank_card_pay_type').html('one time payment');
}
else if(pay_type == 'montly') {
$('#bank_card_pay_type').html('3 monthly payments');
}
else if(pay_type == 'monthly12') {
$('#bank_card_pay_type').html('12 monthly payments');
}

Related

How to interpret (document)0[]

I saw a code fragment like this:
with(document)0[(getElementsByTagName('head')[0] || body).appendChild(createElement(xxx))]
I don't know how to understand with(document)0[]
This is not valid JavaScript syntax and, trying to read around that, the semantics are extremely unclear.
I imagine the author meant something like this:
document.getElementsByTagName('head')[0] || document.body.appendChild(createElement(xxx))
"If there are any <head> tag in the document, return the first. Otherwise return the the result of appending createElement(xxx) to the body".
It is hard to answer this question without the full code. But I'll made some assumptions here.
The first thing that I'd like to say is to avoid of using with() statement. It is not recommended in ECMAScript 5 and is forbidden in strict mode. And one of the reasons is your fragment - this code confused a lot of people, even you.
So let's rewrite it a little bit to make it more understandable:
with(document) {
0[(getElementsByTagName('head')[0] || body).appendChild(createElement(xxx))];
}
How with works you can read here - with statement, but basically it is give us an ability to use directly all the properties and methods of the expression that we are sending to with (in our case it's a document).
So, how this code fragment will looks like without with?
0[(document.getElementsByTagName('head')[0] || document.body).appendChild(document.createElement(xxx))];
The only answer that I don't have is - why to execute this code inside of brackets? The assumption that I have is the following:
this code fragment (document.getElementsByTagName('head')[0] || document.body).appendChild(document.createElement(xxx)) will return the node of new created element. But if we place this code into the 0[], it will return undefined as there is no such property. Again, it's hard to understand all parts of this code fragment without the whole picture.

Breezejs Double trouble in angularjs

I am trying to change a value in a angular view from a integer to a float/double value that is bind to ngmodel. The input don’t except anything other than a integer.
My guess is that breeze does something in the background to validate the value or something on the "defined properties". But my knowledge of JavaScript prototyping is very limiting aka I need to learn it..
This is really hard to explain so I created a plunk that can hopefully help: http://plnkr.co/edit/Gcj0VvBE3f8DRbIjMtqt?p=preview
In the plunk I also added a normal object to test the same values and it is working as expected when changing the numbers to floats/doubles.
So the question is why won’t the value changed when binding to a float/double value from breeze?
I've checked a preliminary fix into GitHub for this. Please check it out and let me know if it works ( or not). We are still testing it.
This issue is caused by Angular's (new) behavior where if the angular digest cycle does not see a change to a model property then it seems to reset the UI to what it was on the previous digest cycle. So.. the idea behind this fix is to convince angular that the model value has changed even when it hasn’t.
and.. nice catch ( this was not obvious and your plunkr helped) :)
Ward adds: You must love the breeze team responsiveness :-) Jay jumped right on this and came up with an interesting solution. But please note the word "preliminary" in Jay's answer. We are discussing this "fix" internally and it may be withdrawn. Consider the zEquivalent directive in this new plunker or just wait until the dust settles.
Update 12 March
I found what I believe is a better solution for your use case because it does not involve "debouncing" nor any change to Breeze. See the zEquivalent directive in this new plunker
Reminder: the "best" resolution of the problem you discovered is still up in the air within the Breeze core team. You should not lock into a particular outcome until we can make a more definitive recommendation.
p.s.: I should have mentioned that Jay and I are on the Breeze core team. We are doing our best to get you out of a jam but sometimes we move a wee too quickly. Bear with us please.
This answer deprecated as of 12 March
Leaving it here for "historical" purposes.
I think you should try the zEquivalent directive first.
It is important to know that the Angular team is working on a robust extension to data binding that includes "debounce" which is still a good idea for many scenarios. See this (long) pull request thread on the Angular GitHub site.
Original Answer
Consider the zDebounce directive currently located in this plunker which is based on #qorsmond's second attempt.
I'd like to know your thoughts. I'm inclined to call this "the solution" and to add it to Breeze Labs. I'll update this answer when/if I do add it to the labs.
you can use input type="number" step="any" and hide the arrows using css
I tracked down the behaviour in the breeze code, when the value change it is intercepted and parsed:
var coerceToFloat = function (source, sourceTypeName) {
if (sourceTypeName === "string") {
var src = source.trim();
if (src === "") return null;
var val = parseFloat(src);
return isNaN(val) ? source : val;
}
return source;
};
So when the value change this function is called that parse the string to a float, the problem is as soon as the value entered is some number and a point like 5. it parse it to the number 5 witch is obviously correct. So you will never be able to get past the point.
When changing the input to a number type it works because its sourceTypeName is not a string.
Update
I ended up changing the breeze code to enable the decimal to be entered, I’m still not sure if I missed something but this works for me.
var coerceToFloat = function (source, sourceTypeName) {
if (sourceTypeName === "string") {
var src = source.trim();
if (src === "") return null;
var val;
if (src.indexOf('.', src.length - 1) !== -1) {
val = src;
}
else {
val = parseFloat(src);
}
return isNaN(val) ? source : val;
}
return source;
};
This doesn't work for large or small numbers that might be entered using an exponent form. If I want to enter 2.55e35 (a large salary ;)) the current implementation stops at the 'e'. Is there an easy way to fix this?

Object has no method 'charAt' in jQuery plugin

I am attempting to use the autoNumeric jQuery plug-in which helps with the conversion of various currencies in jQuery.
The plug-in itself works when I use it in a jsFiddle example.
$(function () {
$('.money').autoNumeric('init', {
aSign: '$',
vMin: '-999999999.99',
nBracket: '(,)'
});
});
However, as soon as I integrate it into a big, legacy project, I start receiving the above error on line 194. I know why I'm getting the error - a string is not being passed into the negativeBracket function (negativeBracket(s, nBracket, oEvent) is the signature). Instead, it seems to be a jQuery object - e.fn.init1. I'm confused on how this might be happening. I realize the community may not be able to give a direct answer, but I would love (and will accept as an answer) being pointed in the right direction as nothing has jumped out at me so far.
Update
So, have some additional info that may be of help. It still has me stumped how it's happening (unfortunately, the answers below didn't help to provide any additional insight). When I link in autoNumeric, I key it off of any text field with the class money. It does work as I am typing in the box. I can see see formatting. However, when I tab into a new box, the box I just finished typing in clears itself completely after hitting line 152 in autoNumeric with the same exact error.
#Carlos487 was correct in his answer when he said I have an object that is not a string. I instead have an object that, I believe, is a function. Here's what I'm seeing in Chrome debugger tools:
e.fn.init[1]
> 0: input#price.money required
> context: input#price.money required
length: 1
selector: ""
> __proto__: Object[0]
The "arrowed" items can be further expanded out. I don't know if this provides any more clues, but it's at least something a bit different.
The errors like
no method XXXXX in Object
are produced because you are trying to call obj.XXXX() and obj is not of the desired type, in your particular case a string.
Have you tried in another browser because older or IE can be a little troublesome. I would recomend using chrome developer tools with your legacy app to see if anything else is conflicting or producing the error
I will bet money that you are using a second library which is interfering with jQuery. It has probably overridden $ with its own function.
Try using jQuery instead of $:
jQuery(function () {
jQuery('.money').autoNumeric('init', {
aSign: '$',
vMin: '-999999999.99',
nBracket: '(,)'
});
});
It turns out that the issue was a myriad of issue compounding into the error I saw. A couple things that was happening:
The validator plug-in was wrapping the jQuery object in its own structure (hence the charAt issue).
Once I fixed that, I also learned that some homegrown code was also wiping and rewriting data into the field to provide formatting (which is what autoNumeric is also doing), so autoNumeric would bomb out because it would get a null value and attempt to format it.
There was some other random craziness that also needed cleaned up. So...issue resolved! Still more to work on, but at least this hurdle is past. Thanks all for your help.

Please explain this usage of a colon in javascript

I'm making a library, and I often inspect the result of Closure Compiler's output to see how it's doing things (I do have unit tests, but I still like to see the compiled code for hints of how it could compress better).
So, I found this very weird piece of code, which I never seen before.
variable : {
some();
code()
}
Note: this is not an object literal! Also, there is no ? anywhere that would make it a ?: conditional.
That code is in a regular function block (an IIFE).
variable, in this case, is an undefined variable. There's no code making it true, false, or whatever, and just to make sure, I put a console.log in there and indeed, I get a ReferenceError.
Please do note that I test my code in IE8 too, so this isn't just in modern browsers. It seems to be standard, plain old javascript.
So let's experiment with it. Firing up Chrome's console, I get this:
undeclaredVariable:{console.log('does this get logged?')} // yes it does.
trueValue:{console.log('what about this?')} // same thing.
falseValue:{console.log('and this?')} // same thing.
but then...
(true):{console.log('does this work too?')} // SyntaxError: Unexpected token :
...and...
so?{console.log('is this a conditional?')}:{alert(123)} // Unexpected token .
So what does it do?
thisThing:{console.log('is used to declare a variable?')}
thisThing // ReferenceError: thisThing is not defined
Please, I'd love it if someone could explain to me what this code is meant to do, or at least what it does.
It is a label
Provides a statement with an identifier that you can refer to using a
break or continue statement.
For example, you can use a label to identify a loop, and then use the
break or continue statements to indicate whether a program should
interrupt the loop or continue its execution.
Another common place you see it is when people stick the wonderful and useless javascript: on event handlers.
This is a label (the bit ending with a colon) followed by a block (the code surrounded by the curly brackets).
Blocks usually follow control statements, like if(...) { /*block*/ }, but they can also simply stand on their own, as in your example.
Labels allow jumping up several loops at a time with a continue or break; see the linked MDN page for several examples, such as:
var itemsPassed = 0;
var i, j;
top:
for (i = 0; i < items.length; i++){
for (j = 0; j < tests.length; j++)
if (!tests[j].pass(items[i]))
continue top;
itemsPassed++;
}
Here, top: is a label that code inside the inner loop can jump to, in order to escape to the outer loop.
For the sake of anyone who doesn't know what JSON is, and sees a colon in what might actually be an object, and is trying to figure out what it is, and finds this discussion, a colon is also used in JSON. There is a practice of embedding functions in a JSON object. Which might be confusing (As it was to me) for anyone who happens to see this for the first time. (Everyone isn't born with the knowledge of JSON and JavaScript programmed into their brains.) So if you find yourself at this discussion, and you think that every time you see a colon in JavaScript, that it's a label, it might not be. It might be that it's a colon after a label, OR it might be part of JSON. In fact, a colon in JSON being shown as a string, is a lot more common than a label. JSON in the form of an object, will be displayed as [object Object], with all the content hidden. So, unless the JSON is in the form of a string, and you display an object to the console (console.log(object)) all you will see is [object Object]. It is common practice to write JavaScript code, wrapped in an object. In that case you will see the JSON in the form of code. That's when you'll ask yourself, "What is this? and what is that colon for?" Then you'll find yourself at this discussion, and be told that it's a label, when it's really part of JSON. The topic of this discussion is worded: "Please explain this usage of a colon in javascript", and then the "correct answer" is marked as having to do with a label. The correct answer is that a colon can be used in more than one way. So, if you don't know what JSON is, or think you know (like I did, but didn't really understand) read about it here:
JSON.org
That is just a label.
you can use continue [label name] (or break) in a loop to go to a label.
More explanations of what they are can be seen throughout the interwebs.
it is used for labeling an statement in jsvascript.check more detail here.
the labeled statement can be used with break and continue later.

Javascript xPath [#StoreName]?

I'm doing some research for a project that I have going on the uses the document.createTreeWalker and I'm looking at a script that uses quite a few xpath's, but I'm curious as to where these come from. Some are obvious and I have been able to find answers to online, such as [#AttributeName] and [#TagName], but what is [#StoreName], [#AttributeValue1], [#AttributeValue2]...these I have not been able to look up online.
Particularly, I'm looking at these lines and not understanding:
thisURL = window.document.location.href.toString();
if(thisURL.search("[#StoreName]") != -1) { //do something }
Perhaps I'm misunderstanding your question, but there's nothing functionally or syntactically different between [#AttributeName] and [#StoreName]. They're both predicates that are looking for elements with particular attributes. The first one is looking for AttributeName attributes, while the second is looking for StoreName attributes.
That said, the code you're showing isn't actually doing any XPath work. It's just looking at whether the URL contains the character sequence [#StoreName] using JavaScript's string search function, and doing something if it does.

Categories

Resources