Generate range of sequential number without repetition - javascript

Can anyone please help me with the code. im trying to generate numbers from range 12012300 to 12012400 in sequence and without repetition. Will be great if message is displayed saying generated number is reserved, below the textbox.
Thanks heaps in advance
<form>
<input name="code" id="code" type="text" placeholder="#########" value="" readonly />
<script type="text/javascript">
function makeid() {
return Math.floor(Math.random() * 100) + 12012300;
}
</script>
<input type="button" value="Generate Code" onclick="document.getElementById('code').value = makeid()"></input>
<input type="reset" value="Reset" />
</form>

You can use the basic example of closure, self-invoking function
If you need sequential numbers you do not need to use Math.random
let makeid = (() => {
let id = 12012300;
return () => {
if(id > 12012400 ) throw( 'max id reached')
return id++;
};
})();
console.log(makeid())
console.log(makeid())
console.log(makeid())

Related

Javascript parameters getting concatenated on trying to find sum [duplicate]

This question already has answers here:
Adding two numbers concatenates them instead of calculating the sum
(24 answers)
Closed 2 years ago.
In this script i am passing number values but i get them as concatenated values.Why is javascript behaving so.I use a function named add and passing two number parameters.Why is it considered as string.I am using chrome browser
<input type="number" id="num1"/>
<input type="number" id="num2"/>
<button onclick='alert(add(document.getElementById("num1").value,document.getElementById("num2").value))' >sum</button>
<script>
const add=function( num1, num2){
return num1+num2;
}
</script>
You should avoid inline javascript and place javascript code in external js file. For better readability, debug and testing purposes.
From #Sascha answer you should convert input text to number and then do the calculations using parseInt. Also, check #Ajeet_Eppakayala answer as an alternative solution.
let submBtn = document.getElementById('sbtBtn');
function calculate(e){
e.preventDefault();
let num1El = document.getElementById('num1');
let num2El = document.getElementById('num2');
let res = document.getElementById('result');
let num1 = parseInt(num1El.value);
let num2 = parseInt(num2El.value);
if (Number.isInteger(num1) && Number.isInteger(num2)){
res.innerHTML = add(num1,num2);
}else{
res.innerHTML = "Please enter numbers";
num1El.focus();
}
}
const add = (num1,num2) => {
return parseInt(num1) + parseInt(num2);
}
submBtn.addEventListener('click',calculate);
<form>
<input type="text" id="num1" />
<input type="text" id="num2" />
<input type="submit" id="sbtBtn" value="Sum" />
<p id="result"><p>
</form>
Because you get the values from an Input-field and this is allways from type string. So you had to use parseInt to get an Integer.
const add=function( num1, num2){
return parseInt(num1)+parseInt(num2);
}
<input type="number" id="num1"/>
<input type="number" id="num2"/>
<button onclick='alert(add(document.getElementById("num1").value,document.getElementById("num2").value))' >sum</button>
You need to parse values to int.
ShortHand for Int parsing is + operator or simple parseInt(<stringNumber>).
const add = function( num1, num2){
return +num1 + +num2;
}
<input type="number" id="num1"/>
<input type="number" id="num2"/>
<button onclick='alert(add(document.getElementById("num1").value,document.getElementById("num2").value))' >sum</button>

