根据选择表单将不同的值插入隐藏的输入字段

时间:2019-06-26 02:44:20

标签: javascript html forms

我需要基于从选择表单中选择的内容,将值“折扣”插入到隐藏的输入字段中。如果选择了选项2、3或4,则应插入该值;如果选择1,则将隐藏的输入值保留为空。

我需要保留当前的选项值,因为它们也会被使用

from django.contrib import admin
from django.core.exceptions import ValidationError
from .models import Question
from django import forms


class QuestionForm(forms.ModelForm):
    model = Question

    def clean(self):
        cleaned_data = super().clean()
        if cleaned_data.get('other_answers').count() != 3:
            raise ValidationError('You have to choose exactly 3 answers for the field Other Answers!')


@admin.register(Question)
class QuestionAdmin(admin.ModelAdmin):
    form = QuestionForm

1 个答案:

答案 0 :(得分:0)

一种实现此目标的方法是使用以下脚本:

/* Attach a "change" event listener where the value of "myhidden" 
will be updated based on the selected option in "myselect" */
document.getElementById('myselect').addEventListener('change', (event) => {

  /* Get the current value of "myselect" as well as the hidden element */
  const mySelectValue = event.currentTarget.value;
  const hiddenElement = document.getElementById('myhidden');

  if (mySelectValue === '1') {
    /* If value of "myselect" is 1 then clear value of hidden element */
    hiddenElement.value = '';
  } else {
    /* Otherwise assign the value of "discount" to the hidden element */
    hiddenElement.value = 'discount';
  }

  console.log(`hiddenElement.value updated to ${hiddenElement.value}`);
});
<div class="form-group">
  <div class="form-inline">
    <select id="myselect" name="quantity">
      <option value="1" selected="selected">1</option>
      <option value="2">2</option>
      <option value="3">3</option>
      <option value="4">4</option>
    </select>
    <input type='hidden' id='myhidden' value=''>
  </div>
</div>