-2

プルダウン メニューの選択に基づいて動的に生成されたテキスト ボックスを jQuery で表示/非表示にする方法を理解しようとしています。私のJSスキルは非常に限られています。人数に応じて、while ループで以下を作成しました。

<select name="location[<?=$pid?>]" id="location[<?=$pid?>]">
<option value="<?=$loc_id?>" selected><?=$loc_name?> </option>
<option value="Other">Other</option>
<option value="Other">--------</option>
<? $query_loc = mysqli_query($link, "SELECT * FROM locations WHERE loc_app = 'Y' ORDER BY loc_name ASC");
while($fetch_loc = mysqli_fetch_array($query_loc)){
     $loc_id = $fetch_loc['loc_id'];
     $loc_name = $fetch_loc['loc_name'];
     ?>
     <option value="<?=$loc_id?>"><?=$loc_name?></option>
     <?
}  ?>
</select>
<input name="location_other[<?=$pid?>]" type="text" id="location_other[<?=$pid?>]" style="display:none" />

jQuery関数:

<script type='text/javascript'>
$(window).load(function(){
    $('#location').change(function () { 
        if ($(this).val() == "Other") { 
            $('#location_other').show(); 
        } else { 
            $('#location_other').hide(); 
        } 
    }); 
});
</script>

の id を保持し、後で処理するために $pid 変数でシリアル化する必要があります。これらでjquery関数を呼び出す別の方法はありますか?

HTML 出力は次のようになります。

<select name="location[287]" id="location[287]">
        <option value="1" selected>A</option>
        <option value="Other">Other</option>
        <option value="Other">--------</option>
        <option value="12">B</option>
        <option value="12">C</option>            
      </select>
      <input name="location_other[287]" type="text" id="location_other[287]" style="display:none" />
4

2 に答える 2

0

試す

$(window).load(function(){
    $('#location').change(function () {
        $('input[id^=location_other]').hide();
        if ($(this).val() == "Other") { 
            $('#location_other').show(); 
        } else { 
            $('#location_other' + $(this).val()).hide(); 
        } 
    }); 
});
于 2013-03-27T00:50:26.497 に答える
0

これを試して

<select name="location[287]" id="location[287]">
    <option value="Other">Other</option>
    <option value="one">One</option>
    <option value="two">Two</option>
    <option value="three">Three</option>
</select>
<input name="location_other[287]" type="text" id="location_other" style="display:none" />


<script type='text/javascript'>
    $(window).load(function() {
        if ($('select[id^="location"]').val() == "Other") {
            $('#location_other').show();
        } else {
            $('#location_other').hide();
        }

        $('select[id^="location"]').change(function() {
            if ($(this).val() == "Other") {
                $('#location_other').show();
            } else {
                $('#location_other').hide();
            }
        });
    });
</script>
于 2013-03-27T09:02:56.983 に答える