2

I am new to jQuery and JS. I have been wondering how to add a checkbox for each of the elements in the array aCurrencies, so I can be able to delete one or many of the elements in this array. My idea is to do this with the for loop I already have in the method below.

I made many unsuccessful attempts to code this, so any input will be highly appreciated.

function showHideCurrencies() {
    $("#lblCurrencies").empty();
    if (bShown == 0) {
        $("#btnShowHideCurrencies").text("HIDE CURRENCIES");
        bShown = 1;
        for (var i = 0; i < aCurrencies.length; i++) {
            $("#lblCurrencies").append("<div>" + aCurrencies[i] + "<i data-arrayIndex='" + i + "' class='fa fa-trash-o fa-fw'></i></div>")
        }
        $("#lblCurrencies").show();
    } else {
        $("#btnShowHideCurrencies").text("SHOW CURRENCIES");
        bShown = 0;
        $("#lblCurrencies").hide();
    }
}
4
  • Sorry but your question is not so much clear.. Do you mean you want to add checkboxes into your HTML via your foreach loop ? Commented Aug 26, 2016 at 8:44
  • I am sorry about that. Yes, this is what I mean. Of course, if there is a better option - I am open. Commented Aug 26, 2016 at 8:47
  • where you want to add into your this label => lblCurrencies ? Commented Aug 26, 2016 at 8:48
  • yes, in the very same label Commented Aug 26, 2016 at 8:50

1 Answer 1

1

I have prepared a demo code like below:

HTML:

<label id="lblCurrencies"></label>
<button id="btnShowHideCurrencies">

</button>

JQuery:

var bShown=0;
var aCurrencies=["first","second","third"];
showHideCurrencies();
function showHideCurrencies() {
    $("#lblCurrencies").empty();
    if (bShown == 0) {
        $("#btnShowHideCurrencies").text("HIDE CURRENCIES");
        bShown = 1;

        for (var i = 0; i < aCurrencies.length; i++) {
            $("#lblCurrencies").append("<div class>" + aCurrencies[i] + "<i data-arrayIndex='" + i + "' class='fa fa-trash-o fa-fw'></i><input type='checkbox' id='chk_"+i+"' /></div>")
        }
        $("#lblCurrencies").show();
    } else {
        $("#btnShowHideCurrencies").text("SHOW CURRENCIES");
        bShown = 0;
        $("#lblCurrencies").hide();
    }    

}

this code will add Checkboxes with Unique Id into your Label.

You can see demo on fiddle Click here.

Hope it helps you

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

Comments

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.