Javascript input value - javascript

I wanted to a make a function that after you enter anything in the input and press the button the alert box would say "value". And if you press the button and you haven't entered anything in the input the alert box would say "no value". Here is my code and it is not working. After I press the button, every time the alert box says "no value".
<body>
<input type="text">
<button onclick="btn()" type="button" name="button">submit</button>
<script type="text/javascript">
var input = document.getElementsByTagName("input");
function btn(){
if (input.value = "none") {
alert("no value");
}else {
alert("value");
}
}
</script>

You need to check the value of input[0] and use === to check for the value:
var input = document.getElementsByTagName("input");
function btn(){
if (input[0].value === "") {
alert("no value");
}else {
alert("value");
}
}
<input type="text">
<button onclick="btn()" type="button" name="button">submit</button>

To be more specific you could declare an id in your element and use it so you do not have to reference the index of the tag. Otherwise you will need to reference the index of the tag as you are using getElementsByTagName().
Also as mentioned in the comment, the comparator is important.
= is used for assigning values to a variable.
== is used for comparing two variables, but it ignores the datatype of variable.
=== is used for comparing two variables, but this operator also checks datatype and compares two values.
var input = document.getElementById("myInput");
function btn() {
if (input.value === "") {
alert("no value");
} else {
alert(input.value);
}
}
<input id="myInput" type="text">
<button onclick="btn()" type="button" name="button">submit</button>

Related

Make alert appear when start typing input

I am trying to make something happen only when a user inputs data into an input element that has been created. However I don't want to validate that data has been inputted or make the user press a button to check if data has been inputted, I want something to happen as soon as the first data value is typed in the input field. I decide to just use a demo of something similar that I want to create - to cut out the clutter:
I have tried:
var input = document.getElementById("input");
if(input == ""){
alert("no value");
}else{
input.style.background = "blue";
}
<input type="text" id="input">
But nothing seems to be working. For what reason is it not working?
So in this example I would only want the background to be blue when the first data value is typed in.
I also tried:
var input = document.getElementById("input");
if(input.length == 0){
alert("no value");
}else{
input.style.background = "blue";
}
and:
var input = document.getElementById("input");
if(input == undefined){
alert("no value");
}else{
input.style.background = "blue";
}
as well as variations using != and !==
Is it something small I'm missing?
You were checking the actual element, not it's value. And, you didn't have any event listener set up for the element. But, it doesn't make much logical sense to check for no value after a value has been entered.
// When data is inputted into the element, trigger a callback function
document.getElementById("input").addEventListener("input", function(){
// Check the value of the element
if(input.value == ""){
alert("no value");
}else{
input.style.background = "blue";
}
});
<input type="text" id="input">
Try this,
jQuery
$('#input').keyup(()=>{
if($('#input').val() == ""){
alert("no value");
} else{
$('#input').css({backgroundColor: 'your-color'});
}
});
Hello you can try this
<input type="text" id="input" onkeyup="inputfun()">
<script type="text/javascript">
function inputfun(){
var input = document.getElementById("input");
if(input.value == ""){
input.style.background = "";
alert("no value");
}else{
input.style.background = "blue";
}
}
</script>
function handleCurrentInput(event) {
const value = event.target.value;
if (!value) {
alert("no value");
} else {
alert("value entered -->", value);
}
}
<input type="text" id="input" onInput="handleCurrentInput(event)">

Having trouble displaying an array value within console.log event using .push function in Jquery

