L84
L84

Reputation: 46298

Use JS to Mark a Form Field as Read Only

I have a form that collects a payment based on a users choice of membership level. When they choose the level JS auto fills in the amount on the form. What I would also like to do is mark the field as readonly after they choose an option. But there is a catch. There is an option to enter a custom amount (I have a minimum amount set). If this option is chosen then I want the amount field left alone to allow the user enter their amount.

How do I have the field auto-populated and marked as readonly unless they choose Custom Amount?

Here is my HTML and JS (Note: I am only showing the HTML for the two fields involved not the entire form.)

HTML

<!-- MEMBERSHIP SELECT -->
<div><label for="CAT_Custom_320540">Membership Level <span class="req">*</span></label></div>
  <select class="cat_dropdown" id="CAT_Custom_320540" name="CAT_Custom_320540">
    <option value=" ">-- Please select --</option>
    <option value="20.00">Basic $20</option>
    <option value="35.00">Regular $35</option>
    <option value="50.00">Advocate $50</option>
    <option value="100.00">Dedicated $100</option>
    <option value="250.00">Big Time $250</option>
    <option value="3500.00">Lifetime $3500</option>
    <option value="">Custom Amount</option>
    </select>

<!-- AMOUNT -->
<div><label for="Amount">Amount<span class="req">*</span> <span id="constraint-300-label"> (minimum: <span id="constraint-300">20.00</span>)</span></label></div>
<input name="Amount" type="text" class="cat_textbox" id="Amount"  />

JS

var select = document.getElementById('CAT_Custom_320540');
var input = document.getElementById('Amount');
    select.onchange = function() {
        input.value = select.value;
}

As you can see I have the Amount field auto-populated but I do not know how to mark as read only and leave the ability to leave the field not read only if Custom Amount is chosen.

I am using jQuery 1.8.3 on the site and willing to use the jQuery was of doing what I did with vanilla JS.

Upvotes: 0

Views: 688

Answers (1)

KooiInc
KooiInc

Reputation: 122878

I think you can test for the value and use the disabled attribute if the value is not empty:

var select = document.getElementById('CAT_Custom_320540');
var input = document.getElementById('Amount');
    select.onchange = function() {
        input.value = select.value;
        if ($.trim(input.value).length)
         input.setAttribute('disabled',true);
        else
         input.removeAttribute('disabled');
}

JSFiddle

Upvotes: 3

Related Questions