简体   繁体   中英

Assign input box value from another input box on select click in jquery

I have a form where there are 5 fields, 3 of them has a value like hours,days and lease which has default values, then one selectbox and another empty input box, my code is like below:

 $(document).ready(function() { $('#hr').change(function() { $('#mytexts').val($('#hours').val()); }); });
 <input type="text" id="hours" value="23" readonly/> <input type="text" id="days" value="33" readonly/> <input type="text" id="lease" value="33" readonly/> <select name="hours" id="hr"> <option value="" onchange="myFunctionhours(this)">---Select---</option> <option value="hours">Hours</option> <option value="days">Days</option> <option value="lease">Lease</option> </select> <input type="text" name="crate" id="mytexts" value="" readonly/>

When a value is selected From the selectBox I want to empty input box to get values from the 3 input boxes accordingly, now in what I did I am able to only get the value of hours box, can anyone please tell me how to do this, thanks in advance

you have to take the the value from the change event, by useing event.target.value then assign its follwing value to the result input as follow:

  $('#hr').change(function(event) {
    let selected = event.target.value;
     if(selected) $('#mytexts').val($("#"+selected).val());
  });

see below wokring snippet:

 $(document).ready(function() { $('#hr').change(function(event) { let selected = event.target.value; $("#choise").html(selected) if(selected) $('#mytexts').val($("#"+selected).val()); }); });
 <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <input type="text" id="hours" value="23" readonly/> <input type="text" id="days" value="33" readonly/> <input type="text" id="lease" value="33" readonly/> <br /><br /> <select name="hours" id="hr"> <option value="" onchange="myFunctionhours(this)">---Select---</option> <option value="hours">Hours</option> <option value="days">Days</option> <option value="lease">Lease</option> </select> <br /><br /> <input type="text" name="crate" id="mytexts" value="" readonly/> <span id="choise"></span>

You have to use the value of dropdown value as query selector in JQuery.

 $(document).ready(function() { $('#hr').change(function() { $('#mytexts').val($("#"+$('#hr').val()).val()); }); });
 <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <:-- begin snippet: js hide: false console: true babel: null -->

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM