Change part of url when option is selected

Viewed 53

We use a select field and need the option value inside a url and need to replace a part of the current url. Because some part of the url is dynamic with a formkey, we need to remove everything form the "/product" part. How can we achieve this?

My my current code does not work, because it removes everything and I want to keep the url and only replace everything from the /product part.

HTML:

<select class="id" id="storage">
  <option value="210234">option 1</option>
  <option value="210345">option 2</option>
  <option value="210678">option 3</option>
</select>

<form action="https://example.com/add/uenc/Y3Jvbmlz/product/210145/"> 

</form>

Current jQuery:

$(document).ready(function(){
        $("select.id").change(function(){
            var selectedid  = $(".id option:selected").val();
            $("form").attr("action","/product/"+selectedid); 
        });
    });
2 Answers

I suggest you to rebuild the newurl:

here i am using regex expression:

$(document).ready(function() {
  $("select.id").change(function() {
    var selectedid = $(".id option:selected").val();
    var newurl = $("form").attr("action").replace(/\/product.+$/, "/product/" + selectedid);
    $("form").attr("action", newurl);
    console.log($("form").attr("action"));
  });
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<select class="id" id="storage">
  <option value="210234">option 1</option>
  <option value="210345">option 2</option>
  <option value="210678">option 3</option>
</select>

<form action="https://example.com/add/uenc/Y3Jvbmlz/product/210145/">

</form>

First you have to get the action value and then you can operate with substring() and indexOf() to cut the desired part:

Working example:

$(document).ready(function() {
  $("select.id").change(function() {
    var selectedid = $(".id option:selected").val();
    var action_string = $("form").attr("action");
    var new_action = action_string.substring(0, action_string.indexOf('product/') + 8) + selectedid + '/';
    $("form").attr("action", new_action);

    console.log($("form").attr("action"));
  });
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<select class="id" id="storage">
  <option value="210234">option 1</option>
  <option value="210345">option 2</option>
  <option value="210678">option 3</option>
</select>

<form action="https://example.com/add/uenc/Y3Jvbmlz/product/210145/">

</form>

Related