JQuery – select 변경 form sumbit

select box 값을 변경하면 자동으로 form submit() 해 버리고 싶은데, 어떻게 하나요? 엄청 간단하게 알려주세요. 🙂

[
How to Submit Form on Select Change
I have the following form. I’d like it to be submitted automatically via jQuery when the user makes a selection, without needing to press the submit button. How do I do this? <form action=”″ me…
![](assets/images/2023/02/apple-touch-icon@2.png?ssl=1)
](https://stackoverflow.com/questions/28122019/how-to-submit-form-on-select-change)

정답은 아래 코드를 참고하세요

$(document).ready(function() {  $('#선택박스아이디').on('change', function() {     document.forms[myFormName].submit();  });});// 혹은$(document).ready(function() {   $('#선택박스아이디').change(function() {     var parentForm = $(this).closest("form");     if (parentForm && parentForm.length > 0)       parentForm.submit();   });});

쉽죠 끝.

on(‘change’) vs .change()

참고로 이벤트 등록을 2가지 형태로 할 수 있는데, 머가 맞는거니?

둘다 맞는데, 머 정답이라기 보다는 그냥 on(이벤트, function() {}); 형태로 사용하는 것을 강권합니다.

[
JQuery 클릭 이벤트 on(“click”) 과 click() 의 차이
JQuery on(“click”)과 click() on(“click”) 과 click() 의 차이점은 동적으로 이벤트를 바인딩할 수 있는지의 차이다. on(“click”)은 동적으로 가능하고 click()은 최초에 선언된 element에만 동작한다. 아래 예..
![](assets/images/2023/02/opengraph.png?ssl=1)
](https://lookingfor.tistory.com/entry/JQuery-%ED%81%B4%EB%A6%AD-%EC%9D%B4%EB%B2%A4%ED%8A%B8-onclick-%EA%B3%BC-click-%EC%9D%98-%EC%B0%A8%EC%9D%B4)

동적으로 생성된 요소의 경우 이벤트도 발생하게 하려면 on 을 써야 한다네요. 진짜끝

Django – ForeignKey display text 변경하기

modelforms 에서 자동으로 값을 가져오긴 하는데 __str__ 에 정의된 글자나 키 값을 기본으로 보여준다. 부가적으로 정보를 더 보여주고 싶은데 __str__ 을 바꾸면 전체에 이 모델을 접근하는 부분이 다 바뀌므로, 딱 combo에 올라가는 글자만 변경하고 싶다면,

label_from_instance 속성을 건드리면 된다.

자세한 설명은 아래 링크를 참고해 보시고,
How to change ForeignKey display text in the Django Admin?

예제 코드를 살펴보면,

subform.fields["product_profile"].queryset = get_user_productprofile(companyid=_companyid, is_superuser=_superuser).order_by("name")subform.fields["product_profile"].label_from_instance = lambda obj: "%s(%s)" % (obj.name, obj.product.name)

queryset 을 통해 필터링 결과를 넣어 줄 수 있고

label_from_instance 통해 display text 를 변경할 수 있다. 예제에서 필드명(상품명) 상태로 보이도록 수정한 버전이다.

![](assets/images/2023/02/4_image.png?resize=183%2C121&ssl=1)

참고 사이트

  • 람다 lambda 를 사용하고 있는데, 관련 기초 정보는 여기를 가보세요.
[
3.5 람다(lambda)
오늘은 람다 형식과 그것을 이용하는 여러 가지 함수들에 대해서 알아보겠습니다. 당장 완벽하게 소화하실 필요는 없을 것 같구요, 가벼운 마음으로 이런 것이 있다는 정도만 아셔 …
![](assets/images/2023/02/chobo_python_title.png?ssl=1)
](https://wikidocs.net/64)

Django model.forms 사용자 필드 추가

model form에서 추가로 별도의 사용자 필드를 추가하고 싶다면, 아래처럼 추가로 forms.필드타입 으로 선언해서 사용하면 된다.

label, widget 용례도 참고해 보면 좋다. required=False 도 옵션으로 주면, 필수 항목으로 추가 되지 않는다.

class FirmwareForm(forms.ModelForm):    is_fileinclue = "enctype=multipart/form-data"    autogen = forms.BooleanField(label=_("중복시 자동변경"), widget=forms.CheckboxInput(attrs={"class": "form-check-input", "type": "checkbox"}), required=False)        class Meta:        model = Firmware        fields = ["company", "dtype", "content"]        labels = {            "company": _("*회사"),            "dtype": _("타입"),            "content": _("파일"),        }        widgets = {            "company": forms.Select(attrs={"class": "form-select"}),            "dtype": forms.Select(attrs={"class": "form-select", "required": True, "placeholder": "타입"}),            # "content": forms.FileInput(attrs={"class": "form-control", "style":"width: 100px;"}),            # "content": forms.FileField('첨부 파일', upload_to='uploads/'),        }

사용할 때는 일반 필드와 동일하다.

if form.cleaned_data["autogen"]:

이런 식으로 값을 바로 보면 된다.

참고 사이트

예제 코드를 볼 수 있다. Django Forms BooleanField 예제 코드들

class CopyPermissionForm(forms.Form):    """    Holds the specific field for permissions    """    copy_permissions = forms.BooleanField(        label=_('Copy permissions'),        required=False,        initial=True,    )
[
django.forms BooleanField Python Code Examples
Python code examples to show how to use the BooleanField class within the forms module of the Django open source project.
![](assets/images/2023/02/default.jpg?ssl=1)
](https://www.fullstackpython.com/django-forms-booleanfield-examples.html)