user3386779
user3386779

Reputation: 7185

Change the querystring using RegEx

I want to replace the part of the given URL using button click.When I click play button need change autoplay=0 to autoplay=1 and When I click close button need change autoplay=1 to autoplay=0

jQuery(document).ready(function($) {
  $('.playButton').click(function() {
    alert('play');
    $("iframe").src = src.replace(/\&autoplay\=\d/, "&autoplay=" + 1);
  });

  $(".close_icon").click(function() {
    alert('close');
    $("iframe").src = src.replace(/\&autoplay\=\d/, "&autoplay=" + 0);
  });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<iframe src="https://www.youtube.com/embed/C0DPdy98e4c?width=640&autoplay=1"></iframe>
<div class="playButton">Play</div>
<div class="close_icon">Close</div>

Upvotes: 0

Views: 53

Answers (2)

Tushar
Tushar

Reputation: 87203

You don't need RegEx for this. String replacement can be done.

$("iframe").src will not set the value of src attribute of iframe. Use attr() to change the attribute of an element.

jQuery(document).ready(function($) {
  $('.playButton').click(function() {
    $("iframe").attr('src', function(i, oldSrc) {
      if (oldSrc.indexOf('autoplay') === -1) {
        // If autoplay is not on URL, add it
        oldSrc += '&autoplay=1';
      }

      return oldSrc.replace('autoplay=0', 'autoplay=1');
    });
  });

  $(".close_icon").click(function() {
    $("iframe").attr('src', function(i, oldSrc) {
      return oldSrc.replace('autoplay=1', 'autoplay=0');
    });
  });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<iframe src="https://www.youtube.com/embed/C0DPdy98e4c?width=640"></iframe>
<div class="playButton">Play</div>
<div class="close_icon">Close</div>


The code can be DRY'd as follow

jQuery(document).ready(function($) {
    // To update the value of autoplay in the URL of iframe src attribute
    var changeAutoplay = function(newValue) {
        $('iframe').attr('src', function(i, oldSrc) {
            return oldSrc.replace(/autoplay=\d/, 'autoplay=' + newValue);
        });
    };

    $('.playButton').click(function() {
        changeAutoplay(1);
    });

    $(".close_icon").click(function() {
        changeAutoplay(0);
    });
});

Upvotes: 2

Bud Damyanov
Bud Damyanov

Reputation: 31889

As you can see, there is an error from the console Uncaught ReferenceError: src is not defined, which means that you try to use non-existent property, try with:

$("iframe").attr("src", function(index, value){ return value.replace("autoplay=0", "autoplay=1") })

Read more about attr method here.

Upvotes: 1

Related Questions