Using number provided in submit as variable? - javascript

I need help understanding how to fix this.
<p> Enter a number in the box. </p>
<div>
<label for ="numberSubmitted"> Number: </label>
<input type="text" class="numberSubmitted">
<input type = "submit" value="Submit">
</div>
<div>
<p class="message"></p>
</div>
var numberSubmitted = Number(numberSubmitted.value);
var message = document.querySelector(".message");
if(numberSubmitted > 100) {
message.textContent = "You won!";
} else {
message.textContent = "You lose!";
}
What's happening is that "You Lose!" is being printed out if I leave the variable as
var numberSubmitted = Number()
If change it to
var numberSubmitted = Number(numberSubmitted.value)
the code just doesn't work.
I don't see online any guide to tell you how to use Number() with classes.
Can anyone please point me in right direction on when to include class when defining the Number method?

So there are a few things:
The "for" in label needs to point to an id, not a class.
Your problem with it not working when you try to put numberSubmitted.value into Number() is that numberSubmitted is undefined, to fix this you need to get the html element of your input box and do .value on that.
You need to put your JavaScript in a script tag.
Try the following:
<p> Enter a number in the box. </p>
<div>
<label for="numberSubmitted"> Number: </label>
<input type="text" id="numberSubmitted">
<input type = "submit" value="Submit" onclick="submit()">
</div>
<div>
<p class="message"></p>
</div>
<script>
function submit() {
var numberSubmitted = Number(document.getElementById('numberSubmitted').value);
var message = document.querySelector(".message");
if(numberSubmitted > 100) {
message.textContent = "You won!";
} else {
message.textContent = "You lose!";
}
}
</script>

Here's another option, using an event listener instead of the inline function call:
JS Fiddle Demo here.
HTML
<p> Enter a number in the box. </p>
<div>
<label for="numberSubmitted"> Number: </label>
<input type="text" id="numberSubmitted">
<input type="button" id="myBtn" value="Submit">
</div>
<div>
<p class="message"></p>
</div>
JS
//bind the listener to the button
document.getElementById('myBtn').addEventListener('click', myFunction);
//get the input element
var el = document.getElementById('numberSubmitted');
function myFunction() {
var numberSubmitted = Number(el.value);
//for debug
console.log(numberSubmitted);
var message = document.querySelector(".message");
if (isNaN(numberSubmitted)) {
message.textContent = "That isn't a number.";
return;
}
if (numberSubmitted > 100) {
message.textContent = "You won!";
} else {
message.textContent = "You lose!";
}
}
As mentioned in my comments earlier, you need to wrap your JS in script tags. I've made other comments in the code segments above. You'll notice that wrapping your original JS in script tags isn't enough -- there is still an 'undefined' error pertaining to the numberSubmitted element. This is because JS has no idea what numberSubmitted is -- you need to find the element in the DOM and assign it to a variable. I've shown you how to do that above.

Related

JavaScript function/event listener not functioning properly

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.

JavaScript Function Activation Issues

