using getElementById within popup opened by magnificPopup fails when trying access popup element

809 Views Asked by At

Using getElementById fails, cause it tries to find the element with id "in" in the father HTML. How to get content of input element "id" from within the popup?

<html>
<head>
    <link media="all" type="text/css" rel="stylesheet" href="//cdnjs.cloudflare.com/ajax/libs/magnific-popup.js/0.9.9/magnific-popup.css">
    <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
        <script src="//cdnjs.cloudflare.com/ajax/libs/magnific-popup.js/0.9.9/jquery.magnific-popup.min.js"></script>
</head>
<body>
    <button id="someid">Open popup</button>

<script>
    $('#someid').magnificPopup({
                                          items: {
                                              src:  
                                                    '<div class="white-popup"><br>\
                                                    <input id="in" type="text" placeholder="content">\
                                                    <a href=document.getElementById('in')>Click</a>',

                                              type: 'inline'
                                          }
                           });  
</script>
</body>
</html>
1

There are 1 best solutions below

1
On BEST ANSWER

You can use event delegation, like this

1

$('#someid').magnificPopup({
  items: {
    src: [
        '<div class="white-popup"><br>',
        '<input id="in" type="text" placeholder="content">',
        '<a href="#">Click</a></div>'
    ].join(),
    
    type: 'inline'
  }
});

$('body').on('click', '.white-popup > a', function () {
  alert($(this).siblings('#in').val());
})

Demo: http://jsbin.com/votam/1/

2 or

$('#someid').magnificPopup({
  items: {
    src: [
        '<div class="white-popup"><br>',
        '<input id="in" type="text" placeholder="content">',
        '<a href="javascript:alert(document.getElementById(\'in\').value);">Click</a></div>'
    ].join(),
    
    type: 'inline'
  }
});

DEMO: http://jsbin.com/votam/2/

3

$('#someid').magnificPopup({
  items: {
    src: [
        '<div class="white-popup"><br>',
        '<input id="in" type="text" placeholder="content">',
        '<a href="url?arg1=\'arg1\'&arg2=" onclick="this.href = this.href + document.getElementById(\'in\').value ">Click</a></div>'
    ].join(),
    
    type: 'inline'
  }
});

Demo: http://jsbin.com/votam/3/edit