ninja
ninja

Reputation: 53

Javascript onchange function not working on select tag

I made 2 input fields and 1 select field and I applied onchange() function to select tag which calls javascript and that script make calculation and show it in other two fields but it is not working for some syntax or logic reasons. please take a look at my code ,any help would be appreciated.

<html>
<head>
<script type="text/javascript">
function update() {
var x = document.getElementsByName("n_person").value;
document.getElementsByName("m_income").value= x*5;
document.getElementsByName("y_income").value= x*4;
}
</script>
</head>

<body>


<div class="elist"> <span class="b_text"><span>*</span>Level 1:</span>
// here is select tag where I put onchage function  <select class="ifield" name="n_person" onChange="update()">
    <option value="" selected="selected">Choose no. of person referred</option>
    <option value="1">1</option>
    <option value="2">2</option>
    <option value="3">3</option>
  </select>
// These are teh input where resultant value will appear  <input type="text" value="" placeholder="Your weekly Income..." name="m_income" id="weekly_income" class="field" readonly required />
  <input type="text" value="" placeholder="Your day Income..." name="y_income" id="day_income" class="field" readonly required/>
</div>
<!--elist-->

</body>
</html>

Upvotes: 2

Views: 155

Answers (2)

Alexander van Oostenrijk
Alexander van Oostenrijk

Reputation: 4764

The method getElementsByName returns, as its name indicates, a list of elements with the specified name and not just one. In your case, the names are unique to the document and the method will return a list with just one value, but you'll still need to index this list. Therefore, you must change this:

var x = document.getElementsByName("n_person").value;

to

var x = document.getElementsByName("n_person")[0].value;

Do this also for the other uses of getElementsByName and your code will work.

Upvotes: 3

Lal
Lal

Reputation: 14810

See this fiddle

Updated JS

function update() {
  var x = document.getElementsByName("n_person")[0].value;
  document.getElementsByName("m_income")[0].value = x * 5;
  document.getElementsByName("y_income")[0].value = x * 4;
}

The problem with your JS was you was not targetting the correct HTML elements using getElementsByName.

Please read more about it here

Upvotes: 4

Related Questions