Search code examples
jquery-mobilepopuphref

Change href attribute pointing to popup id jquery Mobile


How can I use jquery to change the id of a div acting as a jquery mobile popup as well as the href of the anchor pointing to the popup?

In my webapp I have an anchor that, when clicked, brings up a jquery mobile popup div all of which I'm inserting dynamically. In any instance of the webapp, I don't know how many times this code will be inserted. Therefore, my understanding is that I need to be able to dynamically create a unique id for the jquery mobile popup div and set the href of my popup icon.

I am not currently succeeding at dynamically changing the id and href. I've created the following test (JSFiddle Test).

Here is my sample html:

<div class="phone1">
  <p class="textLeft"> <strong>Number: </strong><span>(555)555-5555</span>
    <a href="#myPopup" data-rel="popup" data-transition="pop" class="my-tooltip-btn ui-corner-all ui-btn ui-alt-icon ui-nodisc-icon ui-btn-inline ui-icon-info ui-btn-icon-notext ui-corner-all" title="Learn more">Learn more</a>
  </p>
    <div id="myPopup" data-role="popup" class="ui-content" data-theme="a" style="max-width:350px;">
      <p class="flagText">This number has been flagged as incorrect</p>
    </div>
</div>
<a href="#" class="ui-btn ui-btn-inline ui-btn ui-mini ui-corner-all ui-shadow" id="changeButton">Change href property</a>

Here is my sample javascript / jquery:

$('#changeButton').click(function () {
    alert("Handler for .click() called.");
    $('.phone1 > a').prop('href', 'myNewPopup');
    $('#myPopup').attr('id', 'myNewPopup');
});

Thank you for your help in advance!


Solution

  • As your anchor is not a direct child of .phone1 but rather a grandchild, the > selector does not work. Also the href needs the # symbol:

    $('.phone1 a').prop('href', '#myNewPopup');
    

    Technically you should also use prop to update the id as well:

    $('#myPopup').prop('id', 'myNewPopup');
    

    Updated FIDDLE

    Are you sure you need to do this. After dynamically inserting the popup the first time, you could just update it each successive time by testing if it exists in the DOM first:

    if ($("#myPopup").length > 0){
        //update
    } else {
        //create
    }