2022年6月15日 星期三

[html, input] How to dynamically create a text input

 How to dynamically create a text input

井民全, Jing, mqjing@gmail.com


1. Html

File: index.html

<!doctype html>

<html lang="en">


<head>

    <script src="https://cdnjs.cloudflare.com/ajax/libs/paho-mqtt/1.0.1/mqttws31.min.js" type="text/javascript"></script>

</head>


<body>

    <h1>Test</h1>

    <script src="index.js"></script>

</body>

</html>

2. Function

File: index.js

let body = document.getElementsByTagName("body")[0];


function createHtmlElement(strStyle, strTitle, funClickCallback){

  let ele = document.createElement(strStyle);

  if(strTitle != null)

    ele.innerHTML = strTitle;

  if (funClickCallback != null)

    ele.addEventListener('click', funClickCallback);

  return ele;

}


function createHtmlInput(strTitle, body){

  let ele = createHtmlElement('input', null, null);

  ele.type = "text";

  ele.defaultValue = strTitle;

  if(body == null){

    console.log('Error: createHtmlBr::body == null')

    return null;

  }


  body.appendChild(ele);

  return ele;

}


3. Usage

let input = createHtmlInput("192.168.2.100", body);

document.write(input.value);  # read the input value


4. Result