Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Jquery conditional statement

I'm really sorry if this come across as stupid but i've searched everywhere but i didn't find any tip on how to go about it. i have this variable

 var id = $('#sometextfield').val(); 

This text field value is dynamically generated eg.

 <input type="text" name="id" id="id" value="<?php echo $_get[something];?>" />)

The problem here is that i have an if condition saying

if(id == 100 || id ==120) {
   // i have these variables
   var mulitiplier = 0.005
   var price = (some alog) * mulitiplier;

   // do some very long piece of code
}
else if (id == 200 || id == 220) {
   // Then i have these variables
   var mulitiplier = 0.090;
   var price = (some alog) * mulitiplier;
   // Do the same very long piece of code(its practically the same thing as 
   // the first if statement and the only change is the ariable multiplier)        
}

This works and all but is there any way to not repeat the same thing. I don't like the look of it atm. Many thanks in advance..


2 Answers

function long_piece(multiplier){
    ... long piece of code....
}
var MultMap = {100:0.005, 120:0.005, 200:0.009, 220:0.009}

long_piece(MultMap[id])
like image 57
spicavigo Avatar answered Apr 16 '26 05:04

spicavigo


Just abstract out the very long piece of code to a function which takes the multiplier and price values as parameters. For example

var theCode = function (multiplier, price) {
  do some very long piece of code
};

if(id == 100 || id == 120) {
  var mulitiplier = 0.005
  var price = (some alog) * mulitiplier;
  theCode(multiplier, price);
} else if (id == 200 || id == 220) {
  var mulitiplier = 0.090;
  var price = (some alog) * mulitiplier;
  theCode(multpilier, price);
}

Note: You should consider using parseInt in the initialization of id and === for comparing values instead of == for this type of code.

like image 33
JaredPar Avatar answered Apr 16 '26 04:04

JaredPar



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!