Javascript or jQuery fill data based on value - javascript

I am currently trying to get a solution in order to simplify the login for my staff. Ideally I am looking for a js or jQuery script that pre-fills 2 input fields based upon the data they enter.
E.g. the main field should be: Enter token
IF the token equals 123 then fill input1 and input2 with certain amount of data, while if the token is 456 fill it with other data - if no token matches then do not fill any data. I know this is very unsecure but since it's something running only locally it would work for my specific needs.
<style>.hidden {display: none !important;}</style>
<form>
<input id="token" type="text">
<input class="hidden" id="input1" type="text">
<input class="hidden" id="input2" type="password">
<input type="submit">
</form>
Some advice would be greatly appreciated, thank you

Its pretty simple, You can get the desired result by using the conditional statement like if else.
here is the solution for your problem.
var token=$('#token').val();
if(token==123)
{
$('#input1').val('value1'); //set the value which you want to place here
$('#input2').val('value2'); //set the value which you want to place here
}
else if(token==456)
{
$('#input1').val('value1'); //set the value which you want to place here
$('#input2').val('value2'); //set the value which you want to place here
}
else {
$('#input1').val('');
$('#input1').val('');
}

You're basically wanting to add an input event listener to #token and set the values of the hidden inputs based on the value entered.
Something like this should suffice...
// make sure this script goes AFTER the HTML
// A map of token to values
const secrets = {
123: {
input1: 'input1 123',
input2: 'input2 123'
},
456: {
input1: 'input1 456',
input2: 'input2 456'
}
}
const input1 = document.getElementById('input1')
const input2 = document.getElementById('input2')
document.getElementById('token').addEventListener('input', e => {
const token = e.target.value
// get the values or if the token doesn't exist, sensible defaults
const secret = secrets[token] || {
input1: '',
input2: ''
}
input1.value = secret.input1
input2.value = secret.input2
}, false)
<form>
<input id="token" type="text" placeholder="Enter token">
<input class="hidden" id="input1" type="text">
<input class="hidden" id="input2" type="password">
<input type="submit">
</form>

Try the jquery code given below:
<script
src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js">
</script>
<script type="text/javascript">
$('#token').keyup(function() {
if($(this).val() == 123) {
$('#input1').val('1'); //assign the value you want
$('#input2').val('1'); //assign the value you want
} else if($(this).val() == 456) {
$('#input1').val('2'); //assign the value you want
$('#input2').val('2'); //assign the value you want
} else {
$('#input1').val('');
$('#input2').val('');
}
});
</script>

Related

I want to restrict users from entering number ending with 5

Here is text field.I want users to only enter value like 210,220,230,... and restrict from entering something like 215,225,...
I am looking for suggetions.I don't have much knowledge of javascript.
If you just want to prevent strings that end in '5':
document.getElementById("input").onblur = checkEND;
function checkEND() {
let firstValue = event.currentTarget.value;
if(firstValue.endsWith('5')){
warnUser()
}
}
This won't validate that the string is a valid number though.
function testInput() {
var key = window.event.keyCode;
var x = document.getElementById('textarea').value
var y = document.getElementById('textarea2').value
var z = parseInt(x, 10);
if (z+10 == y) {
document.getElementById('result').innerHTML = "valid";
} else {
document.getElementById('result').innerHTML = "invalid";
}
}
<textarea maxlength="3" id="textarea">5</textarea>
<textarea maxlength="3" id="textarea2">15</textarea>
<button onclick="testInput()">Test Input</button>
<div id="result"></div>
The first input is your first number, the second is your second number.
See Comments If Your Wondering Why This Doesn't Answer His OG Question
You can experiment with the setCustomValidity() of input elements (https://developer.mozilla.org/en-US/docs/Web/API/HTMLInputElement) from an onblur, onchange or oninput handler. If you are not satisfied with the value, set an error message, and an empty string otherwise. As long as the error message is set to non-empty, it is displayed and the form refuses to submit:
function check5() {
cgiftcardq.setCustomValidity(cgiftcardq.value.endsWith('5')?"Nope, it can not end with 5":"");
}
<form>
<input name="cgiftcardq" class="text_field" id="cgiftcardq" size="3" autocomplete="off" type="text" onblur="check5()">
<input type="submit" value="Send">
</form>
(StackOverflow snippets interfere with form submission - probably as part of security -, so successful submission just makes the form disappear)
As setCustomValidity() does not work everywhere (according to the compatibility table, it will not work on non-Andorid mobiles), classic "budget" solution may be mentioned too: you can simply disable the send button as long as you are not satisfied with the input:
function check5() {
if(cgiftcardq.value.endsWith('5')){
send.disabled=true;
message.innerHTML="Nope, it can not end with 5";
} else {
send.disabled=false;
message.innerHTML="OK";
}
}
<form>
<input name="cgiftcardq" class="text_field" id="cgiftcardq" size="3" autocomplete="off" type="text" oninput="check5()">
<input id="send" type="submit" value="Send" disabled>
</form>
<div id="message"></div>

Insert missing letter javascript game

I'm making a language learning game with javascript. I want the user to be able to write the missing letter and the results to be validated through javascript if they are right or wrong.
<form>
De<input id="letterone" type="text" name="latter" pattern="[A-Za-z]{1}">
ign<input id="lettertwo" type="text" name="latter" pattern="[A-Za-z]{1}">r
<input type="submit">
</form>
My javascript code.
if ((getElementById('letterone')==='s') && (getElementById('lettertwo')==='e')) {
alert('Correct');
}else{
alert('Wrong');
}
There are number of errors on your code :
No 'document' before getElementById
No 'value' after the object
No click handler
Incorrect id while accessing the object
Using input type=submit causes an unwanted page refresh as Useless Code comments below.
document.getElementById('submit').addEventListener('click', function() {
if ((document.getElementById('latterone').value==='s') && (document.getElementById('lattertwo').value==='e')) {
alert('Correct');
}else{
alert('Wrong');
}
});
<form>
De<input type="text" id="latterone" pattern="[A-Za-z]{1}">
ign<input type="text" id="lattertwo" pattern="[A-Za-z]{1}">r
<input type="button" id="submit" value="Submit">
</form>
var lOne = document.getElementById('letterone').value; // get the value of the first input
var lTwo = document.getElementById('lettertwo').value; // get the value of the second
if (lOne === 's') && lTwo === 'e') {
alert('Correct');
}else{
alert('Wrong');
}

