Andrew Kilburn
Andrew Kilburn

Reputation: 2251

Javascript compare with select box value to enable a select box

What I'd like to do is check a select box's value using Javascript and if the user has selected the correct value, it will unlock the next two select box's.

The Report drop down box contains multiple options for a user to choose, ultimately I would like to dictate which select boxes open up depending on the value chosen.

For my first attempt I want to be able to check the Report drop down for the value 'ClaimsBySupplier' and if it turns out to be true then it would unlock the Supplier Name drop down box and the Review Period drop down box. JS:

function valueChanged() {

        var rdd = document.getElementById("ReportDD").value;
        var sdd = document.getElementById("SuppNameDD");

        if (rdd.valueOf("ClaimsBySupplier")) sdd.disabled = false;

    }

HTML:

<content id="GenerateReportContent" class="col-md-4">
            <form id="GenerateReportContainer">
                <div class="AltFunctions">
                    <ul>
                        <li>
                            <a href="#" class="AltButton" id="altClearButton">Clear</a>
                        </li>
                        <li>
                            <a href="#" class="AltButton" id="GRaltInfoButton">Info</a>
                        </li>
                    </ul>
                </div>

                <h1 id="GenerateReportHeader">GENERATE REPORT</h1>
                <input type="text" id="txtGRC" class="form-control" placeholder="Enter Specific Claim Number...." onkeydown="valueChanged()" >
                <p id="txtOptional">(optional)</p>
                <select class="GRDropDown" id="ReportDD">
                    <option value="SelectReport">Select Report</option>
                    <option value="ClaimsBySupplier">Claims By Supplier</option>
                    <option value="ClaimsByDepartment">Claims By Department</option>
                    <option value="ReasonCodeBreakdown">Reason code breakdown</option>
                    <option value="MonthlyDebitingReport">Monthly Debiting Report</option>
                </select>
                <br />
                <select class="GRDropDown" id="SuppNameDD" disabled>
                    <option value="SelectSupplierName">Select Supplier Name</option>
                </select>
                <br />
                <select class="GRDropDown" id="ReviewPeriodDD" disabled>
                    <option value="SelectReviewPeriod">Select Review Period</option>
                </select>
                <div class="form-group">
                    <input type="text" id="txtGRC" class="form-control" placeholder="Month Code..." disabled="disabled">
                    <p id="txtOptional">(optional)</p>

                </div>
                <button type="submit" id="GenerateReportButton" class="btn btn-default">GO</button>
            </form>
        </content>

I'm not fluent in Javascript and could do with some help.

Upvotes: 0

Views: 564

Answers (3)

Dmytro Vyprichenko
Dmytro Vyprichenko

Reputation: 4924

I'd prefer to store dependencies between fields in data-attributes. Each input or select will have own data-dependencies attribute with a string of certain format to specify the conditions it requires to become enabled. The conditions are defined as (multiple) key/value pairs where key is the name of another input in the form.

This approach allows you to make multi-purpose script. Check out the code, please.

function DependentInput (input, form) {
    this.input = input;
    this.form = form;
    this.parseDeps();
    this.checkDeps();
    
    var self = this;
    form.addEventListener('change', function () {
        self.checkDeps();
    });
}

// Parse string of dependencies to object
// Almost no need in this function if data-dependencies were filled with JSON
DependentInput.prototype.parseDeps = function () {
    this.deps = {};
    var self = this,
        data = this.input.getAttribute('data-dependencies');
    if (data) {
        data.split(';').forEach(function (d) {
            d = d.split('=');
            self.deps[d[0]] = d[1] || '';
        });
    }
}

// Check the state of fields we depend on
// Dependencies can be strict, when exact match of value is required
// Or soft, in which case any non-empty value is accepted
DependentInput.prototype.checkDeps = function () {
    var active = true;
    for (var d in this.deps) {
        active &= (this.deps[d] == '') ? (!!this.form[d].value) : (this.deps[d] == this.form[d].value);
    }
    this.input.disabled = !active;
}

// Initialize form fields
var inputs = document.querySelectorAll('[data-dependencies]');
Array.prototype.slice.call(inputs).forEach(function (i) {
    new DependentInput(i, i.form);
});
input,
select {
	display: block;
	width: 300px;
	margin-bottom: 1em;
}

