0

Im making a jquery function, but im getting trouble with some variables. I cant get the value of #op1 to the input and in #z1 it shows "i" instead of "Start. Also the counter parameter doesnt add up. It only shows "0". In the click event it gets added up.

javascript code:

$(function() {

$(function () {
var inpreco = [];
var altpreco = [];
var cpcounter9 = 0;

$(".opcaopreco").click(function () {
    SuperF(this, "#preco", "inpreco", "altpreco", "cpvalor", "cpindex",
        "cpactive", "cpcounter9", "preco");
});

function SuperF(element, input, inpArray, secArray, inpValue, secIndex, 
inpActive,
    counter, msqlip) {

    var inpValue = $("#" + element.id).val();
    var secIndex = $("#" + element.id).data(secIndex);
    var inpActive = $("#" + element.id).data(inpActive);

    if (inpArray[0] == "") {
        counter++;
        $("#" + element.id + "l").addClass("activa");
        $(element).data(inpActive, "primary");
        inpArray[0] = (inpValue);
        input.val(inpArray[0]);
    }

    $("#z1").html(inpArray[0]);
    $("#z2").html(counter);
    $("#z3").html(cpcounter9);
};
});

});

html code:

<input id="preco" type="text" name="preco" value=''><br><br>

    <div id="op1l" class="input">
        <input type="checkbox" id="op1" class="opcaopreco" value="Start" data-cpindex="1" data-cpactivo="">
        <label for="op1"></label>
        <span class="itext">Test</span>
    </div>

    <ul id="z">
        <li id="z1">z1</li>         
        <li id="z2">z2</li>
        <li id="z3">z3</li>

    </ul>
0

1 Answer 1

1

You're passing in strings for your parameters, not elements. So when you index that parameter you're getting the first character in the string.

You need to use the strings as selectors to get their associated elements and then pass their return values into your function:

// use the strings to make a selection
var preco = $('#preco');
var inpreco = $('inpreco');
// etc.

// pass the results of each selection into your function
SuperF(this, preco, inpreco, ...)

You can do this inline as well:

SuperF(this, $("#preco"), $("inpreco"), ...)

Similarly, you have other variables you're trying to pass as strings, rather than passing them by name like this:

SuperF(this, $('#preco'), inpreco, altpreco, cpvalor, cpindex, cpactive, cpcounter9, preco);

That is the reason your function can't access most of the parameters and why your counter remains at 0.

Sign up to request clarification or add additional context in comments.

2 Comments

its more complicated than that. inpArray and secArray are arrays and i want to be able to name those arrays in the function. Besides, how do i solve the issue with the counter? it always return 0;
@Adato I've updated the answer again to explain that you need to pass variables, not strings with the names of variables, into your function.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.