如何使用javascript从选择框访问多个值?

时间:2018-04-17 10:05:19

标签: javascript html

如何使用javascript在两个变量中获取value1和value2的值?

    <select class="form-control"  id="country" name="country"> 

    <option  value="**value1**" "**value2**" >Select Item</option>

    </select>

3 个答案:

答案 0 :(得分:0)

您可以创建自己的属性。我知道你可能不想获得带有ID的元素,但我不知道上下文。您可以在选项上调用getAttribute,并使用您为&#34; custom&#34;提供的任何名称。属性。

&#13;
&#13;
window.addEventListener('load', ()=>
{
  const option = document.getElementById('option');
  function init()
  {
    //Use this to get the values
    console.log(option.getAttribute('other-value'));
  }
  
  init();
});
&#13;
<select class="form-control"  id="country" name="country"> 
  <option id="option" value="value1" other-value="value2">Select Item</option>
</select>
&#13;
&#13;
&#13;

答案 1 :(得分:0)

我不知道你真正想用你的代码做什么,
但这是使用option元素的正确方法,以及使用固定分隔符分割多个值的方法:

&#13;
&#13;
var example = document.getElementById('example');
example.addEventListener('change', function() {
  // Console displays the “value”, and not the text, of the selected option
  console.log("option value:", example.value);
});


// Here is what I'll do with your "multiple" values
var country = document.getElementById('country');
var options = country.querySelector('option');
var values = options.value.split("/");

values.forEach(function(val) {
  country.innerHTML += "<option value=" + val + ">" + val + "</option>";
});
&#13;
<p>My simple example</p>
<select id="example" name="country"> 
    <option value="--">Select Country</option>
    <option value="GB">Great Britain</option>
    <option value="FR">France</option>
</select>
<br>
<br>
<p>Example with option getting splitted</p>
<select class="form-control" id="country" name="country">
    <!-- Let's say your multiple values are separated by a "/" -->
    <option value="**value1**/**value2**">Select Item</option>
</select>
&#13;
&#13;
&#13;

希望它有所帮助。

答案 2 :(得分:0)

 $('select').on('change', function() {
      console.log( $('#country').val() );
    console.log($(this).find(':selected').data('second'));
      
    });
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
    <select class="form-control"  id="country" name="country"> 

            <option  value="value1" data-second ="value2" >Select Item 1</option>
           <option  value="value3" data-second ="value4" >Select Item 2</option>

            </select>