简体   繁体   English

如何从模板中的循环选择中获取价值?

[英]How can I get value from loop select in template?

I wan to get value of item price in js for every select what would be my jquery function?我想为每个选择在 js 中获取项目价格的值我的 jquery 函数是什么?

                        {% for package in packages %}
                            <div class="form-group col-md-6">
                                <label for="bedrooms">{{ package.title }}<span style="color: red;">*</span></label>
                                <select class="form-control input-dsn" required id="bedrooms" name="package_{{ package.id }}" onChange="document.getElementByName('package_{{ package.id }}').value = this.value;">

                                    {% for item in package.item_set.all %}
                                        <option  value="{{ item.id }}" data-item-value="{{ item.price }}">{{ item.title }}</option>
                                    {% endfor %}

                                </select>
                            </div>
                        {% endfor %}

This will (I think) iterate over all the options calling a function on each one.这将(我认为)遍历所有选项,在每个选项上调用一个函数。

$(document).ready(function() {
    $("#bedrooms option").each(function() {
        $(this).attr("data-item-value") // is the value you want    
    });
});

Personally I tend to "cheat" and include small JQuery scriptlets in my template where Django can substitute the values I want.就我个人而言,我倾向于“作弊”并在我的模板中包含小的 JQuery 脚本,Django 可以在其中替换我想要的值。 The only thing you have to remember is that certain whitespaces become significant.您唯一需要记住的是某些空格变得重要。 { { is JS. { {是 JS。 {{ is going to cause the Django template engine to get indigestion! {{会导致 Django 模板引擎消化不良!

var option_values = [
    {% for item in package.item_set.all %}{{ item.price }}, {%endfor%} ];

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM