not stuffing string values in js [closed] - javascript

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

Related

replace empty input with 0 and accept only numbers in input type text

I'm a JS learner. I want to display input values in each line (and it's done) but I want to prevent displaying empty values as empty space and replace them with "0". Also I want to force only numbers in the input. Can anyone help me?
<input type="text" id="user-input" onfocus = "this.value =''">
<button id="submit" onclick="addTo()">Submit</button>
<p class="demo"></p>
const myArr = [];
function addTo() {
myArr.push(document.getElementById("user-input").value);
if(myArr.value = "") {
myArr.value = 0;
}
document.querySelector(".demo").innerHTML = myArr.join("<br />")
}
Like you wrote you on the comments, you should change the input to type="number.
Then you must check if the input value in empty before adding it to the array.
Take a look at the example i create for you. There are other ways to do this, but i wanted to stay true to your original idea. i hope it helps you...
let myArr = [];
function addTo() {
const enteredValue = document.getElementById("user-input").value;
const readyValue = enteredValue === '' ? 0 : enteredValue;
myArr.push(readyValue);
document.querySelector(".demo").innerHTML = myArr.join("<br />")
}
<input type="number" id="user-input" onfocus="this.value =''">
<button id="submit" onclick="addTo()">Submit</button>
<p class="demo"></p>
No need for any javascript you can solve both by
<input type="number" placeholder="0">
Granted the placeholder will only show "0" on screen but will return blank as value

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>

Outputs not showing in simple odd/even code

I've just started beginning to code in JavaScript (my first attempt at any so please be patient!), so have just set myself a simple project just to create a input box, and was hoping upon clicking the calculate button to generate a "Even" or "Odd" output that shows up below the box. But somehow I can't get anything to show up. Any ideas what I'm doing wrong?
function myFunction() {
// define var num
var num = document.getElementById("number").value;
//use of if function as number is odd or even (modulo = 0 or 1)
if (num % 2 === 0) {
document.writeIn("Even");
} else {
document.writeIn("Odd");
}
}
<table id="number">
Number: <input type="number" name="name">
<input type="button" onclick="myFunction()" value="Calculate"></table>
You need to take an input with type 'text' and an id of 'number'.
Then get this value of the input and assign to another element the result, because document.writeln does not work after the page is rendered by the user agent.
function myFunction() {
var num = document.getElementById("number").value;
document.getElementById("type").innerHTML = num % 2 ? "Odd": "Even";
}
Number: <input type="text" id="number">
<input type="button" onclick="myFunction()" value="Calculate">
<div id="type"></div>

Generate range of sequential number without repetition

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())

How do I pass Text Field values in a Java Script function? [duplicate]

This question already has answers here:
Addition operation issues?
(5 answers)
Closed 5 years ago.
I am new to java script, I have three text fields with ids text1, text2, text3 respectively. I want to input values in 2 of them and print the sum in the third.
my code looks like this please tell me, what am I doing wrong.
it is adding them as string not numbers.
Also I want to make it like, if I enter value in any 2 of the three boxes. The other one adjusts itself.
EX: '__' + 5 = 7 => ' 2 ' + 5 = 7
will it work if I put variables in value attribute. if So then How?
<html>
<head>
<script>
function myCalculator(a, b) {
c = a + b;
document.getElementById("text3").value = c;
}
</script>
</head>
<body>
<p>
<h1>Calculator</h1>
<input type="text" value="" id="text1"></input> + <input type="text" value="" id="text2"></input> = <input type="text" value="" id="text3"></input>
<input type="button" value="ADD" onclick='myCalculator(document.getElementById("text1").value,document.getElementById("text2").value)'></input>
</p>
</body>
</html>
Use the Number() to convert the strings to numbers. Anything inside a text input.value will initially be a string.
function myCalculator(a, b) {
var c = Number(a) + Number(b);
document.getElementById("text3").value = c;
}
You need to call parseInt(text) on both parameters of myCalculator function to convert them to numbers first.
function myCalculator(a,b){
a = parseInt(a, 10); // convert to integer first
b = parseInt(b, 10);
c=a+b;
document.getElementById("text3").value = c;
}
The second parameter of parseInt function is radix, which needs to be 10 to read numbers in decimal system. It is 10 by default from ES5.
Replace Your Code this with text block , First remember to pass id in quotes and second format your value from string to javascript before adding.
<html>
<head>
<script>
function myCalculator(a,b){
var c=parseInt(a)+parseInt(b);
document.getElementById('text3').value = c;
}
</script>
</head>
<body>
<p>
<h1>Calculator</h1>
<input type="text" value="" id="text1"></input> + <input type="text" value="" id="text2"></input> = <input type="text" value="" id="text3"></input>
<input type="button" value="ADD" onclick='myCalculator(document.getElementById("text1").value,document.getElementById("text2").value)'></input>
</p>
</body>
</html>

Categories