2017-08-31 79 views
0

我從Django中的查詢集創建了一個CustomChoiceField,並使用自定義標籤將每個對象的名稱,url和aspect屬性傳遞到標籤中。下面是從forms.py相關代碼:使用jQuery從Django Radioselect表單獲取標籤的屬性

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看起來不錯。問題是,我需要方面屬性(當前標籤中的值屬性)才能觸發後續的JavaScript函數(cropper.js寬高比)。我怎樣才能獲得在Javascript中的方面的價值?

編輯:

只是要清楚,我一直在尋找一種方式來獲得該類從表單標籤。

回答

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; 
    } 
}); 

然後我可以通過cropAspectcropper.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); 
    } 
});