How to validate a simple web form

Im working on a small form and using js to validate if the fields are empty or not. I have a span class next to the name field "name" "email".
For the "name" field, i have a span class called "error".
For the "email" field, i have another span class called "error2".
what can i do to only use one class to display the "error message", because of course i will have more field and I don't want to keep adding more classes. error3, error4
HTML:
<form action="#i" name="myForm" onsubmit="return(validate());">
Name: <span id="error"></span><br>
<input type="text" name="Name" /><br><br>
EMail: <span id="error2"></span><br>
<input type="text" name="EMail" /><br> <br>
<input type="submit" value="Submit" /> <br>
</form>
JS:
function validate()
{
var t = 0;
if( document.myForm.Name.value == "" )
{
document.getElementById('error').innerHTML = "<br>Empty";
t = 1;
}
if( document.myForm.EMail.value == "" )
{
document.getElementById('error2').innerHTML = "<br>Empty";
t = 1;
}
if(t == 1)
{
return false;
}
else
return true;
}
Instead of giving the spans the attribute of Id, use classes instead. So for example, you can define ALL your spans as follows:
<span class="error"> ... </span>
Then, in your validate function, you can obtain these spans through:
document.getElementsByClassName('error');
Keep in mind though, this returns an array, which would actually be perfect for your function. This way, you can write a basic for-loop to go through each span and make sure each field is filled in correctly.

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>

Fill data in input boxes automatically

I have four input boxes. If the user fills the first box and clicks a button then it should autofill the remaining input boxes with the value user input in the first box. Can it be done using javascript? Or I should say prefill the textboxes with the last data entered by the user?
On button click, call this function
function fillValuesInTextBoxes()
{
var text = document.getElementById("firsttextbox").value;
document.getElementById("secondtextbox").value = text;
document.getElementById("thirdtextbox").value = text;
document.getElementById("fourthtextbox").value = text;
}
Yes, it's possible. For example:
<form id="sampleForm">
<input type="text" id="fromInput" />
<input type="text" class="autofiller"/>
<input type="text" class="autofiller"/>
<input type="text" class="autofiller"/>
<input type="button"value="Fill" id="filler" >
<input type="button"value="Fill without jQuery" id="filler2" onClick="fillValuesNoJQuery()">
</form>
with the javascript
function fillValues() {
var value = $("#fromInput").val();
var fields= $(".autofiller");
fields.each(function (i) {
$(this).val(value);
});
}
$("#filler").click(fillValues);
assuming you have jQuery aviable.
You can see it working here: http://jsfiddle.net/ramsesoriginal/yYRkM/
Although I would like to note that you shouldn't include jQuery just for this functionality... if you already have it, it's great, but else just go with a:
fillValuesNoJQuery = function () {
var value = document.getElementById("fromInput").value;
var oForm = document.getElementById("sampleForm");
var i = 0;
while (el = oForm.elements[i++]) if (el.className == 'autofiller') el.value= value ;
}
You can see that in action too: http://jsfiddle.net/ramsesoriginal/yYRkM/
or if input:checkbox
document.getElementById("checkbox-identifier").checked=true; //or ="checked"

Categories

Resources