Joshua Joshua - 1 year ago 80
Javascript Question

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');{
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;
} if(outpt == 'kiloGrams') {
var pKilo6 = num * 2.2;
} if(outpt == 'ounces') {
var pOunce6 = num * 16;
} if(outpt == 'milliGrams') {
var pMilo6 = num * 453592;

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



Answer Source

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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download