not stuffing string values in js [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 2 years ago.
Improve this question
I want to randomize user input string using sort() function..
but it's not working properly. Can anybody help me solving this problem?
function getAndSetVal() {
var txt1 = document.getElementById('txt').value;
document.getElementById('txt2').value = txt1;
}
// get value
function getVal() {
var txt = document.getElementById('txt').value;
alert(txt);
txt1.sort(function() {
return .5 - Math.random();
});
}
<input type="text" id="txt" name="txt" onclick="this.value = '' " />
<button onclick="getAndSetVal();">Get Value</button>
<input type="text" id="txt2" name="txt" onclick="this.value = '' " />
You need to split the word, sort, and re-join.
If the random number i.e. 0 -> 1 falls in:
the first third, return -1
the last third, return +1
the middle, return 0
Edit: Instead of Math.random() (which is predictable), you can implement a seeded random number generator. David Bau's seedrandom library is light-weight and easy to integrate into your JavaScript application.
Just drop the script in your <head> and instantiate a new random number generator with a seed of the current time in milliseconds.
var random = new Math.seedrandom(new Date().getTime());
function shuffle() {
document.getElementById('txt2').value = randomSort(document.getElementById('txt').value);
}
function randomSort(value) {
return value.trim().split(/\s*,\s*/).sort((a, b) => {
return ((p) => {
return p < (1/3) ? -1 : p > (2/3) ? +1 : 0;
})(random()); // Instead of Math.random()
}).join(', ');
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/seedrandom/3.0.5/seedrandom.min.js"></script>
<input type="text" id="txt" name="txt" value="Banana, Orange, Apple, Mango" />
<button onclick="shuffle()">Shuffle</button>
<input type="text" id="txt2" name="txt" />
String are arrays in some sense but not really, so you have to create an array to use the sort function, try like this:
function shuffle(){
document.getElementById('txt2').value = getVal();
}
function getVal()
{
const txt = document.getElementById('txt').value;
return txt
.split(",")
.map(word => word.trim())
.sort((a, b) => Math.random() > .5 ? 1 : -1)
.join(", ");
}
<input type="text" id="txt" name="txt" value="orange, avocato, banana, fruit" />
<button onclick="shuffle()">Shuffle</button>
<input type="text" id="txt2" name="txt" />
And the sort function pass two parameter and expect return the values 1, -1 or 0.
1 when the first parameter should came first
-1 when the second parameter should came first
0 when doesn't matter the order between both parameters

jquery to find numbers with regular expressions not working

I have a script to find numbers with in the following format (***)***-***
but it doesn't seem to be working. I tried finding phone numbers with only dashes and that worked but when adding the parenthesis doesn't seem to work
$(document).ready(function () {
$('body').html($('body').html().replace(/(\(\d\d\d\)-\d\d\d-\d\d\d\d)/g, '<span style="display:inline-block;">$1</span>'));
});
If you want to find phone numbers like this (***)***-***, use
/\(\d{3}\)\d{3}-\d{3})/g
function replace(){
var myNewTitle = document.getElementById('myTextField').value;
if( myNewTitle.length==0 ){
alert('empty');
return;
}
var title = document.getElementById('title');
title.innerHTML = myNewTitle.replace(/(\(\d\d\d\)-\d\d\d-\d\d\d\d)/g, '###');
}
<h1 id="title">Example</h1>
<input type="text" id="myTextField" value="phone (123)-123-1234"/>
<input type="submit" id="byBtn" value="Change" onclick="replace()"/>

Number Converter JQuery

I am a beginner and I have the following problem/code for the main body:
<body>
<form action="#">
<input type="text" id="start" />
=
<input type="text" id="finish" />
</form>
<script>
$(function() {
var cVal = $("#start").val();
var fVal = $("#finish").val();
});
</script>
</body>
With two text boxes, I would like the value entered in the celsius text box to be converted into fahrenheit in the other text box. I have tried to use the
keyup()
function but failed to produce the results I want.
typing 15 into the celsius box should result in 59 in fahrenheit. I understand that .val() does not take any arguments, so where would I do the computation for converting the numbers? And how can I incorporate keyup?
Any help is appreciated!
The val function does take arguments, you can pass it the new value and it will update textbox contents. Click the link on val, it will take you to the jQuery documentation, where all possible calls are explained. Or see the example below.
function fahrenheitToCelsius(fahrenheit) {
var val = 0;
// perform calculation
return val;
}
function celsiusToFarenheit(celsius) {
var val = 0;
// perform calculation
return val;
}
$(function() {
$("#start").on('keyup', function() {
$("#finish").val(celsiusToFarenheit($(this).val()));
});
$("#finish").on('keyup', function() {
$("#start").val(fahrenheitToCelsius($(this).val()));
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form action="#">
<input type="text" id="start" /> Celsius
=
<input type="text" id="finish" /> Fahrenheit
</form>
This is such a simple thing to do, jQuery is not needed at all, and because you haven't tagged jQuery here comes a plain javascript solution.
What you need to do is the add a keyup trigger on each of the input elements.
To grab our input fields we use document.getElementById(id), we use this because you've added the id attribute to your fields (it's faster than the latter method I'm mentioning). We could've used document.querySelector(selector) to get our input fields to. If you had used name="celsius" on the celsius field, we could've used document.querySelector('input[name="celsius"]') to grab that element.
What we need to do next is to an a keyup trigger to both our input fields. This is done with element.onkeyup = function() {}, in each of those functions we calculate the value for the other field.
var celsius = document.getElementById('start'),
fahrenheit = document.getElementById('finish');
celsius.onkeyup = function() {
fahrenheit.value = this.value * 9/5 + 32;
}
fahrenheit.onkeyup = function() {
celsius.value = (this.value - 32) * 5/9;
}
<form action="#">
<input type="text" id="start" /> Celsius
=
<input type="text" id="finish" /> Fahrenheit
</form>
The jQuery .val() function is an overload function which means it takes 0 up to 1 argument and it's effect varies on the number of arguments passed.
As you can see in my example calling celsiusInput.val() just returns the current value of the field. However if you use it like this farenheitOutput.val(farenheit) the current value of the input is overwritten by the variable passed.
const updateFarenheit = () => {
// find the input and output in the dom by their id
const celsiusInput = $("#start");
const farenheitOutput = $("#finish");
// get the input value
const celsius = celsiusInput.val();
const farenheit = celsius * 9 / 5 + 32;
// update the farenheit output
farenheitOutput.val(farenheit);
}
// this function runs when all js is loaded aka. "document ready"
$(document).ready(function() {
// get input field by id
const celsiusInput = $("#start");
// we pass the updateFarenheit function we defined before as the function which should run
// as soon as the keyup event occures on our celsiusInput field
celsiusInput.keyup(updateFarenheit);
});
<html lang="">
<head>
<meta charset="utf-8">
<title>Celsius to Farenheit</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
</head>
<body>
<form action="#">
<input type="text" id="start" /> =
<input type="text" id="finish" />
</form>
</body>
</html>

How do I pass form values to other fields in a form with javascript

I'm Working with form validation and fields for the first time without inline event handling. I can't find an example of how to pass a integer value, do a operation on it and pass to another field. This is what I'm up against:
FORM LOOKS LIKE THIS:
ITEM CONTAINER QUANTITY PRICE EXTENDEDCOST
Small Beer Bottle,Can ?? #3.99/ea ??
HTML BITS
<form action="#" method="get" name="orderForm" id="orderForm">
<table id="products">
<input name="qtySmall" id="qtySmall" type="text" size="4" maxlength="6" value="" />
<input name="extSmall" id="extSmall" type="text" size="10" maxlength="60" value="" />
Javascript
window.onload = initForms;
function initForms()
{
document.getElementById("qtySmall").onfocus = detect;
document.getElementById("qtySmall").onchange = going_away;
document.getElementById("extSmall").value = passmyvalue; //not sure about this one yet
}
function detect()
{
alert("works")
}
function going_away()
{
pass_variable = document.getElementById("qtySmall").value;
}
function passmyvalue()
{
// I have no idea how to pass my qty small multiply it and pass it to the next field box 4 beers * 3.99 = 15.96 in extsmall
}
Thanks for the Help
Not sure if I am understanding your problem here. Can't you just change your going_away function to do the following?
function going_away()
{
pass_variable = document.getElementById("qtySmall").value;
document.getElementById("extSmall").value = parseInt(pass_variable) * cost;
}

Categories