Trying to call a function each time user changes the input...Values are not updating?

Trying to call a function each time user changes the input...Values are not updating?
0

#1

Hello… :slight_smile:

I’m trying to write a function which adds text to this element:

<p class="commission"></p>

The text will get a new value each time a user changes the value of this input:

<input type="number" step="any" min="0" name="listingPrice" id="listingPrice">

Here is the full code:

Explanation:

When a user types in a price , the commission should update accordingly. The price-ranges and commission-percentages are all stored in a JavaScript Object.

Problem:

The issue I’m facing is that the commission is not giving the proper values for most of the prices. If a user types 1000 in the input field, then the commission should be $35.00 (because the commission for values between 1000.00 to 1999.00 is 3.5%), but instead it shows $25.00

I am not sure if the if statements are causing this behaviour. Could you please explain to me what I’m doing wrong?


#2

Have you done the FCC curriculum? There are so many mistakes in the code: multiple identical calls to addFee, using an if statement instead of a switch (or even just an object lookup), not understanding pass by value vs pass by reference.

In addition, the rates object’s value-to fields ended in *99.00, instead of *99.99.

Your parameter names are non-informative (arg2, arg3) instead of (percentageFee, price).

Objects’ keys are always type-coerced into strings, but that’s because they are the LABELS. The VALUES don’t have to be strings, yet you are storing the prices as strings, forcing your inequality operators to compare the STRING version of the “userInput” variable (by lexicographic order).

I forked and fixed many of the problems with your code, but I still don’t understand why you’re calling the calculateRates() function 3 times for every time the user enters something. on Input is enough.

I left the console.log statements in the forked Pen so that you can learn how to label your log outputs so that you can read them. I also commented the code and renamed the variables, because it was a semantic mess.


#3

(Whew)

I read your fork very carefully, and realise the many (many) mistakes. Most are genuine mistakes (I would not have figured out, at my level, how to write it the way you did, without studying a lot further) and some were silly, like storing the numbers as strings.

Yes, I am in the process of the FCC curriculum, but I’m finding JS really tough as a beginner. I can pass the challenges after a lot of effort, but creating my own programs from scratch (like the pen) results in a semantic mess as you phrased it.

Thanks a lot for the corrections, I’ll make it a duty to figure out each line of code. I really appreciate it …:+1:


#4

You should take edX’s CS50. Sounds like you need an intro to comp sci class. It’s free, and if you want a certificate saying you did it, it only costs 90 bucks. Also, stop messing around with jQuery and learn vanilla javascript (after you learn how to write clean code). I didn’t mean to come off so harsh, but as I said, there were so many problems that I had the pen open in one window and the forum page in another, making notes as I decrypted what I read.

Oh, another style note I didn’t mention, but which matters: Notice how I structured your rates object in the editor: A well-placed newline makes things far more regular and human-readable. Also: Why do you have an rates[priceRange].id offset by one from rates[priceRange?] Are you trying to link this up to a database, or were you just making more work for yourself? I mean, you don’t even need the numbers at all - you could have on array of objects [{value_from: xxx, value_to: xxx, percentage:xxx}], and use the array’s index to iterate through the objects.


#5

A side note, and one I repeat a LOT, is the use of comments. I firmly believe that adding comments to your code can only help, for a number of reasons. I was just reviewing a js file I’d written up a couple weeks back for the calculator challenge – the js file is 191 lines, of which only 88 are actual code. The rest is comments (and empty lines).

First, if I comment the code with the intent behind that code, then when I write the code, I can compare what actually happens with what I expected. Often, I will write the entire program/function in commented ‘pseudo-code’, explaining the logic in plain english as completely as needed. Then, when I actually build the thing, I will leave the comments in place, either at the opening of the file, or as a line-by-line explanation. It helps me keep track of the logic, each step of the way.

Second, if someone is checking out your code later, they can see your logic. They can get a handle on what your variable names may mean, or what your expectations are, or if you are using some truly advanced and funky stuff, you can help them learn. I remember the first time I encountered a .map(..) that was commented beautifully, learned more from seeing the actual output AND the comments.

Third, sometimes I am on my ‘A game’. Not always. There are days I revisit my own code, and have to wonder “Exactly how drunk was I that night…?” It may make sense when I’m in the zone, but on my average day, I can confuse the heck out of myself. Thus, comments.

