How to adjust the length of random password? - javascript

Good morning,
I have this code (just an example):
function random(min, max) {
return min + parseInt(Math.random() * (max - min + 1));
}
function generatePassword(length, charset) {
var password = "";
while (length--) {
password += charset[random(0, charset.length - 1)];
}
return password;
}
function getNewPassword() {
$('#password').text(generatePassword(12, "AaBbCcDdEeFfGgHhIiJjKkLlMmNnOoPpQqRrSsTtUuVvWwXxYyZz0123456789!?##*&.,;:+-=()[]_"));
}
And would like to add an input field in HTML, where I can set the length of the generated password.
Can you please find with me a solution? :-)
http://jsfiddle.net/RnsTq/

Instead of the 12 in the call to generatePassword use parseInt($('#len').val(), 10), where len would be the id of the input element.

There you have it: http://jsbin.com/odosoy/94/edit
Javascript
$(document).ready(function() {
$("#generate").click(function() {
getNewPassword();
});
function random(min, max) {
return min + parseInt(Math.random() * (max - min + 1), 10);
}
function generatePassword(charset) {
var length = parseInt($("#passlength").val(), 10);
var password = "";
while (length--) {
password += charset[random(0, charset.length - 1)];
}
return password;
}
function getNewPassword() {
var pass = generatePassword("AaBbCcDdEeFfGgHhIiJjKkLlMmNnOoPpQqRrSsTtUuVvWwXxYyZz0123456789!?##*&.,;:+-=()[]_");
$('#password').val(pass);
}
});
HTML
Length: <input id="passlength"/><br>
Password: <input id="password"/><br>
<button class="btn btn-info" id="generate">Generate Password</button>
Update
Just reworked and styled your initial example a bit, nothing really special.
http://jsbin.com/odosoy/97/edit and one in which the password is replaced: http://jsbin.com/odosoy/125/edit
Hope it helps.

look at this:
function gen_random(len){
var charset = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";
var tempChar = charset.split('');
for (var i = 0; i < len; ++i) {
password += tempChar[Math.floor(Math.random() * (26+26+10)) + 1];
}
return password;
}

Try to add a new text field and take it's value before you generate your password.
var passwordLength = $('#maxLength').val();
$('#password').val(generatePassword(passwordLength, "AaBbCcDdEeFfGgHhIiJjKkLlMmNnOoPpQqRrSsTtUuVvWwXxYyZz0123456789!?##*&.,;:+-=()[]_"));
You can see a quick & dirty fiddle here: http://jsfiddle.net/nininho/pG5A7/1/

Try something like this:-
Math.random().toString(36).substring(7);

The best way to generate a password in JS is to use a lib such as https://github.com/bermi/password-generator
That will generate you a password with a customizable length that even can be memorable.
There's also several example on the link provided.

Related

Display times table up to 12 based on the users input

it seems to think ttinput is a string when I console.log the variable it says "". All else seems to working I just can't figure out how to have ttinput as a number.
document.getElementById("enter").addEventListener("click", ttcalc)
var ttinput = document.getElementById("table").value;
var ttoutput;
function ttcalc(){
var display = "";
for(var i = 1; i <= 12; i++){
ttoutput = ttinput * i;
display += ttinput + "*" + i + "=" + ttoutput + "<br>"
console.log(ttoutput, ttinput, i);
}
document.getElementById("output").innerHTML = display;
}
this is my html
<form>
<h1>Enter what times table you wish to see</h1>
<input type="number" id="table"><br>
</form>
<button id="enter">Show Times Table</button>
</div>
The problem is that the value of
var ttinput = document.getElementById("table").value;
is read on page load (while the input field is empty). If you move that line of code inside your function it will read the value of the input field after the button is clicked.
If you want to be sure the value entered is a number you can use the parseInt() function and then check if the result is a number with the isNaN() function like this:
var ttinput = parseInt(document.getElementById("table").value);
and then use isNaN():
if( !isNaN(ttinput) ) {
// ttinput is a number
} else {
// ttinput is not a number
}
More here: parseInt and isNaN.
Check example below:
document.getElementById("enter").addEventListener("click", ttcalc)
function ttcalc() {
var ttinput = parseInt(document.getElementById("table").value);
var ttoutput;
var display = "";
if( !isNaN(ttinput) ) {
for(var i = 1; i <= 12; i++) {
ttoutput = ttinput * i;
display += ttinput + "*" + i + "=" + ttoutput + "<br>"
console.log(ttoutput, ttinput, i);
}
document.getElementById("output").innerHTML = display;
} else {
console.log("value is not a number");
}
}
<button id="enter">Enter</button>
<input type="text" id="table" value="">
<div id="output"></div>

Create form for function Html

