代码之家  ›  专栏  ›  技术社区  ›  Dan382

使用jquery更改表单值

  •  1
  • Dan382  · 技术社区  · 7 年前

    我想找到每一个 “.简单产品磁贴” 在一个页面上,然后对于每个附加部分的ref(url末尾的产品代码)到最近的表单值,默认情况下该值为空。

    HTML:

    <div class="simple-product-tile">
    
        <!-- I need the product code at the end of the href 'demo2xx' -->
        <a href="/demo-product-demo2xx"></a>
        <form action="/basket/addproduct" id="product-form" method="post">
            <div class="tbx tbx-quantity">
    
                <!-- Append above product code to the empty value -->
                <input id="productId" name="productId" value="" type="hidden">
            </div>
            <button class="btn-add-to-basket" title="Add to basket" type="submit">
                <span class="btn-cnt">Add to basket</span> 
            </button>
        </form>
    </div>
    

    使用一些非常基本的jquery,我可以将每个值更改为示例代码“000000”:

    $(".simple-product-tile form input#productId").each(function() {
        $(this).val('000000');
    });
    

    如何从最近的Href中剪切“demo2xx”,并将其转换为可应用于最近值的变量?

    我以为我可以使用.slice()从Href中剪切出所需的字符串,但是由于产品代码的长度不同,我认为这不再有效。

    1 回复  |  直到 7 年前
        1
  •  1
  •   Himanshu Upadhyay    7 年前

    你可以这样做:

    $(".simple-product-tile").each(function() {
        var url = $(this).find("a").attr("href");  // Taking HREF value.
        var lastItem = url.split("-").pop(-1);    // Taking last part of the string.
        $(this).find("#productId:first").val(lastItem);  // Assigning value to input.
    });
    

    我建议你 productId 页面独有的。因为id在dom上应该是唯一的。我建议你去 class="productId" . 并相应地更改jquery选择器 .productId 而不是 #productId .