MrProgram
MrProgram

Reputation: 5242

Dynamically change ID on textboxes depending on select value MVC

I have some textboxes and a select tag looking like this:

<select id="calcOption" name="calcOption">
    <option value="PMT" id="PMT" name="PMT">Payment (PMT)</option>
    <option value="I" id="I" name="I">Interest (I)</option>
    <option value="FV" id="FV" name="FV">Future value (FV)</option>
    <option value="PV" id="PV" name="PV">Present value (PV)</option>
</select>
@Html.Label("Present value (PV)", new { id = "pvLabel" })
@Html.TextBox("PresentValue")
@Html.Label("Future value", new { id = "fvLabel" })
@Html.TextBox("FutureValue")
@Html.Label("Interest rate", new { id = "intRateLabel" })
@Html.TextBox("InterestRate")

And depending on the value choosed in the select tag I want the ID and label to change like this:

$(document).on('change', '#calcOption', function () {
var selected = $('#calcOption option:selected').attr('id');
switch (selected) {
    case 'I':
        $('#intRateLabel').text("Payment (PMT)");
        $('#fvLabel').text("Future value (FV)");
        $('#pvLabel').text("Present value (PV)");
        $('#InterestRate').attr({ id: 'PMT', name: 'PMT' });
        break;
    case 'PV':
        $('#intRateLabel').text("Interest rate");
        $('#pvLabel').text("Payment (PMT)");
        $('#fvLabel').text("Future value (FV)");
        $('#PresentValue').attr({ id: 'PMT', name: 'PMT' });
        break;
    case 'FV':
        $('#intRateLabel').text("Interest rate");
        $('#fvLabel').text("Payment (PMT)");
        $('#pvLabel').text("Present value (PV)");
        $('#FutureValue').attr({ id: 'PMT', name: 'PMT' });
        break;
    case 'PMT':
        $('#intRateLabel').text("Interest rate");
        $('#fvLabel').text("Future value (FV)");
        $('#pvLabel').text("Present value (PV)");
        $('#InterestRate').attr({ id: 'InterestRate', name: 'InterestRate' });
        break;
}
});

The problem I have is when I switch between the values more times they don't change back. So if I take value I then the ID InterestRate changes to PMT. But if I change to another value like PV, I want the ID InterestRate to come back where PMT was. So if I click around in the select tag all ID's will be PMT and I need to refresh the page to get all ID's back. But I would like them to change back as I change value. How do I do that?

Upvotes: 0

Views: 668

Answers (1)

Daniel Melo
Daniel Melo

Reputation: 558

First you need set id atribute to this sintaxe:

@Html.Label("Interest rate", new { @id = "intRateLabel" })

Now. I suggest you change the atribute manipulation to class instead id for each elemment

@Html.TextBox("InterestRate", new{ @class = "payment" })

Edit your code to:

$(document).on('change', '#calcOption', function () {
var selected = $('#calcOption option:selected').attr('id');
switch (selected) {
    case 'I':        
        $('.payment').attr({ id: 'PMT', name: 'PMT' });

Upvotes: 1

Related Questions