This is my problem, hope get some support for this.
This is my function.
function show(n,q)
{
for(j=1;j<=n;j++)
{
s=j.toString().length;
t=0;
for(i=s-1;i>=0;i--)
{
t+=Math.pow((Math.floor(j/Math.pow(10,i))%10),q);
}
if(t==j){document.write(t+ " ");}
else{document.write("");}
}
}
show(1000,3);
With two inputs: number n and the exponent q it will solve all the numbers smaller than n which the sum of all the q-exponented of its digits is equal to itself.
For example: q=3, n=200, we have the number 153 because: 1^3 + 5^3 + 3^3 = 153
This function is OK, but due to my bad javascript skill, I dont know how to create a form alowing to enter n and q into 2 boxes, then click button "Show" we have results in the third box.
I have tried this below code, but it does not work :(
<input id='number' type='text' />
<input id='exp' type='text' />
<button onclick='javascript:show()'>Show</button>
<div id='res' style='width:100%;height:200px'></div>
<script>
function show() {
var n=document.getElementById('number').value,
var q=document.getElementById('exp').value,
out=document.getElementById('res'),
out.innerHTML="";
for(j=1;j<=n;j++)
{
s=j.toString().length;
t=0;
for(i=s-1;i>=0;i--)
{
t+=Math.pow((Math.floor(j/Math.pow(10,i))%10),q);
}
if(t==j){
out.innerHTML+=t+ " ";
}
else{
out.innerHTML+="";
}
}
}
</script>
In additon, I want to do it myself, could you guys tell me where i can find guide for this problem.
Thanks.
Your code has some punctuation issues.
Try to replace:
var n=document.getElementById('number').value,
var q=document.getElementById('exp').value,
out=document.getElementById('res'),
out.innerHTML="";
by
var n=document.getElementById('number').value,
q=document.getElementById('exp').value,
out=document.getElementById('res');
out.innerHTML="";
The code looks fine and will do what you are trying to do. Just there are some , (Comma) instead of ; (Semi-colon) in your code. Change them and then try.
Check the solution here.
http://jsfiddle.net/JszG2/
var n=document.getElementById('number').value;
var q=document.getElementById('exp').value;
out=document.getElementById('res');
Below is solution using JQuery....
<script>
function show() {
var num = parseInt($('#number').val());
var exp = parseInt($('#exp').val());
out = $('#res');
var num = document.getElementById('number').value;
var exp = document.getElementById('exp').value;
out = document.getElementById('res');
out.innerHTML = "";
for (p = 1; p <= num; p++) {
q = p.toString().length;
v = 0;
for (i = q - 1; i >= 0; i--) {
v = v+ Math.pow((Math.floor(p / Math.pow(10, i)) % 10), exp);
}
if (v == p) {
out.innerHTML += v + " ";
}
else {
out.innerHTML += "";
}
}
}
</script>

adding a result of a calculation to a span with javascript after a button is clicked

Hi I'm new to javascript and I would like you to help me figure out why I can't get the result of the random number generator to appear in the span tag after the user clicks a calculate button using the min and max number they entered. I believe there is nothing wrong with the random number function it's just when I want to use the random number function as an event handler for the onclick event for the button it doesn't work. well, what I did was, I made a function called answer to gather the users input and to use that input as a parameter for the the random number function that is being called inside the answer function.
Then I used the answer function as an event handler for the onclick thinking that it would have the result of the the random number generator and would apply that to the onclick. and I stored that in var called storage so I could place the result of the event in the span tag later.
Here is the js fiddle of the code. can you help me solve my problem by getting the result of the random_number function in to the span $("output") after the button $("calculate") click?
only pure javascript, no jquery please.
Thank you in advance for your help. and I'm sorry if I got terminology wrong and for bad spelling. http://jsfiddle.net/jack2ky/WDyMd/
<label for="min">Enter the min:</label>
<input type="text" id = "min" /> <br />
<label for="max">Enter the max:</label>
<input type="text" id = "max" /> <br />
<input type="button" id = "calculate" value = "calculate"/>
<span id ="output"> </span>
<script>
var $ = function(id){
return document.getElementById(id);
}
window.onload = function () {
var random_number = function(min, max, digits){
digits = isNaN(digits) ? 0 : parseInt(digits);
if(digits < 0){
digits = 0;
}else if (digits > 16){
digits = 16
}
if(digits == 0){
return Math.floor(Math.random() * (max - min +1)) +min;
}else {
var rand = Math.random() * (max - min) + min;
return parseFloat(rand.toFixed(digits));
}
}
var storage = $("calculate").onclick = answer;
var answer = function(){
var miny = $("min").value;
var maxy = $("max").value;
return random_number(miny, maxy);
}
$("output").firstChild.nodeValue = storage;
}
</script>
</body>
</html>
var storage = $("calculate").onclick = answer;
...
$("output").firstChild.nodeValue = storage;
These two statements are called on page load. What is happening is you are changing the value of variable storage but the statement var storage = $("calculate").onclick = answer;
is being called only once when the page loads. You need to update the answer when user clicks the button. So you can remove $("output").firstChild.nodeValue = storage; and update the answer function like:
var answer = function(){
var miny = parseInt( $("min").value );
var maxy = parseInt( $("max").value );
var ans = random_number(miny, maxy);
$("output").innerHTML = ans;
}
This should do it:
<!DOCTYPE html>
<html>
<head>
<script>
var $ = function(id){
return document.getElementById(id);
}
window.onload = function () {
var random_number = function(min, max, digits){
digits = isNaN(digits) ? 0 : parseInt(digits);
if(digits < 0){
digits = 0;
}else if (digits > 16){
digits = 16
}
if(digits == 0){
return Math.floor(Math.random() * (max - min +1)) +min;
}else {
var rand = Math.random() * (max - min) + min;
return parseFloat(rand.toFixed(digits));
}
}
$("calculate").onclick = function() {
var miny = $("min").value;
var maxy = $("max").value;
$("output").firstChild.nodeValue = random_number(miny, maxy);
}
}
</script>
</head>
<body>
<label for="min">Enter the min:</label>
<input type="text" id = "min" /> <br />
<label for="max">Enter the max:</label>
<input type="text" id = "max" /> <br />
<input type="button" id = "calculate" value = "calculate"/>
<span id ="output"> </span>
</body>
</html>
$("output").firstChild.nodeValue = storage;
This line seems to be the problem because your output-Element has no firstChild. So the value gets written nowhere.
Just use
> $("output").nodeValue = storage;
edit: Tested this in jsFiddle - this is not the solutions as mentioned below!
If You are able to get your value in the variable storage
then you can simply render this value in span as HTML
$("#output span").html = storage;

Why cant i enter decimal values in input in the following case

Before anything you need to see the effect:
jsFiddle
As you can see it is a calculator where you can put a value anywhere and covert it to other values, but the problem is that i cant enter decimal int values like 0.3 or 0.999. What is the cause of this?
var id = {
mm: 1,
cm: 10,
m: 1000,
km: 1000000
};
$('input.bx').on('keyup', function() {
var t = $(this).val();
var i = id[$(this).attr("id")];
var v = parseInt(t, 10);
for (pp in id) {
if (t !== '') {
$("#" + pp).val(v / id[pp] * i);
} else {
$(".bx").val('');
}
}
});
<input type='text' class='bx' id='mm'> Milimeter<br>
<input type='text' class='bx' id='cm'> Centimeter<br>
<input type='text' class='bx' id='m'> Meter<br>
<input type='text' class='bx' id='km'> Kilometer<br>
parseInt is the "problem" since it returns integer - decimal values are not integer but floats. If you want that you must replace it with parseFloat.
1.First you need to use parseFloat because int cant have decimals.
2.Second i would use onChange.
http://jsfiddle.net/Kfkjy/10/
a working fiddle here
you have to use parseFloat and dont try to set the current focused element value cause you are over riding it while typing.
this example is working fine
http://jsfiddle.net/Mohamed_aboelenen/D6T7j/1/
$('input.bx').on('keyup', function() {
var t = $(this).val();
var i = id[$(this).attr("id")];
var v = parseFloat(t, 10);
var a = $(this).attr("id"); // the textbox you write in
for (pp in id) {
if (t !== '' ) {
if(a != pp){ // make changes to any textbox except the one you write in
$("#" + pp).val(v / id[pp] * i);
}
} else {
$(".bx").val('');
}
}
});
$('input.bx').on('blur', function() {
var t = $(this).val();
var i = id[$(this).attr("id")];
var v = Number(t, 10);
for (pp in id) {
if (t !== '') {
$("#" + pp).val(parseFloat(v / id[pp] * i));
} else {
$(".bx").val('');
}
}
});

how to change a javascript result from selectbox to textarea?

What I need to do I take the result from this code..
function genNumbers(listbox) {
var i, rannum;
for(i = 0; i < 1; i++) {
rannum = Math.random()*100000000;
rannum = Math.round(rannum);
if(listbox.options[i] == null) {
listbox.options[i] = new Option( rannum + "#domain.com", rannum + "#domain.com", 0, 0 );
} else {
listbox.options[i].value = rannum;
listbox.options[i].text = rannum + "#domain.com";
}
}
}
<form>
<select name="ranlist" size= "2" style="width:180px"></select><br><br>
<input type="button" value="Generate Random Email" onclick="genNumbers(this.form.ranlist)";>
And make the result appear in a text area. What I am using this for is to generate a random email address for people that dont have an email account when we sign up people in joomla. It all works except I need the result to show in a text area/textbox so i can copy paste it out and into the email field if needed.
Any helps would be great!
Cheers
Jimmy
Just set its value property:
textarea.value = 'foo';

Categories

Resources