![](/img/trans.png)
[英]Change function jquery didn't send value to views.py (didn't work)
[英]Change value of hidden field didn't work
一個簡單的問題(我認為)一個簡單的解決方案,但為什么不會以下(精簡與重要線路版)工作:
編輯:我編輯了我的示例代碼,以便它也許更清楚為什么它有錯誤
我仍然對代碼感到懷疑,因為它看起來很丑陋,里面有很多無用的東西,但是我沒有進入優化階段
HTML:
<div class="select-container">
<input type="hidden" name="enroll-persons-field" id="enroll-persons-field">
<select size="1" name="enroll-persons" id="enroll-persons" class="form-options" tabindex="7">
<option value=""></option>
<optgroup label="Ik boek voor">
<option value="1" selected>1 persoon</option>
<option value="2">2 personen</option>
<option value="3">3 personen</option>
<option value="4">4 personen</option>
<option value="5">5 personen</option>
<option value="more">meer dan 5 personen</option>
</optgroup>
<select>
<div>
[..]
<input type="text" name="enroll-address" id="enroll-address" class="default-input-style" placeholder="Je adres" tabindex="10" required>
現在,我通過jQuery替換選擇列表以設置選項列表的樣式。 我可以想象它是一個丑陋的方法,但到目前為止它仍然有效
$(".select-container").after("<div class='select-list-container'></div>");
$(".select-list-container").append("<ul id='select-option-list'>");
$(".form-options option").each(function(){
li = '<li id="'+$(this).val()+'">'+$(this).attr('text')+'</li>';
$("#select-option-list").append(li);
});
$(".select-list-container").append("</ul>");
$(".form-options").hide();
$(".select-container").text($(".form-options option:last").attr('text')).click(function(){
$(".select-list-container").toggle("fast");
});
$("#select-option-list li").live("click", function(){
$(".select-container").text($(this).text());
$(".select-list-container").toggle("fast");
$("#enroll-persons-field").val($(this).attr("id"));
});
希望這個描述會有所幫助
alert()
結果為undefined
, $(this).attr('id')
是合法值。 我測試了:)
EDIT2:通過將隱藏的輸入字段放置在select-container div
之外來解決它
謝謝大家的幫助!
在您的代碼中, $(this).attr('id')
在文檔的上下文中運行,該文檔沒有名為ID的屬性。 將其更改為$("#enroll-persons-field").attr("id")
,或將結果存儲在變量中並使用兩次。
從您發布的代碼來看, this
是document
。 $(this).attr("id")
等同於document.id
。 除非您先前在JavaScript中的某個位置設置了document.id
否則該值將是未定義的。
你需要去任何你希望的參考this
要,並使用它。
順便說一下, $(this).attr("id")
與this.id
相同。 在這里調用jQuery的開銷是沒有意義的。
嘗試改變這個
$("input#enroll-persons-field").val($(this).attr('id'));
至
var text = $("input#enroll-persons-field").attr('id');
$("input#enroll-persons-field").val(text);
如果您想保留自己擁有的東西,可以始終:
var this = $("input#enroll-persons-field");
<input type="hidden" name="enroll-persons-field" value="myvalue" id="enroll-persons-field">
value
是值, id
是id。
總之你
$("input#enroll-persons-field").val($(this).attr('id'));
就像gilly3指出的那樣,它並不指向您想要的ID。
$("input#enroll-persons-field").val( function(){ return $(this).attr('id') });
將執行您期望的操作,因為此attr('id')引用的是“#enroll-persons-field”而不是文檔本身。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.