フォーラム@nifty | フォーラム・サークル | サイトマップ | ヘルプ |
掲示板 コラム お役立ち イベント リンク   | FHPGサイトマップ | お問い合わせ |
TOP > お役立ち > JavaScriptのおもちゃ箱 > 大小を比較して小さい順に並べる  

大小を比較して小さい順に並べる

原案:小中富雄 氏 (2000/04/01 登録)

 選択された数字を取得して小さい順に並べて表示します。

  1. 数字を選択して、「並べる」ボタンを押してください。
  2. テキストボックスに小さい順に並びます。

表示サンプル

 

 結果-->

ソース記述内容

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html lang="ja">
<head>
<title>大小を比較して小さい順に並べる</title>
<script type="text/javascript">
<!--
//Netscape3以上で試して下さい。
//一部の環境ではsort()関数のバグのためエラーが出るかも知れませんが、、

function num(j){
    document.write("<option selected>"+"0")
    for(var i=1;i<j;i++){
    document.write("<option>"+i);
        }
}

function compare(a,b){
    return (a-b)
}

function lineup(f){

f.result.value=""
var data=new Array(5)

data[0]=parseInt(f.a.options[f.a.selectedIndex].text)
data[1]=parseInt(f.b.options[f.b.selectedIndex].text)
data[2]=parseInt(f.c.options[f.c.selectedIndex].text)
data[3]=parseInt(f.d.options[f.d.selectedIndex].text)
data[4]=parseInt(f.e.options[f.e.selectedIndex].text)

f.result.value=data.sort(compare)
}

function clearIt(f){
    f.result.value=""
}
// -->
</script>
</head>
<body>
<form name="myForm">
 <select name="a" size=1 onChange="clearIt(this.form)">
  <script type="text/javascript">
<!--
num(51);
document.write("</select><select name='b' size=1 \ onChange='clearIt(this.form)'>");
num(51);
document.write("</select><select name='c' size=1 \ onChange='clearIt(this.form)'>");
num(51);
document.write("</select><select name='d' size=1 \ onChange='clearIt(this.form)'>");
num(51);
document.write("</select><select name='e' size=1 \ onChange='clearIt(this.form)'>");
num(51);
// -->
</script>
  </select>
  <input type=Button value="並べる" onClick="lineup(this.form)">
  <input type=Reset value="reset">
  <br>
  <br>
   結果--> 
  <input name="result" type="text" size="20" maxlength="20">
</form>
<body>
<html>
個人情報保護ポリシー
Copyright© NIFTY 2006 All Rights Reserved.
Copyright© FHPG 2006 All Rights Reserved.