获取选定结果的值未定义

问题描述 投票:0回答:1

我有一个带有选项和 ID 的选择。通过一个函数,我试图获取 onClick 函数上此选择的值。在函数中,我警告数据,但它要么未定义,要么为空。我的选择:

  <select class="form-control" id="labels" onchange="chng()">
                    <option>Extra Label</option>
                    @for (int i = 1; i < 21; i++)
                    {
                        <option>@i</option>
                    }
                </select>

和我的 onClick 函数:

function chng() {
    var selectedValue = document.getElementById('labels').value;
    var v = $('#labels').val();
    alert(v);
    alert(selectedValue);
    var addLabelsBtn = document.getElementById('addLabelsBtn');
    addLabelsBtn.href = '/Amazon/[email protected]&extraLabel=' + selectedValue;

}

我尝试了getElemenyById.val()getElementById 给出 undefined.val() 给出 empty

javascript html jquery razor-pages
1个回答
0
投票

纯 JavaScript,我猜你所说的“按钮”实际上是一个锚标记

<a>
,因为你尝试添加一个 href。

我做了一个控制台日志只是为了显示更改的元素。

const select = document.querySelector('#labels');
select.addEventListener('change', handleChange);

function handleChange(event) {
  const selectedValue = this.value;
  const addLabelsBtn = document.getElementById('addLabelsBtn');
  addLabelsBtn.href = '/Amazon/[email protected]&extraLabel=' + selectedValue;
  console.log(addLabelsBtn);
}
.button {
  display: inline;
  width: 10em;
  height: 2em;
  background-color: #4E9CAF40;
  padding: 0.625em;
  text-align: center;
  border-radius: 1em;
  color: #0000ff;
  font-weight: bold;
  text-decoration: none;
}
<select class="form-control" id="labels">
  <option>Extra Label</option>
  <option>1</option>
  <option>2</option>
  <option>3</option>
  <option>4</option>
  <option>5</option>
  <option>6</option>
  <option>7</option>
  <option>8</option>
  <option>9</option>
  <option>10</option>
  <option>11</option>
  <option>12</option>
  <option>13</option>
  <option>14</option>
  <option>15</option>
  <option>16</option>
  <option>17</option>
  <option>18</option>
  <option>19</option>
  <option>20</option>
</select>

<a class="button" id="addLabelsBtn">Howdy</a>

© www.soinside.com 2019 - 2024. All rights reserved.