0

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?

  • You can generate HTML strings in your JavaScript code and then add them in DOM using `element.innerHTML` API. https://developer.mozilla.org/en-US/docs/Web/API/Element/innerHTML – im_tsm Jul 06 '22 at 07:38
  • Can't you use PHP for this? – T.Trassoudaine Jul 06 '22 at 07:52
  • no, our stack is javascript and jquery –  Jul 06 '22 at 08:00
  • @im_tsm innerhtml adds html texts yes, but I'm trying to set the ID. I tried element.id += substrCardNumb(.....), but It doesn't seem to work –  Jul 06 '22 at 09:49
  • @neuromancer can you provide a bit more code? – im_tsm Jul 06 '22 at 13:43
  • Taking a step back: why do you need an ID? Wouldn't it be possible for you to keep object references rather than IDs to refer to your DOM objects? I _know_ you have those references; otherwise you would be unable to assign those IDs to begin with. – Ruud Helderman Jul 06 '22 at 14:51

1 Answers1

0

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("-"))
 })

})

  • Your answer could be improved with additional supporting information. Please [edit] to add further details, such as citations or documentation, so that others can confirm that your answer is correct. You can find more information on how to write good answers [in the help center](/help/how-to-answer). – Community Jul 06 '22 at 18:30