user_v12
user_v12

Reputation: 589

Get option name attribute value to input

I want to get the name attribute value to an input(#currency_sym).

HTML:

<select id="cur_rate" onchange="changeFunc();">
     {{#each currencies}}
        <option name="{{this.symbol}}">{{this.currency}}</option>
     {{/each}}
</select>
<input type="text" id="currency_sym">

Javascript function:

function changeFunc() {
   $('#currency_sym').val($(".currateopt").attr("name"));
}

When I tried selecting various options values. But it always shows only one symbol. What is the problem there?

Upvotes: 1

Views: 819

Answers (3)

Mamun
Mamun

Reputation: 68933

You can use option:selected to target the selected option from the passed element:

Demo:

function changeFunc(el) {
   $('#currency_sym').val($(el).find('option:selected').attr("name"));
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<select class="curratesec" id="cur_rate" onchange="changeFunc(this);">
     <option selected disabled>--Select Currency--</option>
     <option class="currateopt" id="id1" value="1" 
              name="symbol1">Dollar</option>
              <option class="currateopt" id="id2" value="2" 
              name="symbol2">Pound</option>
     <input type="text" id="currency_sym" name="currency_sym">
</select>

Upvotes: 2

Cristopher Fuentealba
Cristopher Fuentealba

Reputation: 171

You can try

html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <script src="test.js"></script>
</head>
<body>
<button type="button" id="test" name="test" onclick="myFunction(this);">Click Me!</button>
</body>
</html>

test.js

function myFunction(obj){
alert(obj.name)
}

OR

var obj = document.getElementById("test");
alert(obj.name);

Regards

Upvotes: -3

matthias_h
matthias_h

Reputation: 11416

To get the name of the selected option, change your function as follows:

function changeFunc() {
   $('#currency_sym').val($("#cur_rate").find("option:selected").attr("name"));
}

Upvotes: 2

Related Questions