I need to take the value from an input box and write it below the input box on the click of a button. I thought to use a label but if there is another way I am open to suggestions.
My code so far:
<h1>Test</h1>
<form name="greeting">
Type your name here: <input type = "Text" name="fullname" id="name"> <button onclick="getName()">Create</button><br>
Hello <label id="greet">Hello</label>
</form>
<script lang="javascript">
function getName() {
var inputVal = document.getElementById("name").value;
if (inputVal == "") {
document.getElementById("name").style.backgroundColor = "red";
}
else {
document.write("Hello " + document.getElementById("name"));
}
First of all, you don't want to submit a form, so change button type from "submit" (default) to "button".
Then you should not use document.write almost never, it's used in very specific cases. Use proper DOM manipulation methods like appendChild. I would use convenient insertAdjacentHTML:
function getName() {
var input = document.getElementById("name");
if (input.value == "") {
input.style.backgroundColor = "red";
} else {
input.insertAdjacentHTML('afterend', '<div>' + input.value + '</div>');
}
}
<form name="greeting">Type your name here:
<input type="Text" name="fullname" id="name" />
<button type="button" onclick="getName()">Create</button>
<br>Hello
<label id="greet">Hello</label>
</form>
First you need to stop your form from submitting. Second you should not use document.write, since it will not append the text as wanted after the input field. And last you need to validate the elements value and not the element itself.
<html>
<head>
<script>
//First put the function in the head.
function getName(){
var input = document.getElementById("name");
input.style.backgroundColor = ''; //Reseting the backgroundcolor
if (input.value == ''){ //Add the.value
input.style.backgroundColor = 'red';
}
else{
//document.write('Hello ' + input.value); //This would overwrite the whole document, removing your dom.
//Instead we write it in your greeting field.
var tE = document.getElementById('greet');
tE.innerHTML = input.value;
}
return false //Prevent the form from being submitted.
}
</script>
</head>
<body>
<h1>Test</h1>
<form name = 'greeting'>
Type your name here: <input type = "Text" name="fullname" id="name"> <button onclick="return getName()">Create</button><br>
Hello <label id="greet">Hello</label>
</form>
</body>
</html>
You need to cancel the submit event which makes the form submit, alternatively you could not wrap everything inside a form element and just use normal div that way submit button wont submit.
Demo : https://jsfiddle.net/bypr0z5a/
Note reason i attach event handler in javascript and note onclick attribute on button element is because jsfiddle works weird, on ordinary page your way of calling getName() would have worked.
byId('subBtn').onclick = function (e) {
e.preventDefault();
var i = byId('name'),
inputVal = i.value;
if (inputVal == "") {
i.style.backgroundColor = "red";
} else {
byId('greet').innerText = inputVal;
i.style.backgroundColor = "#fff";
}
}
function byId(x) {
return document.getElementById(x);
}
Related
I have an event listener that takes input from the user and replaces the default text "Your Username" with the user input.
<input type="text" class="search">
<div id="username">Your Username</div>
<script>
var search = document.querySelector('.search');
search.addEventListener('input', changeText);
function changeText() {username.innerHTML = `${this.value}`}
</script>
If the user backspaces all input, I want the innerHTML of the div to revert to the default (i.e. "Your Username"). How can I do this?
Store the original HTML in initialization, then use it in the change listener if valye is an empty string:
var search = document.querySelector('.search');
var originalHTML = username.innerHTML;
search.addEventListener('input', changeText);
function changeText() {
username.innerHTML = this.value !== '' ? this.value : originalHTML;
}
You need to add a conditional on your eventListener, if input value is null, something like this can do the trick:
<input type="text" class="search">
<div id="username">Your Username</div>
<script>
var search = document.querySelector('.search');
search.addEventListener('input', changeText);
function changeText() {
if(input.value == "") {
username.innerHTML = "Your Username";
} else {
username.innerHTML = `${this.value}`
}
}
</script>
You can add your default text with || operator.
function changeText() {username.innerHTML = `${this.value || 'Your default value'}`}
This will set the text to the default value if this.value is null or undefined or empty.
how would I get a textbox perform a function if a specific word is submitted. I have a robot that jumps on mousedown and I want it to jump if I write jump or write move in the textbox it does the move function. I tried few things but couldnt get it to work
Heres the code
<form id="formDiv" action="" >
Command the robot!: <input type="text" size="50" onkeydown="keyCode(event)">
</form>
<div id="canvasDiv" width="500" height="10"></div>
<script type="text/javascript" src="robotti.js"></script>
<script type="text/javascript">
prepareCanvas(document.getElementById("canvasDiv"), 500, 500);
document.getElementById("canvasDiv").onmousedown = function() {
jump(); }
//document.getElementById("canvasDiv").onkeypress = function() {
//move(); }
document.getElementById("canvasDiv").window.onkeypress = function(event) {
if (event.keyCode == 41) {
move();
}
}
</script>
This should work -:
var text = getElementById("canvasDiv").value;
if(text.includes("move") || text.includes("jump")){
jump();
getElementById("canvasDiv").value = "";
}
Please use onkeyup instead of onkeydown
<!DOCTYPE html>
<html>
<body>
<input type="text" id="canvasDiv" onkeyup="keyCode()" value="">
<script>
function keyCode(e) {
var text = (document.getElementById("canvasDiv").value).toLowerCase();
if(text == 'jump' || text == 'move'){
//call jump function here
alert("jump");
}
}
</script>
</body>
</html>
You shouldn't use HTML attributes like onkeydown etc. Use an EventListener instead. Register one on your input field, grab its value and check (either via switch or if...else) what the user entered. According to the user's input, execute your functions.
document.querySelector('input[type="text"]').addEventListener('keyup', function() {
switch (this.value) {
case 'move':
console.log('move!'); // Your actual function here
this.value = ''; // Reset value
break;
case 'jump':
console.log('jump!'); // Your actual function here
this.value = '' // Reset value
break;
}
});
Command the robot!: <input type="text" size="50">
Further reading:
Why is inline event handler attributes a bad idea in modern semantic HTML?
document.querySelector
(This text box value comes dynamically)
If textbox gets value 100 it will enable submit button but here enable submit button after editing the value to 100 without changing it won't enable.
<script>
function manage(txt) {
var bt = document.getElementById('btSubmit');
if (txt.value != '100') {
bt.disabled = true;
}
else {
bt.disabled = false;
}
}
</script>
It depends on the browser. To make sure that works, use setAttribute and removeAttribute
var bt = document.getElementById('btSubmit');
bt.setAttribute("disabled","disabled");
bt.removeAttribute("disabled");
Can you check this:
function manage(txt) {
var bt = document.getElementById('btSubmit');
if (txt.value != '100') {
console.log('Disabled');
bt.setAttribute("disabled", "true");
} else {
console.log('Enabled');
bt.removeAttribute("disabled");
}
}
<input type="text" id="txt" onkeyup="manage(this)" />
<input type="submit" id="btSubmit" disabled="true" />
Not absolutely sure what the problem is here since your example is not an MCVE, but you can use the "keyup" event to listen to any changes made to your input element while typing.
Also, your code is unnecessarily verbose:
/* ----- JavaScript ----- */
document.getElementById("txt").addEventListener("keyup", function () {
/* Disable the button, if the value of the input is <> 100. */
document.getElementById("btSubmit").disabled = (this.value != 100);
});
<!----- HTML ----->
<input type = "text" id = "txt"/>
<input type = "submit" id = "btSubmit" disabled/>
If you prefer using inline JavaScript in your HTML code, the above solution can be written as:
/* ----- JavaScript ----- */
function manage (element) {
/* Disable the button, if the value of the input is <> 100. */
document.getElementById("btSubmit").disabled = (element.value != 100);
}
<!----- HTML ----->
<input type = "text" id = "txt" onkeyup = "manage(this)"/>
<input type = "submit" id = "btSubmit" disabled/>
I'm completely new to JavaScript, and don't know why this isn't working. When I click on the input box, and type in less than 5 characters, i want a message to display. The message is simply not showing. Source code: https://jsfiddle.net/015por64/
<html>
<body>
<form id="form>">
<input id="input">
<div id="text"> Test </div>
</input>
</form>
</body>
</html>
<script>
function checkUserName(e, minLength) {
var username = document.getElementById("input");
var usernameLength = username.textContent;
if (usernameLength.value.length < 5) {
msg = "Your username must consist of at least five characters."
};
else {
msg = "";
text.innerHTML=msg
};
}
var text = document.getElementById("text");
text.addEventListener("blur", function(e) {checkUserName(e, 5)}, false)
</script>
Few issues with your code:
you need to attach the event to #input and not the div#text.
you need to read value of #input and not textcontent
; after if is wrong because then else will give syntax error.
<html>
<body>
<form id="form>">
<input id="input">
<div id="text"> Test </div>
</input>
</form>
</body>
</html>
<script>
function checkUserName(e, minLength) {
var username = document.getElementById("input");
var usernameLength = username.value;
if (usernameLength.length < 5) {
msg = "Your username must consist of at least five characters.";
text.innerHTML=msg;
}else {
msg = "";
text.innerHTML=msg;
};
}
var text = document.getElementById("text");
document.getElementById('input').addEventListener("blur", function(e) {checkUserName(e, 5);}, false)
</script>
It should be the input where you have to put the blur event listener.
var input = document.getElementById("input");
And since you have no use for text outside the function, better define it inside.
I'm having trouble getting the match to bind to the oninput property of my text input. Basically I want my submit button to be enabled only when the regular expression is matched. If the regex isn't matched, a message should be displayed when the cursor is over the submit button. As it stands, typing abc doesn't enable the submit button as I want it to. Can anyone tell me what I'm doing wrong? Thank you.
<div id="message">
</div>
<form method="POST">
<input type="text" id="txt" oninput="match()" />
<input type="submit" id="enter" value="enter" disabled />
</form>
<script>
var txt = $("#txt").value();
var PATTERN = /abc/;
var REQUIREMENTS = "valid entries must contain the string 'abc'";
// disable buttons with custom jquery function
jQuery.fn.extend({
disable: function(state) {
return this.each(function() {
this.disabled = state;
});
}
});
$('input[type="submit"]).disable(true);
var match = function(){
if (txt.match(PATTERN)){
$("#enter").disable(false)
}
else if ($("#enter").hover()){
function(){
$("#message").text(REQUIREMENTS);
}
}
</script>
Your code would be rewrite using plain/vanille JavaScript.
So your code is more clean and better performance:
<div id="message"></div>
<form method="POST">
<input type="text" id="txt" oninput="match()" />
<input type="submit" id="enter" value="enter" disabled />
</form>
<script>
var txt;
var enter = document.getElementById('enter');
var message = document.getElementById('message');
var PATTERN = /abc/;
var REQUIREMENTS = "valid entries must contain the string 'abc'";
function match() {
txt = document.getElementById('txt').value;
if (PATTERN.test(txt)) {
enter.disabled = false;
} else if (isHover(enter)) {
enter.disabled = true;
message.innerHTML = REQUIREMENTS;
} else {
enter.disabled = true;
}
}
function isHover(e) {
return (e.parentElement.querySelector(':hover') === e);
}
</script>
If you wanted to say that you want handle the events in different moments, your code should be the following.
Note: the buttons when are disabled doesn't fired events so, the solution is wrapper in a div element which fired the events. Your code JavaScript is more simple, although the code HTML is a bit more dirty.
<form method="POST">
<input type="text" id="txt" oninput="match()" />
<div style="display: inline-block; position: relative">
<input type="submit" id="enter" value="enter" disabled />
<div id="buttonMouseCatcher" onmouseover="showText(true)" onmouseout="showText(false)" style="position:absolute; z-index: 1;
top: 0px; bottom: 0px; left: 0px; right: 0px;">
</div>
</div>
<script>
var txt;
var enter = document.getElementById('enter');
var message = document.getElementById('message');
var PATTERN = /abc/;
var REQUIREMENTS = "valid entries must contain the string 'abc'";
function match() {
txt = document.getElementById('txt').value;
if (PATTERN.test(txt)) {
enter.disabled = '';
} else {
enter.disabled = true;
}
}
function showText(option) {
message.innerHTML = option ? REQUIREMENTS : "";
}
</script>
Two problems here:
The variable txt is defined once outside the function match, so the value is fixed to whatever the input with id txt has when the script/page is loaded.
You should move var txt = $("#txt").val(); into the match function.
Notice I changed the function value() to val().
Problems identified:
jQuery events don't happen on disabled inputs: see Event on a disabled input
I can't fix jQuery, but I can simulate a disabled button without it actually being disabled. There's other hacks you could do to get around this as well, for example, by overlaying a transparent element which actually captures the hover event while the button is disabled.
Various syntactical errors: format your code and read the console messages
.hover()){ function() { ... } } is invalid. It should be .hover(function() { ... })
else doesn't need to be followed by an if if there's no condition
.hover( handlerIn, handlerOut ) actually takes 2 arguments, each of type Function
$('input[type="submit"]) is missing a close '
Problems identified by #Will
The jQuery function to get the value of selected input elements is val()
val() should be called each time since you want the latest updated value, not the value when the page first loaded
Design issues
You don't revalidate once you enable input. If I enter "abc" and then delete the "c", the submit button stays enabled
You never hide the help message after you're done hovering. It just stays there since you set the text but never remove it.
https://jsfiddle.net/Lh4r1qhv/12/
<div id="message" style="visibility: hidden;">valid entries must contain the string 'abc'</div>
<form method="POST">
<input type="text" id="txt" />
<input type="submit" id="enter" value="enter" style="color: grey;" />
</form>
<script>
var PATTERN = /abc/;
$("#enter").hover(
function() {
$("#message").css('visibility', $("#txt").val().match(PATTERN) ? 'hidden' : 'visible');
},
$.prototype.css.bind($("#message"), 'visibility', 'hidden')
);
$('form').submit(function() {
return !!$("#txt").val().match(PATTERN);
});
$('#txt').on('input', function() {
$("#enter").css('color', $("#txt").val().match(PATTERN) ? 'black' : 'grey');
});
</script>