I have another question that's been bugging my mind since I started using js fairly recently so that my app would be nicely responsive but I've been hit with another block here.
As the title says I am having serious issues with a particular code.
Here is its summarized form
window.onload = onLoadFunctions;
function onLoadFunctions(){
var show3rdDiv = document.getElementById('show3rdDiv');
var editbtnStart = document.getElementById('editbtnDiv');
var editbtnLog = 0;
editbtnStart.style.display = 'none';
show3rdDiv.onclick = function(){
document.getElementById('3rdDiv')className = "";
if (editbtnLog == 1) {
editbtnStart.style.display = 'block';
}
else {
editbtnStart.style.display = 'none';
}
}
}
function submitclick(){
var uname = document.getElementById("login").elements[0].value;
var upass = document.getElementById("login").elements[1].value;
var preuname = "john";
var preupass = "doe";
if (preuname == uname && preupass == upass) {
editbtnLog = 1;
document.getElementById('2ndDiv')className = "";
alert("The user " + preuname + " was successfully loged in and editbtnLog wass set to: " + editbtnLog);
}
else {
alert("Wrong Username or password!");
}
}
.hidden {
display:none;
}
<div id="login">
<form id="login">
Username<input type"text" placeholder="name">
Passowrd<input type"password" placeholder="password">
<input type="submit" value="Submit" onclick="submitclick()">
</form>
</div>
<div id="2ndDiv" class="hidden">
<input type="button" id="show3rdDiv" value="Continue">
</div>
<div id="3rdDiv" class="hidden">
<div id="editbtnDiv">
<input type="button" id="editbtn" value="Edit"/>
</div>
</div>
No matter what I do that editbtn won't appear or disappear the way an object that requires something should do. And if you noticed i used it's div instead? that's coz it would never appear at all if i just used the input button itself.
Someone please tell me how this is wrong is so many ways?
I tried a lot of styles and I don't really want to use the onclick="" (refer to that Submit button that I hate so much) on my html coz people say it's bad to use it. What should I do here? It got annoying like yesterday already.
Am i missing something? Did I declare this wrong? The furry mermaids i'm loosing precious eyebrow hairs on this project already. <=[
Or maybe i should just stick to the onclick="" thing when it comes to showing that edit btn?
Please Check weather your Script is calling properly or not.Check the line where you define the script.
The "id" attribute is the only
window.onload = onLoadFunctions;
function onLoadFunctions(){
var show3rdDiv = document.getElementById('show3rdDiv');
var editbtnStart = document.getElementById('editbtnDiv');
var editbtnLog = 0;
editbtnStart.style.display = 'none';
show3rdDiv.onclick = function(){
document.getElementById('3rdDiv').className = "";//error
if (editbtnLog == 1) {
editbtnStart.style.display = 'block';
}else {
editbtnStart.style.display = 'none';
}
}
}
function submitclick(){
var uname = document.getElementById("login").elements[0].value;
var upass = document.getElementById("login").elements[1].value;
var preuname = "john";
var preupass = "doe";
if (preuname == uname && preupass == upass) {
editbtnLog = 1;
document.getElementById('2ndDiv').className = "";//error
alert("The user " + preuname + " was successfully loged in and editbtnLog wass set to: " + editbtnLog);
}
else {
alert("Wrong Username or password!");
}
}
<div id="login1">
<form id="login">
Username<input type="text" placeholder="name">
Passowrd<input type="password" placeholder="password">
<input type="button" value="Submit" onclick="submitclick()">
</form>
</div>
<div id="2ndDiv" class="hidden">
<input type="button" id="show3rdDiv" value="Continue">
</div>
<div id="3rdDiv" class="hidden">
<div id="editbtnDiv">
<input type="button" id="editbtn" value="Edit"/>
</div>
</div>
Just a few minutes ago... (note: this is embarrassing!) i figured it out.
(This is not shown in the summarized codes mentioned above)
I made an element that changes its html value like a login button that turns into a logout if you are successfully logged in and changes back if you click it in its logout form so there is a loop. The button's value changes so i experimented a bit and realized that i could tie them together somehow. So i did. By declaring an onclick="" to the show3rdDiv button and a starting class of class="hidden" to editbtnDiv and stating that if the login button has a value of "login" then it keeps the hidden class but if it has a value of logout then it deletes that class.
I'm so stupid sometimes. :/

Javascript function to show text if i input value