Also, as to the “stop messing around with jQuery”, it is a valid part of the FCC curriculum. It is very easy to over-rely on jQuery, as it is any library or framework. So I would agree that learning pure javascript is vital, but don’t throw the baby out with the bathwater. There are many companies who still embrace jQuery, and expect new hires to be intimately familiar with it. Until we can educate the masses, we’re kinda stuck with things being the way they are.

I do agree with the index comment, though – remember that arrays, by their nature, are indexed. element 0 in an array will remain element 0, unless you explicitly rearrange things. Objects are not that way, there is no guarantee that object properties will return in any given order, but arrays, and array indexes, are fundamentally linked.

And that calculator js page? Here’s the link, and it uses jQuery pretty extensively. Not because I needed to, I’d originally written it in pure JS, then in React, then in jQuery, simply to compare and contrast. But this one was heavily commented, as it was being used as a tutorial piece.


#6

Taking a look at your code, I wanted to tinker a little. I also made a few changes.

  • See my post below – I commented the BEJABBERS out of my edited one.
  • I changed the rates Object to a rates Array of Objects, thus allowing me to iterate over them. Made sense, as they were all the same thing, in terms of data shape.
  • I changed the addFee(), as the listingFee parameter doesn’t need to be passed in.
  • I also changed the parameter names from arg1, arg2 to originalValue, percentageRate – I find that names that MEAN something create self-commenting code.
  • I threw a curve-ball in the bit where you find the percentage rate. Where you have a huge set of if statements (which work, though they’re not pretty), I wondered if it would be easiest to simply filter the rates, keeping only the one with a value_from less than my input AND a value_to greater. This only happens for one member of the rates array, thus returning a single-element array.
  • I set the percentage rate with a conditional statement: if there IS a filtered row, then use that percentage rate. If not, simply use zero.
  • Also, with jQuery, you can string the events you’re listening for in a single event listener.

Sounds like a lot, but it’s pretty clear, with the comments in my code. YAAAY FOR COMMENTS!!! heh.

Here’s the working example, and here’s the script. Just for another perspective on the same question.


#7

We have all started where you are, don’t get discouraged.

Your code is not an uncommon sight among beginners, the code tends to be very imperative, over explicit, complicated and messy. You have not yet learned how to make the program do the work for you, so you basically end up doing the work for the program. It will get better, I’m not saying coding will be easy, just that with the right knowledge it ends up being more about logical problem solving, which is where the rubber really meets the road.

I will try to add some pointers to the list.

  1. Plan your attack.

  2. Break down the problem into small chunks.

  3. Test specific code in isolation, don’t pollute the test with side effects from other code.

  4. Manage state, the more you mutate state and have to keep track of side effects, the harder it gets to reason about the code. You end up doing bug fixing that is more like treating symptoms than curing the disease.

I’m guilty of sucking at both point 1 and 4 in my list. But, as they say, knowing is half the battle.

Here is another version, based on the code snowmonkey posted, i have removed Jquery and all the strings. I’m also only listening for the change event.


#8

@vipatron I don’t take it as coming off as harsh. I think it’s amazing that you could get to a level where you can correct someone’s code as if you were proofreading 4th grade English grammar, hahah ^.^

And thanks for the heads up. I def have a lot to learn…Trying to cramp so much into a tiny timeframe, but coding is a wonderful thing when you can control it.

Yes, I didn’t want to make the question unnecessarily elaborate, but the data is actually coming from a database (I’d like for it to remain in a database, and then use JavaScript as a middle-man to serve the content). It’s using PHP’s json_force_object to create a json file. I mistakenly inserted the numbers in the DB with quotes, but that’s corrected now.


#9

Wow, a whole different way of writing the same algorithm… Even tho I learnt about the methods/event-handlers you used (filter, on, etc) this gives new insight on how to apply them to various different algorithms.

I have this silly habit of starting out by using if-statements sets to solve any problem… maybe because it’s one of the first things we learn in programming, and personally I practised helluva lot before moving on to stuff like methods!

But looking at the different approaches used in the answers I received here, thank you, next time I start building a program I’ll go through each different JS method to see which can be applied to create most concise (yet beneficial) code… Make me believe if-statement sets do not exist

Great idea, that’s a really clever way to start out a program… I like the organized concept. Consider it stolen ^.^


#10

Consider it freely given. Looking forward to hearing how it goes.:grin: