如何在选项标签中添加隐藏输入类型?

时间:2017-09-06 03:27:16

标签: javascript jquery asp.net-mvc

  function vGetUsers(elem, id) {
  var cat = $("#cat" + elem).val();
  var xstr = "";
  debugger;
  $.ajax({
  url: '/ApplicationNew/getAllUsers',
  type: 'POST',
  data: { 'Cat': cat },
  dataType: 'json',
  async: false,
  success: function (b) {
      for (x = 0; x < b.length; x++) {

      xstr = xstr + '<option value="' + b[x].UserName + '">' + b[x].FirstName + ' ' + b[x].MiddleInitial + ' ' + b[x].LastName + '</option>'(HERE IS WHERE I WANT TO PLACE THE INPUT TYPE HIDDEEN IS THIS POSIBLE?[enter image description here][1]);
                }
      localStorage.removeItem('vUsers'); //tracked0629
      localStorage.setItem('vUsers', xstr);
            }
        });
    }

当我将<input type="hidden" id="userName' + id + '" value="' + b[x].UserName + '" hidden/>放在选项标签内时会发生什么。

2 个答案:

答案 0 :(得分:0)

用我的例子来解决你的任务:

<html>
    <head>
        <script src="jquery.min.js"></script>
    <head>
    <body>
        <select>
            <option value="1" hidden-attr="hidden attr for 1">Option 1</option>
            <option value="2" hidden-attr="hidden attr for 2">Option 2</option>
            <option value="3" hidden-attr="hidden attr for 3">Option 3</option>
            <option value="4" hidden-attr="hidden attr for 4">Option 4</option>
            <option value="5" hidden-attr="hidden attr for 5">Option 5</option>
            <option value="6" hidden-attr="hidden attr for 6">Option 6</option>
        </select>
        <script>
                $("select").change(function(){
                    var val = $(this).find("option:selected").val();
                    var hidden = $(this).find("option:selected").attr("hidden-attr");
                    alert ("Value: " + val + ", hidden attribute:" + hidden);
                })
        </script>
    </body>
</html>

答案 1 :(得分:0)

而不是隐藏字段,您可以添加这样的额外属性并保留额外的值。

 $('select').change(function(){
       var selected = $(this).find('option:selected');
       var imageSrc = selected.data('image'); 
       alert(imageSrc);
    
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select id="select">
  <option value="1" data-image="image1">A</option>
  <option value="2" data-image="image2">B</option>
  <option value="3" data-image="image3">C</option>
</select>