0

I'm trying to input something into a text field based on an option selected from a dropdown, using .val(), but it is not working.

$('#addressee_type').on('change', function() {
  var type = $("select#addressee_type option:selected").attr('value');
  // alert(type);
  if (type == 'I') {
    $('#name').attr('required', true).val('insured')
  } else if (type == 'A') {
    $('#name').attr('required', true).val('third party adv')
  } else if (type == 'C') {
    $('#name').attr('required', true).val('third party')
  } else {
    $('#name').attr('required', true).val('')
  }

})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="col-sm-4">
  <label class="required">Addressee type</label>
  <select class="form-control chosen" id="addressee_type" name="addressee_type" required>
    <option value="" selected>Please select Addressee type</option>
    <option value="I">Insured</option>
    <option value="A">Third Party Advocate</option>
    <option value="C">Third Party Claimant</option>
  </select>
</div>

<div class="col-sm-4">
  <label class='required'>Addressee Name</label>
  <input class="form-control" readonly="true" id="name" type="text" name="name">
</div>

I added the attr() later on from a solution I found, but it still didn't solve the error. Does anyone have an idea?

DBS
  • 9,110
  • 4
  • 35
  • 53
Sammy
  • 11
  • 1
  • 3
    I've turned your code into a snippet, and it appears to work. Are there any errors in your browser console? or other code that might be interfering? – DBS Nov 23 '22 at 09:56
  • ^^ that said, `var type = $("select#addressee_type option:selected").attr('value');` is probably better written `const type = $("#addressee_type").val();`. (The three changes there are 1. Use `const` [or `let`], `var` is obsolete; 2. Get the current value from the select box itself, not from the option; 3. There's no need for the tag selector on top of the ID selector except in ***very*** unusual edge cases.) – T.J. Crowder Nov 23 '22 at 09:59
  • 1
    See http://stackoverflow.com/questions/14028959/why-does-jquery-or-a-dom-method-such-as-getelementbyid-not-find-the-element for one possible thing it could be in your real page. – T.J. Crowder Nov 23 '22 at 10:00
  • I tried option 3 from this https://stackoverflow.com/questions/14028959/why-does-jquery-or-a-dom-method-such-as-getelementbyid-not-find-the-element and it worked. – Sammy Nov 23 '22 at 12:36
  • In which case, you *probably* wanted option 4: wrap your code in doc.ready (jquery's ready event in that answer). Or option 5: event delegation, or just option1: move your code to the end (which is what adding `module` *essentially* does) – freedomn-m Nov 23 '22 at 12:42

0 Answers0