最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - document.getElementById("id") in onchange parameter - Stack Overflow

programmeradmin2浏览0评论

I am working on an ERP program where i needto write data to and from a database. Here i would like to send data with an input field, therefore i call a specific javascript function on an onchange event.
I would like to add the value of another element with the onchange parameter like this

onchange="myFunction(document.getElementById("myId"))"

I already tried this but it does not work:

onchange="myFunction(document.getElementById(\"myId\"))"

How do i do this?

I am working on an ERP program where i needto write data to and from a database. Here i would like to send data with an input field, therefore i call a specific javascript function on an onchange event.
I would like to add the value of another element with the onchange parameter like this

onchange="myFunction(document.getElementById("myId"))"

I already tried this but it does not work:

onchange="myFunction(document.getElementById(\"myId\"))"

How do i do this?

Share Improve this question edited Jan 16, 2016 at 11:33 Snazzy Sanoj 8021 gold badge11 silver badges28 bronze badges asked Jan 16, 2016 at 9:12 ThomasThomas 1471 gold badge4 silver badges10 bronze badges 3
  • you can use single quotes as well – Ehsan Sajjad Commented Jan 16, 2016 at 9:13
  • @Thomas stackoverflow./a/34825625/4763793 please see this – Rino Raj Commented Jan 16, 2016 at 9:57
  • you can use onchange="myFunction(document.getElementById(\"myId\"))" but only thing is that the function should be defined before it is being called – Rajesh Jangid Commented Jan 16, 2016 at 10:09
Add a ment  | 

6 Answers 6

Reset to default 2

Use this

onchange="myFunction(document.getElementById('myId'))"

Using onchange="myFunction(document.getElementById('myId'))" you're getting the element. If you want to use the value you have to use onchange="myFunction(document.getElementById('myId').value)"

You should try this

onchange="myFunction(document.getElementById('myId'))";

You don't have to get element in such way. It can be done right inside your function:
html part:

onchange="myFunction()"

js part:

function myFunction(){
    var target_id = document.getElementById("myId").value;
    ....
}

Please try this

onchange="myFunction(this.id)"

Example

function myFunction(id) {
  alert(id)
}
<select id="mySelect" onchange="myFunction(this.id)">
  <option value="Audi">Audi
    <option value="BMW">BMW
      <option value="Mercedes">Mercedes
        <option value="Volvo">Volvo
</select>

In JavaScript, the thing called this, is the object that "owns" the current code.The value of this, when used in a function, is the object that "owns" the function.

this.value will do. use it like

onchange=myFun(this.value) or onchange="myFun(this.value)"

both should work

发布评论

评论列表(0)

  1. 暂无评论