簡體   English   中英

選擇默認情況下使用jQuery選擇一個選項

[英]Chosen select an option by default with jQuery

我有一個帶選項的選擇框,我在Zend View上使用jQuery“Chosen”。 這個插件工作正常。

Javascript:
$('#select_type').chosen();

我的問題是我需要在頁面加載時選擇其中一個選項,具體取決於type_id的值。 我試過這個:

document.getElementById('select_type').value = '<?=$this->type_id?>';

這會更改其值,但未在所選的JQuery中選擇該選項。

有任何想法嗎?


編輯:該選項通過執行上面提到的內容成功更改,但它不會更新/更改jQuery“selected”插件中的選定元素。 我的問題是關於更新jQuery Chosen的選定值而不是HTML SELECT(我已成功完成)。 這是jQuery Chosen插件的鏈接

用JS更新列表

運行后:

document.getElementById('select_type').value = '<?=$this->type_id?>';

對於選擇版本1及更高版本(更新版本)

你應該致電:

$('#select_type').trigger('chosen:updated');

取自選擇的文檔

動態更新選擇

如果您需要更新選擇字段中的選項並希望選擇選擇更改,則需要在該字段上觸發“selected:updated”事件。 Chosen將根據更新的內容重新構建自己。

$("#form_field").trigger("chosen:updated");

請參閱更改日志以了解此API更改的公告。

對於低於1的選擇版本(較舊)

你應該致電:

$('#select_type').trigger('liszt:updated');

取自選擇的文檔

動態更新選擇

如果您需要更新選擇字段中的選項並希望選擇選擇更改,則需要在該字段上觸發“liszt:updated”事件。 Chosen將根據更新的內容重新構建自己。

  • jQuery版本$("#form_field").trigger("liszt:updated");
  • 原型版Event.fire($("form_field"), "liszt:updated");

在調用Chosen之前設置值

而不是從JS這樣做,為什么不在用JavaScript調用Chosen插件之前在HTML中設置所選選項? 您正在從一塊PHP設置值,所以我不明白為什么不能這樣做。

您可以使用所選屬性設置正確的元素,如下所示:

<select name="teams[]" data-placeholder="Chose an option:" 
        class="chzn-select" multiple tabindex="6">
    <option value=""></option>
    <option selected="selected">Dallas Cowboys</option>
    <option selected="selected">New York Giants</option>
    <option>Philadelphia Eagles</option>
    <option>Washington Redskins</option>
</select>

選擇將注意初始化並顯示兩個預先選擇的選項。

試試這個:

$("#select_type").val(<?=$this->type_id?>).trigger('change');

$('#select_type').trigger('liszt:updated');

試試這個:

$('#select_type').val('<?=$this->type_id;?>'); // Select the value before .chosen();
$('#select_type').chosen();
$('#select_type').val('<?=$this->type_id?>');

試試吧

請嘗試以下方法:

$("#choen-presentacion").val(value.id_presentacion).trigger('chosen:updated')

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM