Search code examples
javascripthtmlaurelia

Changing title (labels) based on dropdown selection


I'm struggling with a concept where I need to dynamically be able to load a field name. I have a dropdown selection as below code

<label>Payer Type*</label>
 <span class="inherit" style="width: 175px">
      <select class="drop-down" style="width: 175px">
           <option disabled selected value >Select</option>
           <option value="card">Credit Card</option>
           <option value="bank">Bank Account</option>
       </select>
  </span>

From the above options if I select credit card I want the labels to change to card number, card name CVV, and if I select bank account I need the labels to be Account number, account name as shown below.

<div class="col-md-2 p-l-5 p-b-10" style="margin-left: -20px">
                <label>**Card Number* / Account number**</label>
                <span class="inherit"><input class="form-input" style="width:200px;" ></span>
            </div>

            <div class="col-md-2 p-l-5 p-b-10">
                <label>**Card Name / Account name**</label>
                <span class="inherit"><input class="form-input" style="width:200px;"></span>
            </div>

How do I pass the parameters and change the labels based on option we select from dropdown using javascript.? I'm new to javascript and my attempts failed to pass the parameters and get the work done. Greatly appreciate any help on this. Thanks.


Solution

  • You can use onchange event of select. When any option is changed in selected the javascript function changeLabel(select) is called. The option is checked and text of label is changed according to selected option(You need to add id to your label to access it from javascript)

    function changeLabel(select){
      if(select.value == "card"){
         document.getElementById('lbl_data').innerHTML="**Card Number* / Account number**";
      }else if(select.value == "bank"){
        document.getElementById('lbl_data').innerHTML="**Card Name / Account name**";
      }
    }
                
    <label>Payer Type*</label>
     <span class="inherit" style="width: 175px">
          <select class="drop-down" style="width: 175px" onchange="changeLabel(this)">
               <option disabled selected value >Select</option>
               <option value="card">Credit Card</option>
               <option value="bank">Bank Account</option>
           </select>
      </span>
      
      <div class="col-md-2 p-l-5 p-b-10" style="margin-left: -20px">
                    <label id="lbl_data">**Card Number* / Account number**</label>
                    <span class="inherit"><input class="form-input" style="width:200px;" ></span>
                </div>