Yuvi
Yuvi

Reputation: 640

How can I create this switch behaviour via Javascript?

First of all, I am really sorry that I could not give specific title about the issue. I have a .net 4.6.1 view page.

enter image description here

I want to create this feature.

Depending on the DepositType, the DefaultDeposit should display either a £ sign or %.

One of the logic, I already tried was to create another property called DefaultDepositPercent. Create a Input Box which is hidden underneath and use Jquery to display or hide this Input Box. Then in my service layer, pass the value inputted in the DefaultDepositPercent to DefaultDeposit. However, there was an inconvenience that the mvc form also passes the DefaultDeposit value as 0. And there is also an issue of someone fiddling with the Javascript.

I have googled but could not find any answers. It is likely because I could describe the issue in few words.

Any direction would be helpful. Thanks

Upvotes: 0

Views: 43

Answers (1)

Rajshekar Reddy
Rajshekar Reddy

Reputation: 19007

In bootstrap we just have to place the span tag above or below the input element to get the Prefix or Postfix effect. More Details Here

So the idea is first not to have this post / prefix span tag initially but add it either on DOM ready event or when the drop down selection changes using Jquery insertBefore and insertAfter. Here is a working sample. Hope this is helpful.

$(function() {

  SetUpDepositTextBox();  // set up the input box once when DOM is ready

  $('.DepositType').on('change', function() {
    SetUpDepositTextBox(); // set up the text box when ever the dropdown changes
  });
});

function SetUpDepositTextBox() {
  $('#depositDefaultWrapper span').remove();
  var $this = $('.DepositType');

  if ($this.val() == "Amount") {
    $('<span class="input-group-addon">£</span>').insertBefore('#depositDefaultWrapper input');
  } else {
    $('<span class="input-group-addon">%</span>').insertAfter('#depositDefaultWrapper input');
  }
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"></script>
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" rel="stylesheet" />

 Deposit Type
<select class="DepositType form-control">
  <option value="Amount">Amount</option>
  <option value="Percentage">Percentage</option>
</select>

Default Deposit
<div id="depositDefaultWrapper" class="input-group">
  <input type="text" class="form-control" value="10">
</div>

Upvotes: 1

Related Questions