選択>オプションにIDを追加する方法:選択したHTML要素?選択された選択>オプション要素にIDを追加する方法
ここまでは私のコードです。
<!-- select time zone -->
<div class="row">
<div class="col-md-6 col-md-offset-3">
<h3 id="stepOne"><b>Step 1:</b> Select your Time Zone</h3>
<select class="form-control" name="timeZone" id="getTimeZone" onchange="getTimeZone()">
<?php foreach ($time_zones as $key => $array) : ?>
<?php foreach ($array as $offset => $zone) : ?>
<option value="<?php echo $offset; ?>"><?php echo $zone; ?></option>
<?php endforeach; ?>
<?php endforeach; ?>
</select>
</div>
</div>
<!-- end select timezone -->
<!-- get timezone from dropdown -->
<script>
function getTimeZone() {
// if option is selected add an ID attribute
// then get that id attributes inner html
var id = $("#getTimeZone").children("option:selected").attr("timeZoneSelected");
var timeZone = document.getElementById("getTimeZone").value;
document.getElementById("showTimeZone").innerHTML = timeZone;
document.getElementById("timeZoneField").value = timeZone;
document.getElementById("stepOne").className = "text-success";
}
</script>
<!-- end get timezone from dropdown -->
基本的に私はタイムゾーンのリストをループしています。ユーザーがタイムゾーンを選択すると、オプションにIDを追加したいとします(例:id="timeZoneSelected"
)。
次に、その特定のオプション要素のinnerHTMLを取得したいと思います。私のコードは、具体的には、
が動作していないあなたが見ることができるように:
var id = $("#getTimeZone").children("option:selected").attr("timeZoneSelected");
はどこで間違ったんですか?
これには「id」は使用しないでください。静的にすることを意図しています。代わりにクラスを使用してください。また、 'timeZoneSelected'属性を持たないので、選択されたオプションの' text() 'がほしいと思うようです。 –
さて、助言には注意しましたが、HTMLページ全体の1つの要素に" timeZoneSelected "属性...だから私はそれがIDのためのものだと思った。 –
どのようにですか? 'option:selected 'を使って非常に単純に検索できる' option'要素に動的識別子を入れることは非常に奇妙な要求です。 –