Reputation: 589
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
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
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
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