Jump to content

Prompt box modification


shaijuelayidath

Recommended Posts

<button onclick="myFunction()">Try it</button> <p id="demo"></p> <script>function myFunction(){var x;var name=prompt("Please enter your name","Harry Potter"); if (name!=null) { x="Hello " + name + "! How are you today?"; document.getElementById("demo").innerHTML=x; }}</script> i am new to javascript and refering w3schools.when execute the above codeif i am enter any name is the prompt box, it is coming correctly.eg. if I give a name 'Tom' in the prompt box, it will get' Hello Tom ! How are you today? 'But if i did'nt type any thing, or if i make it is empty, i am getting' Hello ! How are you today? 'Can i bring a word 'Stranger' in between 'Hello" and "How are you today?"if the promptbox made empty:eg.' Hello Stranger How are you today?'

Link to comment
Share on other sites

something wrong again i faced, the code i done is below: <script>function myFunction(){var x;var name=prompt("Please enter your name","Harry Potter"); if (name!=null){x="Hello " + name + "! How are you today?";document.getElementById("demo").innerHTML=x;}else (name==null){x="Hello Stranger ! How are you today?";document.getElementById("demo").innerHTML=x;}}</script> if i click again in the button and enter a different name, it is showing only 'Hello Stranger !How are you today?"can it possible 'when i am entering a 'name', it should be show 'name' and when i make it empty it should show 'Hello Stranger How are you today?"

Link to comment
Share on other sites

Your code is wrong in else. Use this. <script>function myFunction(){var x;var name=prompt("Please enter your name","Harry Potter");if (name!=null){x="Hello " + name + "! How are you today?";document.getElementById("demo").innerHTML=x;}else {x="Hello Stranger ! How are you today?";document.getElementById("demo").innerHTML=x;}}</script>

Link to comment
Share on other sites

if (name!=null)
this if condition works in all ways, i.e. if name is null or not so try this one: <script>function myFunction(){var x;var name=prompt("Please enter your name","Harry Potter");if (name!= '') { x="Hello " + name + "! How are you today?"; document.getElementById("demo").innerHTML=x; }else if(name=='') {name='Stranger'; x="Hello " + name + "! How are you today?"; document.getElementById("demo").innerHTML=x; }}</script> When you leave the propt box empty then it will show "Hello Stranger! How are you today?"
Link to comment
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now
×
×
  • Create New...