1

How can I change the value of a select list with the value of another select list

<select class="main-filter" id="Test1" name="Test1"><option value="">Select Option</option>
<option value="1">One</option>
<option value="2">Two</option>
</select>

Need to replace #ReplaceThisText# with value selected from above select box

<select id="selectfilter" name="selectfilter" class="form-control main-filter">
                        <option value="">Sort Products</option>
                        <option value="/?id=na&amp;selectfilter=hl&amp;Type=#ReplaceThisText#">Chnage Value</option>

                    </select>

I have tried code from this link Change the Text of a Option with jQuery and jquery how to find and replace a selected option that has a certain value but cannot seem to get it to work

My code is

$('#Test1').change(function () {
        sessionStorage.setItem("Test1", $(this).val());
        $('.main-filter :selected:contains("#ReplaceThisText#")').val($(this).val());
        location.href = $(this).val();
    });
0

1 Answer 1

1

:contains will look at the .text() value - but your #ReplaceThisText# is not in the .text() value - so you'll need to use .filter() to find it instead:

Adding some console.logs so you can see what's happening and updated the .val(newval) code to make the replacement.

$('#Test1').change(function() {
  var newval = $(this).val();
  console.log("before", $(".main-filter :contains('Change Value')").val())
  var opt = $('.main-filter option').filter(function() {
      return $(this).val().indexOf("#ReplaceThisText#") >= 0;
  });
  console.log("opt length", opt.length);
  opt.each(function() { 
      $(this).val($(this).val().replace(/#ReplaceThisText#/gi, newval));
  });
  console.log("after", $(".main-filter :contains('Change Value')").val())
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select class="main-filter" id="Test1" name="Test1">
  <option value="">Select Option</option>
  <option value="1">One</option>
  <option value="2">Two</option>
</select>

<select id="selectfilter" name="selectfilter" class="form-control main-filter">
  <option value="">Sort Products</option>
  <option value="/?id=na&amp;selectfilter=hl&amp;Type=#ReplaceThisText#">Change Value</option>
</select>

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.