0

I'm getting a set of user roles from the database using PHP and they are put in a <select> tag's <option>s as follows:

<div class="col-md-3">
    <select name="role" id="user_role" class="form-control" onkeyup="clearMsg('roleerr')" onchange="getRole()"/>
        <option value="">Select a Role</option>
        <?php while($rowrole = $resultrole->fetch(PDO::FETCH_BOTH)) { ?>
        <option value="<?php echo $rowrole ['role_id']; ?>">
        <?php echo $rowrole ['role_name']; ?>
        </option>
        <?php } ?>
    </select>
    <span id="roleerr" class="error">*</span>
</div>

And I want to get the selected value of the dropdown 'onchange' and for that getRole() javascript function is written. How to get this done?

3 Answers 3

1

When the element changes, the value of the dropdown will be set to the value attributed to the selected option. So you would just define your javascript function and have it fetch the value of the dropdown:

function getRole(){
   var finalVal = document.getElementById("user_role").value;
   // And then here you can do whatever you want with the information
}
Sign up to request clarification or add additional context in comments.

1 Comment

This doesn't work....I think the value can't be accessed as var finalVal = document.getElementById("user_role").value; because it's a php array index <option value="<?php echo $rowrole ['role_id']; ?>"> Please help me
0

You can assign value in paramater in onchange()

this should work below

function getRole(value) {
  if(value != "")
     alert(value)
 }
<div class="col-md-3">
    <select name="role" id="user_role" class="form-control" onchange="getRole(this.value)"/>
        <option value="">Select a Role</option>
        <option value="23">select 23</option>
        <option value="24">select 24</option>
        <option value="25">select 25</option>
    </select>
    <span id="roleerr" class="error">*</span>
</div>

Comments

0

You could try event of onchange.

onchange="getRole(event)"

Javascript.

function getRole(event) {
    var selectElement = event.target;
    var value = selectElement.value;
    alert(value);
}

I tested it with hard data.

function getRole(event) {
    var selectElement = event.target;
    var value = selectElement.value;
    alert(value);
}
<div class="col-md-3">
    <select name="role" id="user_role" class="form-control" onchange="getRole(event)"/>
        <option value="">Select a Role</option>
        <option value="1">admin</option>
        <option value="2">user</option>
        <option value="3">support</option>
    </select>
    <span id="roleerr" class="error">*</span>
</div>

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.