Enable button only if text is filled in (NO SPACES) - javascript

I've looked around for an answer to my question, but all the solutions I have found do not take into account that spaces also work as input.
I have a join function, and the button shouldn't be enabled if a user only enters space. It should need actual text. Anyone has a solution to this?
Here's my function:
$("#join").click(function(){
var name = $("#name").val();
if (name != "") {
socket.emit("join", name);
$("#login").detach();
$("#UsersOnline").show();
$("#msg").show();
$("#messaging").show();
$("#msg").focus();
ready = true;
}

you could use jquery trim()
var name = $.trim($("#name").val());
https://api.jquery.com/jQuery.trim/
EDIT:
As #David Thomas pointed out, we can also use String.prototype.trim()
var name = $("#name").val().trim();
function updateResult() {
var before = $("#name").val().replace(/\s/g,'SPACE');
var name = $("#name").val().trim();
$('#result').text('Before:' + before + "\nAfter:" + name);
}
$(document).ready(function(){
updateResult();
$('body').on('keyup','#name',function(){
updateResult();
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<p>By default value i left left a space for the name</p>
Name : <input type="text" id="name" value=" "><br>
<br>
Value of name : <pre id="result">empty</pre>

Related

How can I concatenate multiple user inputs in JS?

I am just starting out but I am stuck in what many will likely find to be a simple problem. I am trying to have multiple inputs concatenate after a button is pressed at the end.
Here is the code I tried but only "fname" shows up after I click the button instead of the value that was input into the space. What am I missing?
<!DOCTYPE html>
<html lang="en">
<body>
<p> Please enter your First Name: <input type="text" id="fname"></p>
<p> Please enter your Last Name: <input type="text" id="lname"></p>
<p> Please enter your User ID: <input type="text" id="uid"></p>
<p> Please enter your date of birth: <input type="date" id="bday"></p>
<button onclick="getEls()">Click Here<br>
When Done</button>
<script>
function getEls() {
document.getElementById("answer");
answer.innerHTML = (Hello + "fname" + " " + "lname" + your user id is " uid" + and your birthday is + "bday".);
}
</script>
<p id=answer>
<p>
</body>
</html>
I don't know if I understand well your question but is that what you want?
function getEls() {
var answer = document.getElementById("answer");
var fname = document.getElementById("fname").value;
var lname = document.getElementById("lname").value;
var uid = document.getElementById("uid").value;
var bday = document.getElementById("bday").value;
answer.innerHTML = ("Hello " + fname + " " + lname + " your user id is " + uid + " and your birthday is " + bday + ".");
}
<!DOCTYPE html>
<html lang="en">
<body>
<p>
Please enter your First Name:
<input type="text" id="fname">
</p>
<p>
Please enter your Last Name:
<input type="text" id="lname">
</p>
<p>
Please enter your User ID:
<input type="text" id="uid">
</p>
<p>
Please enter your date of birth:
<input type="date" id="bday">
</p>
<button onclick="getEls()">
Click Here<br>
When Done
</button>
<p id=answer>
<p>
</body>
</html>
If you have any questions please tell me in the comment
Your errors were a combination of typos (which would be a valid close reason), and a misunderstanding of how to use HTML <input> elements, and their values, in a String.
First, we'll look at the mistakes:
function getEls() {
// here, you retrieve an element correctly but don't
// assign it to a variable, and you do nothing with it;
// this is valid JavaScript, and not necessarily an error,
// but it's entirely pointless:
document.getElementById("answer");
// the reason that this works is the legacy of a terrible
// decision by Microsoft - years ago - to make any element
// with an id an automatic global variable, with the variable-
// name being the (unique) id of that element. This is
// a common implementation, but not listed in the spec so
// it may change in future; don't rely on the behaviour (and
// ideally don't use global variables):
answer.innerHTML =
// here you have hard-coded String components to which
// you want to interpolate/concatenate your supplied
// variables; unfortunately (for reasons unknown) you chose
// to leave the String unquoted (so, in JavaScript, these
// become undeclared variables), and you've quoted the
// variable names (and a lone white-space):
(Hello + "fname" + " " + "lname" + your user id is " uid" + and your birthday is + "bday".);
// Also, you seem to have a '+' operator missing, which
// contributes to the 'missing ) in parenthetical' error.
}
To correct this:
<p>Please enter your First Name: <input type="text" id="fname"></p>
<p>Please enter your Last Name: <input type="text" id="lname"></p>
<p>Please enter your User ID: <input type="text" id="uid"></p>
<p>Please enter your date of birth: <input type="date" id="bday"></p>
<button onclick="getEls()">Click Here<br>
When Done</button>
<script>
function getEls() {
let answer = document.getElementById("answer"),
fname = document.getElementById('fname'),
uid = document.getElementById('uid'),
bday = document.getElementById('bday');
answer.innerHTML = ("Hello" + fname.value + " " + lname.value + "your user id is " + uid.value + " and your birthday is " + bday.value + ". ");
}
</script>
<p id=answer></p>
JS Fiddle demo.
Now, while that works, we're going to refine it towards code that's more DRY (don't repeat yourself), and also towards unobtrusive JavaScript, which moves the event-handling out of the HTML:
// using a simple named function, using Arrow syntax, to retrieve an element
// via its assigned 'id' attribute-value (this is optional, but personally I
// don't like typing 'document.getElementById(...)' more than once):
const dGEBI = (id) => document.getElementById(id),
// your function, declared as a constant (on the assumption you're
// unlikely to redefine the function through the lifetime of your
// page):
getEls = function () {
// we retrieve the various elements, and assign them to
// variables:
let answer = dGEBI('answer'),
// we retrieve the <input> elements, and cache their values:
fname = dGEBI('fname').value,
lname = dGEBI('lname').value,
uid = dGEBI('uid').value,
bday = dGEBI('bday').value;
// here we use a template-literal to construct the String; this is
// delimited by backticks; and we can directly interpolate JavaScript
// variables or the results of JavaScript expressions into the String,
// by wrapping them with curly-braces ('{...}') and prefixing with a '$'
// character:'
answer.innerHTML = `Hello ${fname} ${lname}, your user id is: ${uid}, and your birthday is: ${bday}. `
}
// here we use document.querySelector() to retrieve the first (if any) element matching
// the supplied CSS selector; and then use EventTarget.addEventListener() to bind
// the getEls() function (note the deliberate lack of parentheses) as the event-handler
// for the 'click' event:
document.querySelector('button').addEventListener('click', getEls);
<p>Please enter your First Name: <input type="text" id="fname"></p>
<p>Please enter your Last Name: <input type="text" id="lname"></p>
<p>Please enter your User ID: <input type="text" id="uid"></p>
<p>Please enter your date of birth: <input type="date" id="bday"></p>
<button>Click Here<br>When Done</button>
<p id=answer></p>
JS Fiddle demo.
Next, We'll take a look at your HTML; and use <label> elements:
const dGEBI = (id) => document.getElementById(id),
getEls = function() {
let answer = dGEBI('answer'),
fname = dGEBI('fname').value,
lname = dGEBI('lname').value,
uid = dGEBI('uid').value,
bday = dGEBI('bday').value;
answer.innerHTML = `Hello ${fname} ${lname}, your user id is: ${uid}, and your birthday is: ${bday}. `
}
document.querySelector('button').addEventListener('click', getEls);
label {
display: block;
}
label:last-of-type {
display: revert;
}
<!-- Here, we've replaced the <p> elements with <label> elements; this
allows the user to click the text of the <label> to focus the
associated <input> element: -->
<label>Please enter your First Name: <input type="text" id="fname"></label>
<label>Please enter your Last Name: <input type="text" id="lname"></label>
<label>Please enter your User ID: <input type="text" id="uid"></label>
<!-- I've taken a different approach here, and used the 'for' attribute to
associate the <input> and <label>; for this approach the 'for' attribute
must contain the exact 'id' attribute-value of the relevant <input>: -->
<label for="bday">Please enter your date of birth: </label> <input type="date" id="bday">
<button>Click Here<br>When Done</button>
<p id=answer></p>
JS Fiddle demo.
References:
HTML:
<input>.
<label>.
JavaScript:
Arrow functions.
document.getElementById().
document.querySelector().
EventTarget.addEventListener().
HTMLInputElement.
HTMLLabelElement.
Template-literals.

Trying to get user input to print in a P element

I would like to be able to take user input of a first and last name and upon clicking a submit button update a P element with that first and last name. almost like "Hello firstname lastname!"
The code I've provided is what my click function currently looks like.
function newName(){
var Name = input.value;
if (Name==""){
document.getElementById("hello").innerHTML="Hello" + Name;
}
};
You need to use the trim() to remove blank spaces and then check the condition.
var firstName = document.querySelector('#firstName');
var lastName = document.querySelector('#lastName');
function updateName() {
if (firstName.value.trim() && lastName.value.trim()) {
document.getElementById("hello").textContent = `Hello ${firstName.value} ${lastName.value}`;
}
};
<input type="text" placeholder="Firstname" id="firstName" />
<input type="text" placeholder="Firstname" id="lastName" />
<button onclick="updateName()">Click</button>
<p id="hello">
</p>
function getName(){
let name = input.value;
if (name != ""){
document.getElementById("name").textContent = Hi ${name};
}
}
This would be the most concise way to do it. Since this is simple test function.
function newName(){
if(input.value !== undefined || ""){
document.getElementById("hello").innerHTML= 'Hello '+ input.value }
};
Your code should look like below. JS Fiddle here for quick reference: https://jsfiddle.net/sagarag05/5nteLzm6/3/
function newName(){
let fullName = input.value;
if (fullName != ""){
document.getElementById("fullName2").textContent = `Hello ${name}`;
}
}

javascript form with a popup

Really basic, I'm just trying to understand how to test a form using simple JavaScript without jQuery etc. Tried W3Schools but didn't work.
So I'm trying just a simple form instead with one field to get how it all works. Below I put a single field in a form, and thought I could test the fname variable against the firstName field.
But what happens is that the alert is never hit in the if statement. How to test the field firstName?
Any tips would be helpful.
function validateForm() {
var fname = document.getElementById("firstName");
if (fname == "") {
alert("first name is a mandatory field");
} else {
document.getElementById("formMessage").innerHTML = fname + " entered.";
}
}
<h2>Question 1 validate with alert popups</h2>
<p>Please enter the following mandatory information</p>
<form name="identification">
<p>First Name:<input type="text" id="firstName" /></p>
<p>
<button type="button" onclick="validateForm()">Submit</button>
</p>
</form>
<p id="formMessage"></p>
You're comparing the element itself. You should instead check the value of the element.
e.g.
var fname = document.getElementById("firstName").value;
fname is the element when you do document.getElementById, so you have to do:
function validateForm() {
var fname = document.getElementById("firstName");
if (fname.value == "") {
alert("first name is a mandatory field");
} else {
document.getElementById("formMessage").innerHTML = fname.value + " entered.";
}
}
You might also want to trim fname.value in case the user inputs bunch of empty spaces.
Use document.getElementById("firstName").value to get the value. if you don't add .value it means it didn't read the specified value.

Auto generate name based on user input using jquery

I have two Input fields I want to name based on user input but this name should be lowercase and spaces between words change to "-". I am doing like this
$(function() {
$("#name").keyup(function() {
var name = $("#name").val();
var alias = name.charAt(0);
$("#alias").val(alias);
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<input name="name" class="text-input medium-input" type="text" id="name" value="" />
<input name="alias" class="text-input medium-input" type="text" id="alias" />
This given me result I write "arslan" in first input field then showing "a" in second input field
Showing only one letter
I want to name based on user input but this name should be lowercase
and spaces between words change to "-".
Use replace
$("#alias").val( name.replace( /\s+/g, "-" ) );
Your function should look like
$(function() {
$("#name").keyup(function() {
var name = $("#name").val();
$("#alias").val( name.toLowerCase().replace( /\s+/g, "-" ) );
});
});
You should copy the whole entry from name input to alias while replacing the spaces with '-' and turning it to lower case.
$("#name").keyup(function() {
$("#alias").val($(this).val().replace(" ", "-").toLowerCase());
});
Simple Solution
var name = $("#name").val().toLowerCase();
var alias = name.split(" ").join("-");
$("#alias").val(alias);
This will help you
$(function() {
$("#name").keyup(function() {
var name = $("#name").val().toLowerCase();
$("#alias").val(name.replace(/-/g,' '));
});
});
The replace will change all - given in the name with space

Get variable via user input

I want that the user can see the value of a variable by writing it's name in a textarea, simpliefied:
var money = "300$";
var input = "money"; //user wants to see money variable
alert(input); //This would alert "money"
Is it even possible to output (in this example) "300$"?
Thanks for help!
Instead of seprate variables, use an object as an associative array.
var variables = {
'money': '300$'
}
var input = 'money';
alert(variables[input]);
You can use an object and then define a variable on the go as properties on that object:
var obj = {}, input;
obj.money = "300$";
input = "money";
alert(obj[input]);
obj.anotherMoney = "400$";
input = "anotherMoney";
alert(obj[input]);
A simple way,you can still try this one :
var money = "300$";
var input = "money"; //user wants to see money variable
alert(eval(input)); //This would alert "money"
Here is an answer who use the textarea as asked.
JSFiddle http://jsfiddle.net/7ZHcL/
HTML
<form action="demo.html" id="myForm">
<p>
<label>Variable name:</label>
<textarea id="varWanted" name="varWanted" cols="30" rows="1"></textarea>
</p>
<input type="submit" value="Submit" />
</form>
<div id="result"></div>
JQuery
$(function () {
// Handler for .ready() called.
var variables = {
'money': '300$',
'date_now': new Date()
}
//Detect all textarea's text variation
$("#varWanted").on("propertychange keyup input paste", function () {
//If the text is also a key in 'variables', then it display the value
if ($(this).val() in variables) {
$("#result").html('"' + $(this).val() + '" = ' + variables[$(this).val()]);
} else {
//Otherwise, display a message to inform that the input is not a key
$("#result").html('"' + $(this).val() + '" is not in the "variables" object');
}
})
});

Categories

Resources