Home > Software engineering >  How to change option selection and change button link for multipe forms in a page?
How to change option selection and change button link for multipe forms in a page?

Time:12-21

How can I take the value from the option and update button link with the option value? I come across this solution but there are a few things which I want to achieve that are not covered.

Example JSFiddle.

How can I use same script when there are three forms in a page instead of one?

$('select').on('change', function() {
  $('.button').attr('href', 'cart.php?a=add&pid='   $(this).val());
});
<select id="micro-plan">
  <option value="5">$5.00 monthly</option>
  <option value="10">$10.00 monthly</option>
  <option value="15">$15.00 monthly</option>
  <option value="20">$20.00 monthly</option>
</select>
<a href="cart.php?a=add&pid=1"  target="_blank">Order</a>

<select id="mega-plan">
  <option value="25">$25.00 monthly</option>
  <option value="30">$30.00 monthly</option>
  <option value="35">$35.00 monthly</option>
  <option value="40">$40.00 monthly</option>
</select>
<a href="cart.php?a=add&pid=25"  target="_blank">Order</a>

<select id="super-plan">
  <option value="45">$45.00 monthly</option>
  <option value="50">$50.00 monthly</option>
  <option value="65">$65.00 monthly</option>
  <option value="70">$70.00 monthly</option>
</select>
<a href="cart.php?a=add&pid=45"  target="_blank">Order</a>

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

CodePudding user response:

  1. Use the same class for each button (or no class--you can just use the element type).
  2. Query for the button by its proximity to the select element.
  3. Use $(this) to refer to the element on which the event fired, just as you have to get its value.

$('select').on('change', function() {
  $(this).next('.button').attr('href', 'cart.php?a=add&pid='   $(this).val());
});
<select id="micro-plan">
  <option value="5">$5.00 monthly</option>
  <option value="10">$10.00 monthly</option>
  <option value="15">$15.00 monthly</option>
  <option value="20">$20.00 monthly</option>
</select>
<a href="cart.php?a=add&pid=1"  target="_blank">Order</a>

<select id="mega-plan">
  <option value="25">$25.00 monthly</option>
  <option value="30">$30.00 monthly</option>
  <option value="35">$35.00 monthly</option>
  <option value="40">$40.00 monthly</option>
</select>
<a href="cart.php?a=add&pid=25"  target="_blank">Order</a>

<select id="super-plan">
  <option value="45">$45.00 monthly</option>
  <option value="50">$50.00 monthly</option>
  <option value="65">$65.00 monthly</option>
  <option value="70">$70.00 monthly</option>
</select>
<a href="cart.php?a=add&pid=45"  target="_blank">Order</a>

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

  • Related