Search code examples
javascripthtmlfrontendwml

How to dynamically make html element get its ID?


So I have something like this:

 <button id="select-settings-<var2 CardID>-{substrCardNumb(<var2 CardAccID>)}">

The function just returns the last digits of the given variable.

Obviously this doesn't work, but what im trying to do is dynamically generate an ID for different cards. The var2-s come from the server and currently I'm getting the full length for cardAccID, but I only want the last 4 digits to be in the ID of the html element.

How do I insert inline javascript functions into an id?


Solution

  • I found a solution that works for me. What I'm doing here is maping through all the elements that I know contain a button to which I want to add an ID. From those buttons I select the first button because that's the one I care about right now. I split the buttons current ID, which is "select-settings-randomnumbers". I get an array of 3 and I take the last element [2] and with substring() I get the last 4 digits of that element. I later replace the number at array[2] with the newly gotten 4 digits.

    jQuery(document).ready(function(){
     jQuery(".cards__content__card__list-item__actions").each(function(){
        let button = jQuery(this).find("button").eq(0)
        let splitId = button.attr("id").split("-")
        let cutId = splitId[2].substring(splitId[2].length -4)
        splitId[2] = cutId
        button.attr("id", splitId.join("-"))
     })
    

    })