Home > front end >  How to change html href attribute variable value with jQuery?
How to change html href attribute variable value with jQuery?

Time:07-11

I am trying to change html href attribute variable value ?post=55 to ?post=44 with button click while not changing other URL variable(thread=7) using jQuery, but don't know how.

HTML

<button >button</button>

<a href="posts.php?thread=7&post=55" >Post</a>

JAVASCRIPT

$('.button').on('click', function() {

$("a").attr('href','posts.php?post=44') // this does not work because it removes ?thread=7
$("a").attr('href','posts.php?thread=7&post=44') // this also does not work because ?thread=7 is just a placeholder. I don't know what actual thread number is going to be.
  
});

This is what I have

<a href="posts.php?thread=7&post=55" >Post</a> 

This is what I want when clicking button

<a href="posts.php?thread=7&post=44" >Post</a>

CodePudding user response:

To do what you require you can provide a function to prop() (note: not attr()*) which accepts the current attribute value as an argument. From there you can use a regular expression to find the number within the current href and replace it.

The benefit of using this method is that it will work no matter where in the URL the post argument appears.

Also in the following example I stored the page value to set as a data attribute on the button, but this can be amended to suit your specific use case.

$('.button').on('click', function() {
  $('a').prop('href', (i, href) => href.replace(/(post=)\d{1,2}/, '$1'   $(this).data('page')));
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.0/jquery.min.js"></script>
<button  data-page="44">Update post to '44'</button>

<a href="posts.php?thread=7&post=55" >Post</a>

* See this answer for why you should use prop() over attr().

CodePudding user response:

$('.button').on('click', function() {
   // Get the href Value:
   const link = $("a").attr('href'); // posts.php?thread=7&post=44
   // Split the href value by '&' (returns Array):
   const parts = link.split('&'); // ['posts.php?thread=7','post=44']
   // Get the actual post value (may not needed?)
   const post = parts.slice(-1)[0]; // post=44
   // remove the 'post=44' part:
   parts.pop() // ['posts.php?thread=7']
   // Important if more than one "&" in URL:
   const linkBase = parts.join('&');
   // Build the new URL including YOUR Post number:
   const newUrl = linkBase   '&post=n';
   
   $("a").attr('href', newUrl)

// Sources:
// https://developer.mozilla.org/de/docs/Web/JavaScript/Reference/Global_Objects/String/split
  
});

Please note that this is an example that can be improved but its written with all necessary steps to better followup.

Hope it helps

  • Related