如何在jQuery中获取具有可变ID的值?

时间:2018-10-31 11:52:18

标签: jquery django-templates

function addDictToCookie(id) {
    var name = $("#" + id + "input[id = material_name]").val();
    var unit = $("#" + id + "select[id = material_unit] :selected").text();
    var count = $("#" + id + "input[id = material_count]").val();
    var dict = { "name": name, "unit": unit, "count": count }
    Cookies.set('new', dict, { expires: 0.001 })
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<form action="GET" id="{{material.Id}}">
    <div class="col-sm-5 topbox_insidebox_insideblocks">
        <input type="text" name=Material value="{{material.Id}}" class="in" readonly id="material_name">
    </div>
    <div class="col-sm-2 topbox_insidebox_insideblocks">
        <select id="material_unit">
            <option value="{{material.Volume}}">m^3</option>
        </select>
    </div>
    <div class="col-sm-5 topbox_insidebox_insideblocks">
        <input type="text" name=Value value="{{material.Volume}}" class="in" readonly id="material_count">
    </div>
    <button type="submit" class="btn btn-white topbox_button" id="addToCart" onclick="addDictToCookie('{{material.Id}}')"> Add</button>
</form>

我为django标签使用了<form>变量。现在,我想获取输入值,但定义为var的此函数为null

如何解决这个问题?

1 个答案:

答案 0 :(得分:0)

上面的代码中有一个非常小的错误,就是在连接ID之后使用空格

错误代码:

$("#" + id + "input[id = material_name]").val();

正确的代码:

$("#" + id + " input[id = material_name]").val();

示例: 表单ID为myForm

如果您不使用空格,jQuery将尝试

错误代码:

$("#myForminput[id = material_name]").val();

在上面的示例中,myForminput id在html中不可用,因此它将始终返回undefined

正确的代码:

$("#myForm input[id = material_name]").val();

在下面的示例中,我仅删除了django代码,以便您可以清楚地了解这一点:

function addDictToCookie(id) {
    var name = $("#" + id + " input[id = material_name]").val();
    var unit = $("#" + id + " select[id = material_unit] :selected").text();
    var count = $("#" + id + " input[id = material_count]").val();
    var dict = { "name": name, "unit": unit, "count": count }
    
	console.log(dict)	
  
  return false;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<form id="myForm">
    <div class="col-sm-5 topbox_insidebox_insideblocks">
        <input type="text" name=Material value="Something" class="in" readonly id="material_name">
    </div>
    <div class="col-sm-2 topbox_insidebox_insideblocks">
        <select id="material_unit">
            <option value="Some Value">Some Value</option>
        </select>
    </div>
    <div class="col-sm-5 topbox_insidebox_insideblocks">
        <input type="text" name=Value value="123" class="in" readonly id="material_count">
    </div>
    <button type="submit" class="btn btn-white topbox_button" id="addToCart" onclick="return addDictToCookie('myForm')"> Add</button>
</form>