Joshua
Joshua

Reputation: 822

Why are different parts of my JQuery effecting other parts of my JQuery?

I am trying to finish my converter, and at one point I did have it working but now some of the code won't work. Like any conversion from LBS. I found out that unrelated parts of the code effect other parts, because I erased the essential parts of the code, and then pasted back in part by part to see where it messed up. For example when I put just the part of the code that converts LBS to other units, it works fine, as you can see in the examples below, but when I put the conversion for grams, it does not work. Why are different parts of my code effecting each other, just by being in the same click function?

var main = function() {
  var bttn = $('.sbs');
  bttn.click(function(){
    var rslt = $('#result');
    var num = $('#nmbr').val();
    var inpt = $('#slct1').val();
    var outpt = $('#slct2').val();

    //Converstion from pounds
    if(inpt == 'pounds'){
      if(outpt == 'grams') {
        var pGrams6 = num * 453.59;
        rslt.text(pGrams6);
      } if(outpt == 'kiloGrams') {
        var pKilo6 = num * 2.2;
        rslt.text(pKilo6);
      } if(outpt == 'ounces') {
        var pOunce6 = num * 16;
        rslt.text(pOunce6);
      } if(outpt == 'milliGrams') {
        var pMilo6 = num * 453592;
        rslt.text(pMilo6);
      }
    }

     //Conversion from grams
    if(inpt = 'grams') {
      if(outpt == 'pounds') {
        var pPound5 = num / 453.59;
        rslt.text(pPound5);
      } if(outpt == 'kiloGrams') {
        var pKilo5 = num / 1000;
        rslt.text(pKilo5);
      } if(outpt == 'ounces') {
        var pOunce5 = num * 28.35;
        rslt.text(pOunce5);
      } if(outpt == 'milliGrams') {
        var pMilo5 = num * 1000;
        rslt.text(pMilo5);
      }
    }
  });
}

$(document).ready(main);

FULL CODE: https://jsfiddle.net/qete67cz/

Upvotes: 0

Views: 18

Answers (1)

Pointy
Pointy

Reputation: 413866

This line is the problem:

if(inpt = 'grams') {

You want ==, not =. As it is, that if test will always be true because you're assigning a non-empty string.

In general, when you're testing something to see if its some value or some other value, you probably should use if ... else if instead of a simple sequence of if statements.

Upvotes: 2

Related Questions