The issue here is that I have designed a basic website which takes in a users input on a form, what I then intend to do is print that value out to the console.log. however, when I check the console under developer tools in Google Chrome, all I get printed out is []length: 0__proto__: Array(0)
and not the value the user has inputted.
<input type="text" name="username" value="testuser">
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script>
function error() {
var error1 = [];
var list_of_values = [];
username_error = $('input[name="username"]').val();
if (!username_error){
error1.push('Fill in the username field.');
}
console.log(error1);
if (error1.length > 0){
for(let username_error of error1){
alert(username_error);
return false;
}
}
string = $('input[name="username"]').val('');
if(string.length <= 1){
for (let list_of_values of string){
string.push();
}
console.log(string);
return true;
}
}
error();
</script>
Suggestion, you can make it actually things easier with the following code.
the function below scans all input fields under fieldset element
$("fieldset *[name]").each....
the issue above is multiple alert, what if you have a lot of inputs, it would alert in every input, which wont be nice for the users :) instead you can do this
alert(error1.toString().replace(/,/g, "\n"));
to alert the lists of errors at once.
string = $('input[name="username"]').val('');
that is actually clearing your value.. so it wont give you anything in console.log().
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<fieldset>
<input type="text" name="name" value="" placeholder="name"/><br/><br/>
<input type="text" name="username" value="" placeholder="username"/><br/><br/>
<button onclick="error()">check</button>
</fieldset>
<script>
function error() {
var error1 = [];
var list_of_values = [];
$("fieldset *[name]").each(function(){
var inputItem = $(this);
if(inputItem.val()) {
return list_of_values.push(inputItem.val());
}
error1.push('Fill in the '+inputItem.attr('name')+' field!')
});
if(error1.length > 0) {
console.log(error1);
alert(error1.toString().replace(/,/g, "\n"));
}
if(list_of_values.length > 0) {
console.log(list_of_values);
}
}
</script>
Register the <input> to the input event. When the user types anything into the <input> the input event can trigger an event handler (a function, in the demo it's log()).
Demo
Details commented in demo
// Reference the input
var text = document.querySelector('[name=username]');
// Register the input to the input event
text.oninput = log;
/*
Whenever a user types into the input...
Reference the input as the element being typed into
if the typed element is an input...
log its value in the console.
*/
function log(event) {
var typed = event.target;
if (typed.tagName === 'INPUT') {
console.log(typed.value);
}
}
<input type="text" name="username" value="testuser">

Validation on input field using javascript

I wants to check, if entered field's value is valid or not using onchange before submitting the page. I have written like below.It validates well.But how to activate 'NEXT' button when there is no error on input entries.
<div><input type="text" name="your_name" id="your_name" onchange = "validate_Name(this,1,4)" />
<span id="your_name-error" class="signup-error">*</span>
</div>
<div><input type="text" name="your_addr" id="your_addr" onchange = "validate_Name(this,1,4)" />
<span id="your_addr-error" class="signup-error">*</span>
</div>
<input class="btnAction" type="button" name="next" id="next" value="Next" style="display:none;">
<script type="text/javascript" src="../inc/validate_js.js"></script>
<script>
$(document).ready(function() {
$("#next").click(function() {
var output = validate(); //return true if no error
if (output) {
var current = $(".active"); //activating NEXT button
} else {
alert("Please correct the fields.");
}
});
}
function validate() {
//What should write here?I want to analyse the validate_js.js value here.
}
</script>
Inside validate_js.js
function validate_Name(inputVal, minLeng, maxLeng) {
if (inputVal.value.length > maxLeng) {
inputVal.style.background = "red";
inputVal.nextElementSibling.innerHTML = "<br>Max Characters:" + maxLeng;
} else if (!(tBox.value.match(letters))) {
inputVal.style.background = "red";
inputVal.nextElementSibling.innerHTML = "<br>Use only a-zA-Z0-9_ ";
} else {
inputVal.style.background = "white";
inputVal.nextElementSibling.innerHTML = "";
}
}
If by "activating" you want to make it visible, you can call $('#next').show().
However if you want to simulate a click on it, with jQuery you can simply call $('#next').click() or $('#next').trigger('click') as described here. Also, you might want to put everything in a form and programmatically submit the form when the input passes validation.
You could possibly trigger the change event for each field so it validates each one again.
eg.
function validate() {
$("#your_name").trigger('change');
$("#your_addr").trigger('change');
}

Get value from textbox based on checkbox on change event

I have two textboxes and one checkbox in a form.
I need to create a function javascript function for copy the first txtbox value to second textbox on checkbox change event.
I use the following code but its shows null on first time checkbox true.
function ShiptoBill()
{
var billing = document.getElementById("txtbilling").value;
var shipping = document.getElementById("txtshipping").value;
var check = // here i got checkbox checked or not
if(check == true)
{
// here I need to add the txtbilling value to txtshipping
}
}
Given that form controls can be accessed as named properties of the form, you can get a reference to the form from the checkbox, then conditionally set the value of txtshipping to the value of txtbilling depending on whether it's checked or not, e.g.:
<form>
<input name="txtbilling" value="foo"><br>
<input name="txtshipping" readonly><br>
<input name="sameas" type="checkbox" onclick="
this.form.txtshipping.value = this.checked? this.form.txtbilling.value : '';
"><br>
<input type="reset">
</form>
Of course you might want to set the listener dynamically, the above just provides a hint. You could also conditionally copy the contents over if the user changes them and the checkbox is checked, so a change event listener on txtbilling may be required too.
Try like following.
function ShiptoBill() {
var billing = document.getElementById("txtbilling");
var shipping = document.getElementById("txtshipping");
var check = document.getElementById("checkboxId").checked;
if (check == true) {
shipping.value = billing.value;
} else {
shipping.value = '';
}
}
<input type="text" id="txtbilling" />
<input type="text" id="txtshipping" />
<input type="checkbox" onchange="ShiptoBill()" id="checkboxId" />
function ShiptoBill()
{
var billing = document.getElementById("txtbilling");
var shipping = document.getElementById("txtshipping");
var check = document.getElementById("checkboxId").checked; // replace 'checkboxId' with your checkbox 'id'
if (check == true)
{
shipping.value = billing.value;
}
}
To get the event when it changes, do
$('#checkbox1').on('change',function() {
if($(this).checked) {
$('#input2').val($('#input1').val());
}
});
This checks for the checkbox to have a change, then checks if it is checked. If it is, it places the value of Input Box 1 into the value of Input Box 2.
EDIT: Here's a pure JS solution, and a JSBin too.
function ShiptoBill()
{
var billing = document.getElementById("txtbilling").value;
var shipping = document.getElementById("txtshipping").value;
var check = document.getElementById("thischeck").checked;
console.log(check);
if(check == true)
{
console.log('checked');
document.getElementById("txtshipping").value = billing;
} else {
console.log('not checked');
}
}
with
<input id="thischeck" type="checkbox" onclick="ShiptoBill()">

Javascript - text input to icon

I am trying to create a simple web application. Like in Facebook chat when I enter "(Y)" it turns into the thumbs up icon. Similarly I am trying to do something like that with the following code. But it is not working for me. I am not expert with JavaScript. I need some help that what's wrong with the code?
And I made the code in a way that if i enter "y" it will return LIKE. I want to know how to show an icon after "y" input.
<html>
<head>
<title>Emogic</title>
</head>
<body>
<input type="text" id="input">
<input onclick="appear()" type="submit">
<p id="output"></p>
<script>
function appear(){
var value = document.getElementByid("input").value
var result = document.getElementById("output").innerHTML
if(value == "y"){
result = "LIKE"
}
else if(value == ""){
alert("You must enter a valid character.");
}
else{
alert("Character not recognised.");
}
}
</script>
</body>
</html>
There are a few issues/typo in your code :
it's document.getElementById(), with a capital I in Id.
result will be a string, containing the innerHTML of your element, but not a pointer to this innerHTML : when you then set result to an other value, it won't change the element's innerHTML as you expected. So you need to create a pointer to the element, and then set its innerHTML from the pointer.
The quick fix of your code would then be :
function appear() {
var value = document.getElementById("input").value;
var output = document.getElementById("output");
if (value == "y") {
output.innerHTML = "LIKE";
} else if (value == "") {
alert("You must enter a valid character.");
} else {
alert("Character not recognised.");
}
}
<input type="text" id="input" value="y">
<input onclick="appear()" type="submit">
<p id="output"></p>
But you'll find out that your user will have to enter exactly "y" and only "y" for it to work.
I think you should use instead String.replace() method with a regular expression to get all occurences of a pattern, i.e, for "(Y)" it could be
function appear() {
var value = document.getElementById("input").value;
var output = document.getElementById("output");
// The Regular Expression we're after
var reg = /\(Y\)/g;
// your replacement string
var replacement = 'LIKE';
// if we found one or more times the pattern
if (value.match(reg).length > 0) {
output.innerHTML = value.replace(reg, replacement);
} else if (value == "") {
alert("You must enter a valid character.");
} else {
alert("Character not recognised.");
}
}
<input type="text" id="input" value="I (Y) it (Y) that">
<input onclick="appear()" type="submit">
<p id="output"></p>

Categories