【问题标题】:How to make js/javascript retrieve the specific html option value inside a django python forloop如何让 js/javascript 在 django python forloop 中检索特定的 html 选项值
【发布时间】:2017-10-26 09:50:16
【问题描述】:

所以我想在我的循环选项值上获取当前选择的选项,但它只会在我按下提交时不断获取循环的最后一个索引。

views.py

def editGrp(request):       
JSONer = {}
parsedData = urlparse.urlparse(request.get_full_path())
pkid = (urlparse.parse_qs(parsedData.query)['pkid'][0])
print(pkid)
groupid = (urlparse.parse_qs(parsedData.query)['groupid'][0])
if User.objects.filter(id=pkid).count() > 0 and Group.objects.filter(id=groupid).count() > 0:
    print(pkid)
    print(groupid)
    userID = User.objects.filter(id=pkid)[0]
    userID.profile.group_id = groupid
    print(userID.username)
    userID.save(force_update=True)
return HttpResponseRedirect(json.dumps(JSONer)) 

我的“admin.html”中的特定代码

循环用于列出不在特定组内的所有用户

<label class="control-label col-md-3 col-sm-3 col-xs-12">Add Members:</label>
<div class="col-md-8 col-sm-6 col-xs-12">
    <select name="employeeName" id="employeeLocation" class="select2_single form-control" tabindex="-1">
    {% for user in users %}
      {% ifnotequal user.profile.group.id groups.id %}
        <option name="userGroup" id="userGroup-{{ user.id }}" value="{{user.id}}">{{user.username}}</option>
      {% endifnotequal %}
    {% endfor %}
    </select>
</div>

admin.html 中的提交按钮

<button type="submit" data-dismiss="modal" onClick="editGrpAjax('userGroup-{{user.id}}', {{groups.id}})" class="btn btn-primary">Save changes</button>

javascript 代码

<script>
    function editGrpAjax(id,groupid){
      var newid = document.getElementById(id).value;
      var newgroupid = document.getElementById('groupid-' + groupid).value;
        $.ajax({url: 'http://127.0.0.1:8000/editGrp/?pkid='+ newid + "&groupid=" + newgroupid, 
            success: function(result){

              // insert success message here
            }
        });
    }
</script>

它不断获取循环的最后一个值,而不是提交时在选项值中当前选择或突出显示的那个。

【问题讨论】:

  • “它不断获取循环的最后一个值”。它是什么”?我想也许你的意思是 editGrpAjax 函数?在那种情况下,这两个sn-ps的代码是如何联系起来的?无法看到调用 editGrpAjax 的任何地方,也看不到传递给它的内容,因此无法说明为什么它可能接收到错误的值。您提到“按提交”,但这也没有显示。我认为您错过了代码中最重要的部分。
  • 是的,忘记添加了,我的错。刚刚更新了!
  • “it”指的是被 javascript 代码检索的 userGroup 的“id”。

标签: javascript python html ajax django


【解决方案1】:

不要费心将idgroupid 传递到您的函数中。就像你说的 - 它总是只接收循环的最后一个值,因为这是基于userGroup-{{user.id}}', {{groups.id}} 字符串的硬编码。该字符串由服务器在页面加载时设置,并且在页面生命周期内永远不会更改。

如果您想找到当前选择的选项,只需执行以下操作:

var newid = document.getElementById("employeeLocation").value;

&lt;select&gt;value 将是当前选择的&lt;option&gt; 的值。

【讨论】:

    猜你喜欢
    • 2018-04-03
    • 2020-03-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-05-07
    • 2019-06-08
    相关资源
    最近更新 更多