LoginSignup
0
1

More than 3 years have passed since last update.

【jquery,js】URL・大きさを指定してウィンドウを開く [disabledプロパティ,value,confirm,open,switch,elementsプロパティ] [js06_20210223]

Last updated at Posted at 2021-02-23

処理の概要

URLを指定して任意の大きさで新しいウィンドウを開く

処理のフロー:

 (1)入力された値(リンク、幅、高さ)が入力されているかをチェックする
 (2)入力された値(リンク、幅、高さ)を取得する
 (3)ポップアップメッセージを出力する
 (4)Yesが選択されたら新しいウィンドウを開く

画面イメージ

画像1

画像2

ソースコード

index.html
    <body onload="init()">
        <form name="form1">
            <p>
                <input type="button" name="btnOpen" value="Open" onclick="openWindow()">
                <input type="button" name="btnClose" value="Close" onclick="closeWindow()">
            </p>
            <p>URL:<input type="text" name="txtUrl"></p>
            <p>幅:<input type="text" name="txtWidth"></p>
            <p>高さ:<input type="text" name="txtHeight"></p>
        </form>
    </body>
main.js
function init(){
    document.form1.txtUrl.value = "http://www.ank.co.jp";
    document.form1.txtWidth.value = "600";
    document.form1.txtHeight.value = "480";
    document.form1.btnClose.disabled = "true";
}

function openWindow(){
    var errMsg = errorCheck();

    if (errMsg !=""){
        alert(errMsg + "が入力されていません");
        return;
    }

    var url = document.form1.txtUrl.value;
    var width = document.form1.txtWidth.value;
    var height = document.form1.txtHeight.value;

    if (confirm("新しいウィンドウを開いてもよいですか?")){
        mywin = window.open(url,"","width=" + width + ",height=" + height);
        document.form1.btnClose.disabled = false;
    }
}

function closeWindow(){
    mywin.close();
    document.form1.btnClose.disabled = true;
}

function errorCheck(){
    var errMsg = "";

    for(i=0; i<document.form1.length; i++){
        if(document.form1.elements[i].type == "text" 
        && document.form1.elements[i].value == ""){
            switch(document.form1.elements[i].name){
                case "txtUrl":
                    errMsg += "[URL]";
                    break;
                case "txtWidth":
                    errMsg += "[幅]";
                    break;
                case "txtHeight":
                    errMsg += "[高さ]";
                    break;
            }
        }   
    }
    return errMsg;
};

ポイント

html:
(1)各ボタンにメソッドを紐付ける
js:
(1)値を取得するまえに入力チェックを行う(errorCheckメソッド)
(2)window.openメソッドの第一引数は、「url」、このほかオプションの設定が出来る
(3)openされたら、closeボタンオブジェクトを有効化する。
(4)form1のオブジェクトを「form1.elements[i]」で配列として取得し、switchに渡して制御する

参考資料

JavaScript(仕事の現場でサッと使える!デザイン教科書) p74

0
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
1