【问题标题】:Identifying HTML dropdown selection in jQuery识别 jQuery 中的 HTML 下拉选择
【发布时间】:2020-10-16 08:58:17
【问题描述】:

我有我的 html 代码:

<form>
  <input type="radio" id="pan" class="radioButton" value="pan">
  <label for="pan">PAN</label>
  <input type="radio" id="singleColor" class="radioButton" value="singleColor">
  <label for="singleColor"> 
       <span>
           <select name="imageColor">
               <option value="red" selected="selected">Red</option>
               <option value="red">Green</option>
               <option value="red">Blue</option>
           </select>
       </span>
    </label>
</form>

我想要做的是具有当用户选择单色单选按钮时的功能 - 下拉列表中的选择是图像颜色的选择。所以,最初红色在开始时就在那里,所以如果我只是点击单选按钮,那么它会抓取红色图像。如果我从下拉列表中选择“蓝色”,那么该值将被传递,它会抓取一张蓝色图像。我计划为此使用 ajax,我只是好奇如何设置 jQuery 来读取它。例如:

$("#singleColor").on('click', function() {
   
    if(selected === "red") {
       //Ajax code to call red image in
    }
    if(selected === "blue") {
       //Ajax code to call blue image in
    }
    $("#singleColor").change(function() {
       //identify the current value (i.e. Red, Blue, or Green)
       //Call Ajax for what ever is selected
});

类似于上面的东西。我只是不知道如何传递代码中选择的内容,以便能够根据用户选择来识别要调用的 @RequestMapping。

如果我没有正确解释这一点,请告诉我,我很乐意深入了解。

谢谢!

【问题讨论】:

  • 选择元素的值(JavaScript:.value,jQuery:.val())会告诉你当前选择了什么。

标签: javascript html jquery


【解决方案1】:

您需要将每个options 的value 设置为颜色名称,然后您可以使用$("#imageColor").val() 来获取所选选项的值。请注意,您无需将 select 包装在 labelspan 中,因为这不会做任何事情。

$("#imageColor").change(function(e){
  console.log($(this).val());
  switch($(this).val()){
    case "red":
      //Ajax code to call red image in
      break;
    case "blue":
      //Ajax code to call blue image in
      break;
    case "green":
      //Ajax code to call green image in
      break;
  }
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form>
  <input type="radio" id="pan" class="radioButton" value="pan">
  <label for="pan">PAN</label>
  <input type="radio" id="singleColor" class="radioButton" value="singleColor">
     <select id="imageColor">
         <option value="red" selected="selected">Red</option>
         <option value="green">Green</option>
         <option value="blue">Blue</option>
     </select>
</form>

【讨论】:

    猜你喜欢
    • 2021-04-06
    • 1970-01-01
    • 2014-05-26
    • 1970-01-01
    • 2011-05-20
    • 1970-01-01
    • 2012-06-11
    • 2016-04-05
    • 1970-01-01
    相关资源
    最近更新 更多