Skip to content
Advertisement

Use function parameters as a variable call

what has already been described in the title, but basically I want to send a function perimeter and use it to call one of the three different variables. Also so it doesn’t come to a miss understanding the “$(‘#’+id)” part of the code works all I need is the correct syntax for the “id =” part (if even possible). And I know there is a workaround but I am trying to minimize code and this seems like the most optimal solution.

my code:

<div class="one">
    <p>ime:</p>
    <input type="text" id="name">
    <p>kraj:</p>
    <input type="text" id="city">
    <p>starost:</p>
    <input type="text" id="age">
    <p id="one_output"></p>
</div>
var name = "1";
var city = "2";
var age = "3";

function statement(id) {
    id = $('#'+id+'').val();
    $("#one_output").text("Sem " + name + " in živim v " + city + ". Star sem " + age);
};

$('.one input[type="text"]').keyup(function() {
    switch($(this).attr("id")) {
        case "name":
            statement(the_id);
            break;
        case "city":
            statement(the_id);
            break;
        case "age":
            statement(the_id);
            break;
    }
});

Advertisement

Answer

ok, I think I finally understood what you’re after

so you’re passing a variable name and want to dynamically call it, instead of going the global way using this, I would recommend to do it by having all your vars in just one global one, for example

var formInputs = { name: '1', city: '2', age: '3' }

and then you can easily read/write them with formInputs[ var_name_here ]

so your example, would be written as

var formInputs = { name: '1', city: '2', age: '3' }

function statement(name, val) {
    formInputs[name] = val
    var txt = `Sem ${formInputs.name} in živim v ${formInputs.city}. Star sem ${formInputs.age}`
    $("#one_output").text(txt)
}

$('.one input[type="text"]').keyup(function() {
    var elm = $(this)
    statement(elm.attr("id"), elm.val())
})

var formInputs = { name: '...', city: '...', age: '...' }

var statement = function(name, val) {
    formInputs[name] = val // assign value to variable
    var txt = `Sem <b>${formInputs.name}</b> in živim v <b>${formInputs.city}</b>. Star sem <b>${formInputs.age}</b>` // the new text
    $("#one_output").html(txt) // output
}

$('.one input[type="text"]').keyup(function() {
    var elm = $(this) // our key element
    statement(elm.attr("id"), elm.val()) // pass id and why not the value, so we dont need the element again
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="one">
    <p>ime: <input type="text" id="name"></p>
    <p>kraj: <input type="text" id="city"></p>
    <p>starost: <input type="text" id="age"></p>
    <p id="one_output"></p>
</div>
User contributions licensed under: CC BY-SA
7 People found this is helpful
Advertisement