Skip to content
Advertisement

Can i put 2 values in 1 textbox in javascript?

Is there a way to put 2 values in 1 text box using javascript? another question just dont answer if dont antw to, may i know how to if-else numbers like (enter-age 18-60 only)

<script>
function greeting() {
var name; 
var name = name.value;
document.getElementById("greeting1").value = name;
var greet;
var timep = time.value;
if (timep == "M") {
    greet = "Good Morning";
    document.getElementById("greeting1").value = greet;
    }
    else if (timep == "E") {
    greet = "Good Evening";
    document.getElementById("greeting1").value = greet;
    }
    else{
    alert("Not Allowed")
    }
    }       
</script>
<body>
<p>Enter Name::</p> <input type="text" id="name"  />
<p>Enter Time Period [M/E]::</p> <input type="text" id="time"  />
<button onclick="greeting()">TRY</button>
<input type="text" id="greeting1" readonly  />

Advertisement

Answer

To append multiple values to same text field use .value += greet

function greeting() {
  var name = document.getElementById("name").value;
  var greet;
  var timep = time.value;

  if (timep == "M") {
    greet = "Good Morning";
  } else if (timep == "E") {
    greet = "Good Evening";
  } else {
    alert("Not Allowed")
  }
  
  document.getElementById("greeting1").value = greet + ' ' + name;
}
<p>Enter Name::</p> <input type="text" id="name" />
<p>Enter Time Period [M/E]::</p> <input type="text" id="time" />
<button onclick="greeting()">TRY</button>
<input type="text" id="greeting1" readonly />

Solution without entering time:

function greeting() {
  var name = document.getElementById("name").value;
  var hour = new Date().getHours();
  var greeter = document.getElementById("greeting1");
  
  greeter.value = name;

  if (hour < 12) {
    greeter.value += " Good Morning";
  } else {
    greeter.value += " Good Evening";
  }
}
<p>Enter Name::</p> <input type="text" id="name" placeholder="Name"/>
<button onclick="greeting()">TRY</button>
<input type="text" id="greeting1" readonly />
User contributions licensed under: CC BY-SA
2 People found this is helpful
Advertisement