如何在html select的onChange上传递参数

发布于 2024-10-17 22:19:48 字数 182 浏览 2 评论 0原文

我是 JavaScript 和 jQuery 的新手。我想显示一个组合框-A,它是一个 HTML

如何传递完整的组合框及其选择 id,以及如何传递 onChange 事件的其他参数?

I am a novice at JavaScript and jQuery. I want to show one combobox-A, which is an HTML <select> with its selected id and contents at the other place on onChange().

How can I pass the complete combobox with its select id, and how can I pass other parameters on fire of the onChange event?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(17

单身狗的梦 2024-10-24 22:19:48
function getComboA(selectObject) {
  var value = selectObject.value;  
  console.log(value);
}
<select id="comboA" onchange="getComboA(this)">
  <option value="">Select combo</option>
  <option value="Value1">Text1</option>
  <option value="Value2">Text2</option>
  <option value="Value3">Text3</option>
</select>

上面的示例获取 OnChange 上组合框的选定值事件。

function getComboA(selectObject) {
  var value = selectObject.value;  
  console.log(value);
}
<select id="comboA" onchange="getComboA(this)">
  <option value="">Select combo</option>
  <option value="Value1">Text1</option>
  <option value="Value2">Text2</option>
  <option value="Value3">Text3</option>
</select>

The above example gets you the selected value of combo box on OnChange event.

黒涩兲箜 2024-10-24 22:19:48

在某些情况下,另一种方法可能很方便,即将所选 的值直接传递给函数,如下所示:

function myFunction(chosen) {
  console.log(chosen);
}
<select onChange="myFunction(this.options[this.selectedIndex].value)">
  <option value="1">Text 1</option>
  <option value="2">Text 2</option>
</select>

Another approach wich can be handy in some situations, is passing the value of the selected <option /> directly to the function like this:

function myFunction(chosen) {
  console.log(chosen);
}
<select onChange="myFunction(this.options[this.selectedIndex].value)">
  <option value="1">Text 1</option>
  <option value="2">Text 2</option>
</select>

如果没有你 2024-10-24 22:19:48

关于如何在 jQuery 中执行此操作:

<select id="yourid">
<option value="Value 1">Text 1</option>
<option value="Value 2">Text 2</option>
</select>

<script src="jquery.js"></script>
<script>
$('#yourid').change(function() {
  alert('The option with value ' + $(this).val() + ' and text ' + $(this).text() + ' was selected.');
});
</script>

您还应该知道 Javascript 和 jQuery 并不相同。 jQuery 是有效的 JavaScript 代码,但并非所有 JavaScript 都是 jQuery。您应该查找差异并确保您使用的是合适的。

For how to do it in jQuery:

<select id="yourid">
<option value="Value 1">Text 1</option>
<option value="Value 2">Text 2</option>
</select>

<script src="jquery.js"></script>
<script>
$('#yourid').change(function() {
  alert('The option with value ' + $(this).val() + ' and text ' + $(this).text() + ' was selected.');
});
</script>

You should also know that Javascript and jQuery are not identical. jQuery is valid JavaScript code, but not all JavaScript is jQuery. You should look up the differences and make sure you are using the appropriate one.

守不住的情 2024-10-24 22:19:48

JavaScript 解决方案

<select id="comboA">
<option value="">Select combo</option>
<option value="Value1">Text1</option>
<option value="Value2">Text2</option>
<option value="Value3">Text3</option>
</select>
<script>
 document.getElementById("comboA").onchange = function(){
    var value = document.getElementById("comboA").value;
 };
</script>

<script>
 document.getElementById("comboA").onchange = function(evt){
    var value = evt.target.value;
 };
</script>

<script>
 document.getElementById("comboA").onchange = handleChange;

 function handleChange(evt){
    var value = evt.target.value;
 };
</script>

JavaScript Solution

<select id="comboA">
<option value="">Select combo</option>
<option value="Value1">Text1</option>
<option value="Value2">Text2</option>
<option value="Value3">Text3</option>
</select>
<script>
 document.getElementById("comboA").onchange = function(){
    var value = document.getElementById("comboA").value;
 };
</script>

or

<script>
 document.getElementById("comboA").onchange = function(evt){
    var value = evt.target.value;
 };
</script>

or

<script>
 document.getElementById("comboA").onchange = handleChange;

 function handleChange(evt){
    var value = evt.target.value;
 };
</script>
泪痕残 2024-10-24 22:19:48

我发现@Piyush 的答案很有帮助,只是补充一下,如果您以编程方式创建一个选择,那么有一种重要的方法可以实现这种可能并不明显的行为。假设您有一个函数并且创建了一个新的选择:

var changeitem = function (sel) {
  console.log(sel.selectedIndex);
}
var newSelect = document.createElement('select');
newSelect.id = 'newselect';

正常的行为可能是说

newSelect.onchange = changeitem;

但这实际上并不允许您指定传入的参数,因此您可以这样做:

newSelect.setAttribute('onchange', 'changeitem(this)');

并且您可以设置参数。如果您采用第一种方式,那么您将获得 onchange 函数的参数将取决于浏览器。第二种方式似乎跨浏览器工作得很好。

I found @Piyush's answer helpful, and just to add to it, if you programatically create a select, then there is an important way to get this behavior that may not be obvious. Let's say you have a function and you create a new select:

var changeitem = function (sel) {
  console.log(sel.selectedIndex);
}
var newSelect = document.createElement('select');
newSelect.id = 'newselect';

The normal behavior may be to say

newSelect.onchange = changeitem;

But this does not really allow you to specify that argument passed in, so instead you may do this:

newSelect.setAttribute('onchange', 'changeitem(this)');

And you are able to set the parameter. If you do it the first way, then the argument you'll get to your onchange function will be browser dependent. The second way seems to work cross-browser just fine.

忆梦 2024-10-24 22:19:48

jQuery 解决方案

如何获取所选选项的文本值

选择元素通常具有您想要访问的两个值
首先是要发送到服务器的,这很简单:

$( "#myselect" ).val();
// => 1

第二个是选择的文本值
例如,使用以下选择框:

<select id="myselect">
  <option value="1">Mr</option>
  <option value="2">Mrs</option>
  <option value="3">Ms</option>
  <option value="4">Dr</option>
  <option value="5">Prof</option>
</select>

如果您想在选择第一个选项(而不仅仅是“1”)时获取字符串“Mr”,您可以按以下方式执行此操作:

$( "#myselect option:selected" ).text();
// => "Mr"  

另请参阅

jQuery solution

How do I get the text value of a selected option

Select elements typically have two values that you want to access.
First there's the value to be sent to the server, which is easy:

$( "#myselect" ).val();
// => 1

The second is the text value of the select.
For example, using the following select box:

<select id="myselect">
  <option value="1">Mr</option>
  <option value="2">Mrs</option>
  <option value="3">Ms</option>
  <option value="4">Dr</option>
  <option value="5">Prof</option>
</select>

If you wanted to get the string "Mr" if the first option was selected (instead of just "1") you would do that in the following way:

$( "#myselect option:selected" ).text();
// => "Mr"  

See also

这对我有帮助。

对于选择:

$('select_tags').on('change', function() {
    alert( $(this).find(":selected").val() );
});

对于单选/复选框:

$('radio_tags').on('change', function() {
    alert( $(this).find(":checked").val() );
});

This is helped for me.

For select:

$('select_tags').on('change', function() {
    alert( $(this).find(":selected").val() );
});

For radio/checkbox:

$('radio_tags').on('change', function() {
    alert( $(this).find(":checked").val() );
});
怪我太投入 2024-10-24 22:19:48

你可以尝试下面的代码

<select onchange="myfunction($(this).val())" id="myId">
    </select>

You can try bellow code

<select onchange="myfunction($(this).val())" id="myId">
    </select>
陪你到最终 2024-10-24 22:19:48

html模板:

<select class="staff-select">
   <option value="">All</option>
   <option value="196">Ivan</option>
   <option value="195">Jon</option>
</select>

Js代码:

const $staffSelect = document.querySelector('.staff-select')

$staffSelect.onchange = function () {
  console.log(this.value)
}

Html template:

<select class="staff-select">
   <option value="">All</option>
   <option value="196">Ivan</option>
   <option value="195">Jon</option>
</select>

Js code:

const $staffSelect = document.querySelector('.staff-select')

$staffSelect.onchange = function () {
  console.log(this.value)
}
深爱成瘾 2024-10-24 22:19:48

您只能使用“this.value”发送值

function getComboA(selectObjectValue) {
   console.log(selectObjectValue);
}

<select id="comboA" onchange="getComboA(this.value)">
   <option value="">Select combo</option>
   <option value="Value1">Text1</option>
   <option value="Value2">Text2</option>
   <option value="Value3">Text3</option>
</select>

You can send only value with 'this.value'

function getComboA(selectObjectValue) {
   console.log(selectObjectValue);
}

<select id="comboA" onchange="getComboA(this.value)">
   <option value="">Select combo</option>
   <option value="Value1">Text1</option>
   <option value="Value2">Text2</option>
   <option value="Value3">Text3</option>
</select>
我们只是彼此的过ke 2024-10-24 22:19:48

以防万一有人正在寻找 React 解决方案而无需下载附加依赖项,您可以编写:

<select onChange={this.changed(this)}>
   <option value="Apple">Apple</option>
   <option value="Android">Android</option>                
</select>

changed(){
  return e => {
    console.log(e.target.value)
  }
}

确保在构造函数中绑定 Changed() 函数,如下所示:

this.changed = this.changed.bind(this);

Just in case someone is looking for a React solution without having to download addition dependancies you could write:

<select onChange={this.changed(this)}>
   <option value="Apple">Apple</option>
   <option value="Android">Android</option>                
</select>

changed(){
  return e => {
    console.log(e.target.value)
  }
}

Make sure to bind the changed() function in the constructor like:

this.changed = this.changed.bind(this);
余厌 2024-10-24 22:19:48

一旦我编写了这段代码,只是为了解释 select 的 onChange 事件,您可以将此代码保存为 html 并查看其工作原理的输出。并且很容易理解。

<html>
    <head>
        <title>Register</title>
    </head>
    <body>
    <script>
        function show(){
            var option = document.getElementById("category").value;
            if(option == "Student")
                  {
                        document.getElementById("enroll1").style.display="block";
                  }
            if(option == "Parents")
                  {
                        document.getElementById("enroll1").style.display="none";
                  }
            if(option == "Guardians")
                  {
                        document.getElementById("enroll1").style.display="none";
                  }
        }
    </script>
            <form action="#" method="post">
                <table>
                    <tr>
                        <td><label>Name </label></td>
                        <td><input type="text" id="name" size=20 maxlength=20 value=""></td>
                    </tr>
                    <tr style="display:block;" id="enroll1">
                        <td><label>Enrollment No. </label></td>
                        <td><input type="number" id="enroll" style="display:block;" size=20 maxlength=12 value=""></td>
                    </tr>
                    <tr>
                        <td><label>Email </label></td>
                        <td><input type="email" id="emailadd" size=20 maxlength=25 value=""></td>
                    </tr>
                    <tr>
                        <td><label>Mobile No. </label></td>
                        <td><input type="number" id="mobile" size=20 maxlength=10 value=""></td>
                    </tr>
                    <tr>
                        <td><label>Address</label></td>
                        <td><textarea rows="2" cols="20"></textarea></td>
                    </tr>
                    <tr >
                        <td><label>Category</label></td>
                        <td><select id="category" onchange="show()">    <!--onchange show methos is call-->
                                <option value="Student">Student</option>
                                <option value="Parents">Parents</option>
                                <option value="Guardians">Guardians</option>
                            </select>
                        </td>
                    </tr>
                </table><br/>
            <input type="submit" value="Sign Up">
        </form>
    </body>
</html>

this code once i write for just explain onChange event of select you can save this code as html and see output it works.and easy to understand for you.

<html>
    <head>
        <title>Register</title>
    </head>
    <body>
    <script>
        function show(){
            var option = document.getElementById("category").value;
            if(option == "Student")
                  {
                        document.getElementById("enroll1").style.display="block";
                  }
            if(option == "Parents")
                  {
                        document.getElementById("enroll1").style.display="none";
                  }
            if(option == "Guardians")
                  {
                        document.getElementById("enroll1").style.display="none";
                  }
        }
    </script>
            <form action="#" method="post">
                <table>
                    <tr>
                        <td><label>Name </label></td>
                        <td><input type="text" id="name" size=20 maxlength=20 value=""></td>
                    </tr>
                    <tr style="display:block;" id="enroll1">
                        <td><label>Enrollment No. </label></td>
                        <td><input type="number" id="enroll" style="display:block;" size=20 maxlength=12 value=""></td>
                    </tr>
                    <tr>
                        <td><label>Email </label></td>
                        <td><input type="email" id="emailadd" size=20 maxlength=25 value=""></td>
                    </tr>
                    <tr>
                        <td><label>Mobile No. </label></td>
                        <td><input type="number" id="mobile" size=20 maxlength=10 value=""></td>
                    </tr>
                    <tr>
                        <td><label>Address</label></td>
                        <td><textarea rows="2" cols="20"></textarea></td>
                    </tr>
                    <tr >
                        <td><label>Category</label></td>
                        <td><select id="category" onchange="show()">    <!--onchange show methos is call-->
                                <option value="Student">Student</option>
                                <option value="Parents">Parents</option>
                                <option value="Guardians">Guardians</option>
                            </select>
                        </td>
                    </tr>
                </table><br/>
            <input type="submit" value="Sign Up">
        </form>
    </body>
</html>
东走西顾 2024-10-24 22:19:48
function setMyValue(v) {
  console.log(v);
}
<select onchange="setMyValue(this.value)">
  <option value="a">1</option>
  <option value="b">2</option>
  <option value="c">3</option>
</select>

function setMyValue(v) {
  console.log(v);
}
<select onchange="setMyValue(this.value)">
  <option value="a">1</option>
  <option value="b">2</option>
  <option value="c">3</option>
</select>

黑凤梨 2024-10-24 22:19:48

这对我有用 onchange = setLocation($(this).val())

这里。

    @Html.DropDownList("Demo", 
new SelectList(ViewBag.locs, "Value", "Text"), 
new { Class = "ddlStyle", onchange = "setLocation($(this).val())" });

This worked for me onchange = setLocation($(this).val())

Here.

    @Html.DropDownList("Demo", 
new SelectList(ViewBag.locs, "Value", "Text"), 
new { Class = "ddlStyle", onchange = "setLocation($(this).val())" });
上课铃就是安魂曲 2024-10-24 22:19:48

简单地:

function retrieve(){
alert(document.getElementById('SMS_recipient').options[document.getElementById('SMS_recipient').selectedIndex].text);
}

function retrieve_other() {
  alert(myForm.SMS_recipient.options[document.getElementById('SMS_recipient').selectedIndex].text);
}

function retrieve() {  alert(document.getElementById('SMS_recipient').options[document.getElementById('SMS_recipient').selectedIndex].text);
}
<HTML>
<BODY>
  <p>RETRIEVING TEXT IN OPTION OF SELECT </p>
  <form name="myForm" action="">
    <P>Select:
      <select id="SMS_recipient">
        <options value='+15121234567'>Andrew</option>
          <options value='+15121234568'>Klaus</option>
      </select>
    </p>
    <p>
      <!-- Note: Despite the script engine complaining about it the code works!-->
      <input type="button" onclick="retrieve()" value="Try it" />
      <input type="button" onclick="retrieve_other()" value="Try Form" />
    </p>
  </form>
</HTML>
</BODY>

输出:
Klaus 或 Andrew 取决于 selectedIndex 是什么。如果您需要该值,只需将 .text 替换为值即可。但是,如果它只是您想要的值(而不是选项中的文本),则使用 document.getElementById('SMS_recipient').value

Simply:

function retrieve(){
alert(document.getElementById('SMS_recipient').options[document.getElementById('SMS_recipient').selectedIndex].text);
}

function retrieve_other() {
  alert(myForm.SMS_recipient.options[document.getElementById('SMS_recipient').selectedIndex].text);
}

function retrieve() {  alert(document.getElementById('SMS_recipient').options[document.getElementById('SMS_recipient').selectedIndex].text);
}
<HTML>
<BODY>
  <p>RETRIEVING TEXT IN OPTION OF SELECT </p>
  <form name="myForm" action="">
    <P>Select:
      <select id="SMS_recipient">
        <options value='+15121234567'>Andrew</option>
          <options value='+15121234568'>Klaus</option>
      </select>
    </p>
    <p>
      <!-- Note: Despite the script engine complaining about it the code works!-->
      <input type="button" onclick="retrieve()" value="Try it" />
      <input type="button" onclick="retrieve_other()" value="Try Form" />
    </p>
  </form>
</HTML>
</BODY>

Output:
Klaus or Andrew depending on what the selectedIndex is. If you are after the value just replace .text with value. However if it is just the value you are after (not the text in the option) then use document.getElementById('SMS_recipient').value

筑梦 2024-10-24 22:19:48
 //html code
   <select onchange="get(this)">
      <option value="a">1</option>
      <option value="b">2</option>
      <option value="c">3</option>
    </select>

//javscript code
   function get(select) {
      let value = select.value;  
      console.log(value);
    }
    
 //html code
   <select onchange="get(this)">
      <option value="a">1</option>
      <option value="b">2</option>
      <option value="c">3</option>
    </select>

//javscript code
   function get(select) {
      let value = select.value;  
      console.log(value);
    }
    
满身野味 2024-10-24 22:19:48

我认为现在附加事件处理程序的首选方法(而不是 onchange= 属性)是

document.querySelector('whatever').addEventListener('change', (event) => {
   const theValue = event.target.value;
})

I would think the preferred way to attach the event handler now (instead of onchange= attribute) is

document.querySelector('whatever').addEventListener('change', (event) => {
   const theValue = event.target.value;
})
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文