使用JQuery从Django Radioselect表单获取Label的属性

时间:2017-08-31 14:44:59

标签: javascript jquery django forms

我在Django的查询集中创建了一个CustomChoiceField,其自定义标签将每个对象的name,url和aspect属性传递给标签。以下是forms.py的相关代码:

class CustomChoiceField(forms.ModelChoiceField):
    def label_from_instance(self, obj):
        return mark_safe("<span class='%s'>%s</span><img src='%s' class='teams__filter__image'/>" % (obj.aspect, obj.name, obj.image.url))

filter_pic = CustomChoiceField(required=False, label=mark_safe('Image Filter'), widget=forms.RadioSelect(attrs={'id':'filter-choice'}), queryset=FilterPic.objects.filter(activated=True), empty_label='None')

它以HTML格式呈现:

<p class="teams__form__label">Image Filter</p>
<p><label for="filter-choice_0"><input checked="checked" id="filter-choice_0" name="filter_pic" type="radio" value="" /> None</label></p>
<p><label for="filter-choice_1"><input id="filter-choice_1" name="filter_pic" type="radio" value="2" /> <span class='0.7'>WeHealth Orange</span><img src='/media/images/2017/08/28/orangefilter.png' class='teams__filter__image'/></label></p>
<p><label for="filter-choice_2"><input id="filter-choice_2" name="filter_pic" type="radio" value="1" /> <span class='0.7'>WeHealth Blue</span><img src='/media/images/2017/08/28/bluefilter.png' class='teams__filter__image'/></label></p>

HTML中的一切看起来都很棒。问题是,我需要 aspect 属性(当前标签中的value属性)才能触发后续的Javascript函数(cropper.js宽高比)。如何在Javascript中获取方面值?

修改

为了清楚起见,我正在寻找一种从表格中获取标签类的方法。

1 个答案:

答案 0 :(得分:0)

当用户选择无线电选择时,我最终创建了一个触发器:

$('input:radio[name="filter_pic"]').change(function() {

然后我确定了该选项的id并找到了下一个元素的class(因为纵横比被传递到该元素的类中):

var idVal = $(this).attr("id");
var aspectClass = $("input[id='"+idVal+"']").next().attr("class");

最后,我将cropAspect设置为等于该类或默认值为2.0:

if (aspectClass) {
    cropAspect = aspectClass;
} else {
    cropAspect = 2;
}

以下完整代码:

$('input:radio[name="filter_pic"]').change(function() {
    var idVal = $(this).attr("id");
    var aspectClass = $("input[id='"+idVal+"']").next().attr("class");
    if (aspectClass) {
        cropAspect = aspectClass;
    } else {
        cropAspect = 2;
    }
});

然后,我可以将cropAspect传递给cropper.js,如下所示:

$image.cropper({
    viewMode: 1,
    aspectRatio: cropAspect,
    minCropBoxWidth: 200,
    minCropBoxHeight: 200,
    rotatable: true,
    scalable: true,
    checkOrientation: true,
    ready: function () {
        $image.cropper("setCanvasData", canvasData);
        $image.cropper("setCropBoxData", cropBoxData);
    }
});