【问题标题】:Cannot read value form <selected> element with JQuery/Javascript无法使用 JQuery/Javascript 读取表单 <selected> 元素的值
【发布时间】:2014-11-05 06:04:55
【问题描述】:

我无法获取表单元素的值,即使从其他类似的问题中这应该可以工作。

仅供参考 - 我有一个函数可以将 2 个 ID(#selected_sign 和 #selected_sign_form)写入一篇文章和一个嵌套在文章中的表单 - 这纯粹是为了样式/识别目的。

以下是无法根据分配的 ID 获取元素值的函数:

var sSize_prices= new Array();
sSize_prices["45"]=45; //per sq ft
sSize_prices["60"]=65; //per sq ft

function getSizePrice() {
var getSizePrice=0;

var theForm = document.forms["selected_sign_form"];
var selectedSize = theForm.elements["os0"];
alert(selectedSize.value);

getSizePrice = sSize_prices[selectedSize.value];

return getSizePrice;
}

这是包含 ID 文章和表单的 HTML 标记:

<section class="sign_type">
    <h3>Selection</h3>
    <article class="signs" onclick="calculateTotal()" id="selected_sign">
      <figure class="sample">
        <a href="/cat/s1b.png" rel="lightbox" title="Sign preview">
          <img class="sign_preview" src="/cat/s1.png" alt="Sign preview" title="Sign preview" />
        </a>
      </figure>
      <form action="" class="options" onsubmit="return false;" id="selected_sign_form">
        <div class="sign_option1"><label class="on0">Size:</label>
          <select name="Size" class="os0" onclick="calculateTotal()">
            <option value="45">45cm sq</option>
            <option value="60">60cm sq</option>
          </select>
        </div>
        <div class="sign_option2"><label class="on1">Qty:</label>
          <input name="Quantity" class="os1" value="1" onkeyup="calculateTotal()" />
        </div>
        <div class="sign_option3"><label class="on2">Fine:</label>
          <input name="Custom" class="os2" value="" />
        </div>
      </form>
      <div class="price"></div>
    </article>
</section>

【问题讨论】:

  • 我认为您不能像这样分配数组值:sSize_prices["45"]=45;。在 JavaScript 中,您只能按数字访问数组索引。如果你想要现在的方式,你需要使用Object
  • 那纯粹是对照数组检查 值以找到相应的“价格”。它工作得很好,特别是对于每个选项具有不同定价的大型选项数组。

标签: jquery forms select element


【解决方案1】:

您可以使用 jQuery 来完成。你可以使用不同的jQuery Selector,使用'id'选择器获取表单元素,使用.find()获取选择元素。

var sSize_prices= new Array();
sSize_prices["45"]=45; //per sq ft
sSize_prices["60"]=65; //per sq ft

function getSizePrice() {
var getSizePrice=0;

var selectBox= $("#selected_sign_form").find(".os0:first");
alert($(selectBox).val());

getSizePrice = sSize_prices[$(selectBox).val()];

return getSizePrice;
}

注意 - 请在script 之前包含 jquery 库。要包含 jquery 库,请参阅this

【讨论】:

    【解决方案2】:

    您的代码很好,只需要对 HTML 进行小修改。

    以下行在表单中寻找一个元素,其属性“name”等于“os0”:

    theForm.elements["os0"];
    

    如果您将“选择”标签的名称设置为“os0” - 它会起作用。

    E.G.

    <select name="os0" class="os0" onclick="calculateTotal()">
    

    【讨论】:

    • 这也很完美,而且是更有效的解决方案。谢谢!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-08-23
    • 2015-12-04
    • 1970-01-01
    • 1970-01-01
    • 2011-10-05
    • 1970-01-01
    相关资源
    最近更新 更多