Mr.Smithyyy
Mr.Smithyyy

Reputation: 1329

possible to change one variable or another inside of a function

I don't know if this is possible so I figured this would be the place to ask.

I have two inputs and they each hold a unique value. They each have their own respective variable that the value is saved into. I was wondering if there was a way to use just one function to update their values instead of two seperate ones. Below is my code so far.

<form>
    <input type="text" id="valueOne" onchange="changeValueOne(this.value)">
    <input type="text" id="valueTwo" onchange="changeValueTwo(this.value)">
</form>


var valueOne = parseFloat($('#valueOne'));
var valueTwo = parseFloat($('#valueTwo'));

function changeValueOne(newValueOne) {
    valueOne = newValueOne;
}
function changeValueTwo(newValueTwo) {
    valueTwo = newValueTwo;
}

Upvotes: 1

Views: 62

Answers (3)

dandavis
dandavis

Reputation: 16726

the simple expandable way uses a collection instead of vars:

<form>
    <input type="text" id="valueOne" onchange="changeValue(value, id)">  
    <input type="text" id="valueTwo" onchange="changeValue(value, id)">
</form>

<script>
var vals={ 
    valueOne : parseFloat($('#valueOne').val()),
    valueTwo : parseFloat($('#valueTwo').val())
};

function changeValue(newValue, slot) {
    vals[slot] = newValue;
}

</script>

not only is it incredibly simple and fast, this lets you add many options without reworking the forking code (ifs), all you need to do is modify the vals object and the handler will keep up automatically with all available options, even creating new ones on-the-fly if needed (from new inputs being appended during run-time).

Upvotes: 0

Maverick976
Maverick976

Reputation: 538

Try this:

var valueOne, valueTwo;

$("#valueOne, #valueTwo").change(function(){
    if($(this).attr('id') == 'valueOne') {
        valueOne = $(this).val();
    } else {
        valueTwo = $(this).val();
    }
});

Upvotes: 2

MinusFour
MinusFour

Reputation: 14423

You could have a second parameter to indicate which variable to store and/or where.

var values;
function changeValue(newValue, pos){
   values[pos] = newValue;
}

Change html to:

 <input type="text" id="valueOne" onchange="changeValue(this.value, 'first')">
 <input type="text" id="valueOne" onchange="changeValue(this.value, 'second')">

Alternatively if you want to store them in separate variables:

function changeValue(newValue, pos){
   if(pos == 'first'){
      valueOne = newValue;
   } else if(pos == 'second'){
      valueTwo = newValue;
   }
}

Upvotes: 0

Related Questions