drzip28288 2017-03-16 07:50
浏览 605
已采纳

如何在form.serialize中获取下拉值和文本?

In my project I want the serialize data of the form, but for the dropdowns it gives the values only not a text of that selected value of drop down.

<select name='attend'>
    <option value="1" selected="selected">Question</option>
    <option value="2">Attending</option>
    <option value="3">not-attending</option>
</select>

Here it gives attend = 1. I also want the text of that selected option that is "Question".

  • 写回答

1条回答 默认 最新

  • doujie9882 2017-03-16 07:52
    关注

    serialize() will only retrieve the name and value properties from an element.

    To do what you require you can use serialize() as normal, then append the selected option text to it:

    var data = $('form').serialize() + '&attendText=' + $('select option:selected').text();
    
    console.log(data);
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
    <form>
      <select name='attend'>
        <option value="1" selected="selected">Question</option>
        <option value="2">Attending</option>
        <option value="3">not-attending</option>
    </select>
    </form>

    If you wanted to use serializeArray() you would need to push() the data to the resulting object, like this:

    var data = $('form').serializeArray();
    data.push({ 
      name: 'attendText',
      value: $('select option:selected').text() 
    });
    
    console.log(data);
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
    <form>
      <select name='attend'>
        <option value="1" selected="selected">Question</option>
        <option value="2">Attending</option>
        <option value="3">not-attending</option>
    </select>
    </form>

    </div>
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥30 软件自定义无线电该怎样使用
  • ¥15 R语言mediation包做中介分析,直接效应和间接效应都很小,为什么?
  • ¥15 Jenkins+k8s部署slave节点offline
  • ¥15 微信小游戏反编译后,出现找不到分包的情况
  • ¥15 如何实现从tello无人机上获取实时传输的视频流,然后将获取的视频通过yolov5进行检测
  • ¥15 WPF使用Canvas绘制矢量图问题
  • ¥15 用三极管设计一个单管共射放大电路
  • ¥15 孟德尔随机化r语言运行问题
  • ¥15 pyinstaller编译的时候出现No module named 'imp'
  • ¥15 nirs_kit中打码怎么看(打码文件是csv格式)