javascript/ php
I am trying to get the value and content of an option element. So far I have it getting the value using this.value
as shown below
<select name='name' id='name' onchange='someFunction(this.value)'>
<option selected='selected' disabled='disabled' value=''>CONTENT</option>
" . $options . "
</select>";
Can I pass over the "CONTENT" on the onchange
event as well at the value?
Something like this maybe... onchange='showAccountInfo(this.value, ???)
Any help would be awesome thanks!
<select name='name' id='name' onchange='someFunction(this)'>
<option selected='selected' disabled='disabled' value=''>CONTENT</option>
" . $options . "
</select>"
function someFunction(obj)
{
var value = obj.value;
var content = obj.querySelector("option:checked").textContent;
}
That should do it:
I changed the object passed in the onchange
function. It passes the select object to the function using the keyword this
. Then we use value
to select the value and a querySelector that selects the selected option using the selector option:checked
. This way your code becomes more readable.
However you could store it inside the onchange like this:
onchange='showAccountInfo(this.value, this.querySelector("option:checked").textContent)'
Personally I wouldn't use (or recommend) the use of inline events.
I would do it like this using addEventListener
:
function someFunction(e) { //this refers to the select element (the owner of the event); var value = this.value; var content = this.querySelector("option:checked").textContent; alert("value: " + value + " content: " + content); } document.querySelector("#name").addEventListener("change", someFunction, false); //attach an onchange event using the addEventListener method. //I'm using document.querySelector here to select an element on the page.
<select name='name' id='name' > <option selected='selected' value='1:'>CONTENT 1</option> <option value='2:'>CONTENT 2</option> <option value='3:'>CONTENT 3</option> <option value='4:'>CONTENT 4</option> </select>
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.