To the point, if i input value "20" in input field then show message "Thank you".
Here's my HTML Code:
<form method="post" action="">
<input type="text" id="nominal" value="">
<input type="submit" value="submit">
</form>
Here's my JS Code:
$(document).ready(function(){
var money = 20;
/* not sure if this is written correctly, but this is supposed to
check whether the hidden input element value is equal to var money */
if ($("input[id='nominal']").val() == money ) {
var h = document.createElement("H1") // Create a <h1> element
var t = document.createTextNode("Thank You"); // Create a text node
h.appendChild(t); // Append the text to <h1>
};
});
i've created one script to fulfill what I need, but not working! what's wrong?
My JDFIDDLE LINK
You have to create an event to listening for changes, in this case changed. And you can make your code a bit smaller too. ;)
$(function() {
$("#nominal").change(function() {
if( $(this).val() == 20 )
$(this).after("<h1>Thank You</h1>");
});
});
Full working exaple with removing the message when value changes again and strict check can be seen here.
$(document).ready(function(){
var money = 20;
$("#nominal").change(function() { // take change event of input box
if ($(this).val() == money ) { // use $(this) to take value
var h = document.createElement("H1"); // Create a <h1> element
var t = document.createTextNode("Thank You"); // Create a text node
h.appendChild(t);
$('form').append(h); // append created h1 element in form/html
} else {
$('form').find("h1").remove();
}
})
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<form method="post" action="">
<input type="text" id="nominal" value="">
<input type="button" value="submit" name="submit" id="submit">
</form>

Using get element by ID for user input

I am trying to code this web app to have the user input important information about their device, then place it in the relevant spots in javascript. Here is my code so far.
<script type="text/javascript">
function update() {
var key = document.getElementById("key").value;
if (input.length < 40) {
alert("Please enter a valid input");
return;
}
document.getElementById("access key").innerHTML;
}
</script>
<script type="text/javascript">
function update() {
var device_id = document.getElementById("device_id").value;
if (input.length < 24) {
alert("please enter a valit input");
return;
}
document.getElementById("device_id").innerHTML;
}
</script>
<p><input type="text" id="key" autofocus placeholder = "Enter product key here" /></p>
<p><input type="text" id="device_id" autofocus placeholder = "Enter device ID here" /></p>
<p><input type="submit" value="Submit" onclick="update()"/></p>
<h1>Rotary Gate Systems</h1>
<article>
Open
</article>
<article>
Close
</article>
<article>
<p class="status_closed status_button">CLOSED</p>
<p class="status_open status_button">OPEN</p>
<p class="status_none status_button">NO CONNECTION</p>
</article>
<script src='http://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.js'></script>
<script>/*jslint browser: true*/
/*global $, jQuery*/
/*jshint strict: true */
/*EDIT THESE VARIABLES*/
//key is the same as your 'access token'
var key = "key"
//device_id is the same as the 'core id'
var device_id = "device_id"
I think I may be missing something in the submit button, or what I'm trying to do may not be possible with this attribute. Can someone take a look at this and let me know where I may be messing up?
You need to change your conditional statements to,
if (key.length < 40) {
and
if (device_id.length < 40) {
since input is not defined inside your update() functions.
And additionally, you should consider combining the two update() functions into one so as to conduct the validity checks on key and device_id together whenever the form is submitted.
Based on your comments, it sounds like you're trying to update the key and device_id variables with the values from the two <input> elements.
You should learn about variable scope in JavaScript to be sure you can access those variables.
If the key and device_id variables are in scope when your function runs, you can just assign them values directly. Don't precede the assignments with the var keyword, or you'll be defining new locally-scoped variables instead of updating the existing variables from the outer scope.
You also cannot have two functions with the same name (in this case, update) defined within the same scope; only the most recently defined function will work.
var key = "key";
var device_id = "device_id";
function update() {
var tempkey = document.getElementById("key").value;
if (tempkey.length < 40) {
alert("Please enter a valid key.");
return;
}else{
key = tempkey;
}
tempdevice_id = document.getElementById("device_id ").value;
if (tempdevice_id.length < 24) {
alert("please enter a valid device ID.");
return;
}else{
device_id = tempdevice_id;
}
}
<p>
<input type="text" id="key" autofocus placeholder="Enter product key here" />
</p>
<p>
<input type="text" id="device_id" autofocus placeholder="Enter device ID here" />
</p>
<p>
<input type="submit" value="Submit" onclick="update()" />
</p>
<h1>Rotary Gate Systems</h1>
<article>
Open
</article>
<article>
Close
</article>
<article>
<p class="status_closed status_button">CLOSED</p>
<p class="status_open status_button">OPEN</p>
<p class="status_none status_button">NO CONNECTION</p>
</article>

enable buttons in javascript/jquery based on regex match

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>

Categories

Resources