-1

I am trying to set the value of a drop down list from the input box value and also trying to disable it. I am able to disable it but unable to set the value of it from the input box. Can anyone please help here.

Here is my HTML code.

<div class="form-group">
    <label>New Image VM Resource Group</label>
    <input type="checkbox" id="IsAssociation" name="resourcegroupnull" value="New-Resourcegroup">New Resourcegroup</input>
    <select class="form-control" id="groupunderwriter" name="rgnames_option1">
        <option value="" disabled selected>Select Image VM Resource Group</option>
        <?php 
        foreach ($rgnames as $item) {
            echo "<option value='strtolower($item)'>$item</option>";
        }
        ?>
    </select>

Here is my JavaScript code.

$(document).on('change', '#IsAssociation', function () {
    if ($(this).prop('checked')) {
        $('#groupunderwriter').attr('disabled', 'disabled');
        let rgname = prompt("Please enter resource group name");
        if (rgname != null) {
            $('#groupunderwriter').val('rgname');
        }
    } else {
        $('#groupunderwriter').removeAttr('disabled');
    }
});
Don't Panic
  • 13,965
  • 5
  • 32
  • 51
askwizard
  • 107
  • 9
  • Use .val() to set a value – ADyson Aug 01 '22 at 07:19
  • @askwizard you can use `val()`, but this will only set the selected option if it ***exactly*** matches the input the user gives. Are you instead saying that you want to create a new option which contains the value the user types in to the `prompt()`? – Rory McCrossan Aug 01 '22 at 07:55
  • No I wanted to only set the selected option based on the text entered in the input not the 2nd option, but I am trying with $('#groupunderwriter').val(rgname); and it's not working. – askwizard Aug 01 '22 at 08:25
  • https://stackoverflow.com/questions/5182772/append-option-to-select-menu and https://stackoverflow.com/questions/10570070/how-to-disable-enable-select-field-using-jquery seem to cover what you're trying to do? – Don't Panic Aug 01 '22 at 09:24

1 Answers1

0

use jquery val() property for set and get value for html selector

$('#groupunderwriter').append('<option selected value="'+rgname+'">'+rgname+'</option>');
$('#groupunderwriter').val(rgname);
Jay Patel
  • 231
  • 1
  • 4
  • '... and disable it for any further modification?' – Rory McCrossan Aug 01 '22 at 07:51
  • I have changed the code as per your advice but this gives a blank text in the dropdown list. Please find the modified actual code. – askwizard Aug 01 '22 at 07:52
  • please check, i have updated answer , now it will append option to select – Jay Patel Aug 01 '22 at 09:08
  • `rgname` doesn't exist in the `select` when you are trying to use `.val()`. And the next line adds a 2nd option which is `selected` (*Select Image VM Resource Group* is already selected), and adds it without an actual `value` ... – Don't Panic Aug 01 '22 at 09:27