input:disabled,
select:disabled {
	outline: 2px solid tomato;
}
<form>
    <select name="ReportDD" title="No dependencies">
        <option value="SelectReport">Select Report</option>
        <option value="ClaimsBySupplier">Claims By Supplier</option>
        <option value="ClaimsByDepartment">Claims By Department</option>
    </select>
  
	<!-- SuppNameDD is activated when ReportDD = "ClaimsBySupplier" -->
    <select name="SuppNameDD"
            title="Requires ClaimsBySupplier"
            data-dependencies="ReportDD=ClaimsBySupplier">
        <option value="">Select SuppName</option>
        <option value="SupplierName">Supplier Name</option>
    </select>
  
	<!-- SuppNameDD is activated when ReportDD = "ClaimsBySupplier" and SuppNameDD = "SupplierName" -->
    <select name="ReviewPeriodDD"
            title="Requires ClaimsBySupplier and SupplierName"
            data-dependencies="ReportDD=ClaimsBySupplier;SuppNameDD=SupplierName">
        <option value="">Select RewiewPeriod</option>
        <option value="ReviewPeriod1">Review Period 1</option>
        <option value="ReviewPeriod2">Review Period 2</option>
    </select>
  
	<!-- TxtGRC1 is activated when ReviewPeriodDD has any of non-empty values -->
    <input type="text"
           name="TxtGRC1"
           title="Requires ReviewPeriodDD to have any non-empty value"
           placeholder="Txt 1"
           data-dependencies="ReviewPeriodDD"/>
  
    <!-- TxtGRC2 is activated when ReviewPeriodDD = "ReviewPeriod2" and TxtGRC1 has any value -->
    <input type="text"
           name="TxtGRC2"
           title="Requires ReviewPeriod2 and TxtGRC1 filled"
           placeholder="Txt 2"
           data-dependencies="ReviewPeriodDD=ReviewPeriod2;TxtGRC1"/>
</form>

Upvotes: 1

Andrew Kilburn
Andrew Kilburn

Reputation: 2251

 $(document).ready(function () {            
            $('#ReportDD').change(function () {
                if ($(this).val() == "ClaimsBySupplier") {
                    $('#SuppNameDD').removeAttr('disabled');
                    $('#ReviewPeriodDD').removeAttr('disabled');
                }
                else if ($(this).val() == "ClaimsByDepartment") {
                    $('#SuppNameDD').removeAttr('disabled');
                    $('#ReviewPeriodDD').removeAttr('disabled');
                }
                else if ($(this).val() == "ReasonCodeBreakdown") {
                    $('#SuppNameDD').removeAttr('disabled');
                    $('#ReviewPeriodDD').removeAttr('disabled');
                }
                else if ($(this).val() == "MonthlyDebitingReport") {
                    $('#ReviewPeriodDD').removeAttr('disabled');
                    $('#txtGRC').removeAttr('disabled');
                }
            });
        });

Asked some work colleagues and they helped. Here is the JQuery way of doing it. I didn't get a chance to use ntaloventi's answer so I cannot confirm if it is correct.

Upvotes: 0

Iqbal Rizky
Iqbal Rizky

Reputation: 350

This just simple if else statement
maybe you can think to keep disable if rdd was not "ClaimsBySupplier"

function valueChanged() {
var rdd = document.getElementById("ReportDD");
var sdd = document.getElementById("SuppNameDD");

if (rdd.value == "ClaimsBySupplier") 
{
  sdd.disabled = false;
}
else
{
sdd.disabled = true;
}

//if (rdd.value.indexOf('ClaimsBySupplier') > -1) sdd.disabled = false;
};
<content id="GenerateReportContent" class="col-md-4">
            <form id="GenerateReportContainer">
                <div class="AltFunctions">
                    <ul>
                        <li>
                            <a href="#" class="AltButton" id="altClearButton">Clear</a>
                        </li>
                        <li>
                            <a href="#" class="AltButton" id="GRaltInfoButton">Info</a>
                        </li>
                    </ul>
                </div>

                <h1 id="GenerateReportHeader">GENERATE REPORT</h1>
                <input type="text" id="txtGRC" class="form-control" placeholder="Enter Specific Claim Number...." >
                <p id="txtOptional">(optional)</p>
                <select class="GRDropDown" id="ReportDD" onchange="valueChanged()">
                    <option value="SelectReport">Select Report</option>
                    <option value="ClaimsBySupplier">Claims By Supplier</option>
                    <option value="ClaimsByDepartment">Claims By Department</option>
                    <option value="ReasonCodeBreakdown">Reason code breakdown</option>
                    <option value="MonthlyDebitingReport">Monthly Debiting Report</option>
                </select>
                <br />
                <select class="GRDropDown" id="SuppNameDD" disabled>
                    <option value="SelectSupplierName">Select Supplier Name</option>
                </select>
                <br />
                <select class="GRDropDown" id="ReviewPeriodDD" disabled>
                    <option value="SelectReviewPeriod">Select Review Period</option>
                </select>
                <div class="form-group">
                    <input type="text" id="txtGRC" class="form-control" placeholder="Month Code..." disabled="disabled">
                    <p id="txtOptional">(optional)</p>

                </div>
                <button type="submit" id="GenerateReportButton" class="btn btn-default">GO</button>
            </form>
        </content>

Hopes this help...

Upvotes: 0

Related Questions