In Java Script Text box Name Doesn't like - javascript

I don't want to change my text box name in Form because it' using some where else in program.
Problem is JavaScript doesn't like my textbox name (m4j-117). it's Considering "-" as minus.
How can I make it work with out change my text box name.
Thanks
Any help will be appreciate.
Here is my Sample Code.
<form name="randform">
<body>
<script language="javascript" type="text/javascript">
function randomString() {
var chars = "0123456789";
var string_length = 8;
var randomstring = '';
for (var i=0; i<string_length; i++) {
var rnum = Math.floor(Math.random() * chars.length);
randomstring += chars.substring(rnum,rnum+1);
}
document.randform.m4j-117.value = "P"+randomstring;
}
</script>
<input type="button" value="Create Random String" onClick="randomString();">
<input type="text" name="name" value="value" onblur="randomString();;"/>
<input type="text" name="m4j-117" value="">
</body>
</form>

How about:
document.getElementsByName("m4j-117")[0].value = "P"+randomstring;
From a specific form:
document.randform.elements["m4j-117"] = "P"+randomstring;

document.randform['m4j-117'].value
Relying on names is a bit antiquated though; I'd suggest giving it an ID and using document.getElementById directly, or using querySelector with an appropriate ID for the form

Related

create input text with loop js

I would like to know how could I create many <input type=text /> tags with a loop in JS.
I need that loop to be linked to a first input (type=number), which tell to the loops how many input text to create.
function getP () {
var nbP = Number(document.getElementById("nombreP").value);
for (var i = 0; i < nbP; i++) {
var newForm = document.createElement("input[type=text]");
newForm.id = "form"+i
document.body.appendChild(newForm);
}
}
<form method="get">
<input type="number" name="nombrePlat" id="nombreP">
<input type="submit" value="Envoyer" id="ok" onclick="getP()">
</form>
Direct answer to your question:
<script type="text/javascript">
function getP() {
var nbP = +document.getElementById("nombreP").value;
var inputContainer = document.getElementById("inutContainer");
for (var i = 0; i < nbP; i++) {
var newForm = document.createElement("input");
newForm.setAttribute("type", "text");
newForm.setAttribute("id", "form"+i);
inputContainer.appendChild(newForm);
inputContainer.appendChild(document.createElement("br"));
}
}
</script>
<form>
<input type="number" name="nombrePlat" id="nombreP">
<input type="button" value="Envoyer" id="ok" onclick="getP()">
<div id="inutContainer">
</div>
</form>
BUT: this is good question to learn about Javascript and HTML, but bad to create powerfull UI. To implement modern UI in JS/HTML i am strongly recommend to learn more abou next technologies:
https://reactjs.org/ or https://angular.io/ or https://vuejs.org/
I hope it helps:
document.querySelector('#ok').addEventListener('click', getP)
function getP(event) {
let inputsQtt = document.querySelector('input[type=number]').value
for (let i = 0; i < inputsQtt; i++) {
let input = document.createElement("input");
document.body.appendChild(input);
}
}
<form method="get">
<input type="number" name="nombrePlat" id="nombreP">
<input type="button" value="Envoyer" id="ok">
</form>
There are few problems with your code
First: syntax error, you are missing 1 curly bracket } to close function.
And second and more important as you click on button it causes to submit form and refreshes the page.To solve this you just need to change type of button from submit to button.
And also you can not use "input[type=text]" to create element.You can just create an element with following code
function getP () {
var nbP = Number(document.getElementById("nombreP").value);
for (var i = 0; i < nbP; i++) {
var newForm = document.createElement("input");
newForm.id = "form"+i;
newForm.setAttribute("type","text");
document.body.appendChild(newForm);
}
}
Here's a slightly different approach, that involves adding a wrapper container within your form.
function updateForm() {
var parent = document.getElementById('inputs'),
count = document.getElementById('inputCount').value || 0;
parent.innerHTML = '';
for (let i = 0; i < count; i++) {
parent.innerHTML += `<input placeholder="text input ${i+1}" name="form${i+1}" id="form${i+1}" /><br>`;
}
}
<form method="get" name="inputForm">
<input min="0" type="number" name="inputCount" id="inputCount">
<div id="inputs">
<!-- container for dynamic inputs -->
</div>
</form>
<!-- Notice inputs can also be associated to form with `form` attribute -->
<input form="inputForm" type="submit" value="Make" id="ok" onclick="updateForm()">

Sort Number in a Textbox on Ascending order using keypress function - HTML

Hi I'm new in the community.
I am trying to create a simple page where in there are 3 textbox. 1st text box is where the number will be entered. For 2nd and 3rd textbox is where the result will be shows on a different format as soon as the numbers are entered from the 1st textbox. 2nd text box should show the number with a comma which I was able to do. Example: As soon as I enter a number on the first text box 22 55 01 02 the 2nd text box will show 22,55,01,02 however on the 3rd textbox it should show the same number from 2nd textbox but on Ascending order which I weren't able to do so. Tried searching for a solution already but to now avail. Maybe I am just missing something. Any help will be very much appreciated.
function boxx1KeyPress() {
var boxx1 = document.getElementById("boxx1");
var s = boxx1.value.replace(/[ ,]+/g, ",");
var x = s;
var lblValue = document.getElementById("boxx2");
lblValue.value = "" + s;
// code for textbox 3 that didn't work
//function sortAscending(a, b)
//{return a - b;
// }
//var points = boxx3.value;
//points.sort(sortAscending);
//document.getElementById("boxx3").innerHTML = points;
}
function ClearField() {
document.getElementById("boxx1").value = "";
document.getElementById("boxx2").value = "";
document.getElementById("boxx3").value = "";
}
<body>
<B><br><center>PASTE HERE</br>
<input id="boxx1" type="text" onKeyPress="boxx1KeyPress()"
onKeyUp="boxx1KeyPress()">
<br>
<input type="button" Value="Clear Field" onClick="ClearField()">
<br>
<br>11x5 GAMES</BR>
<span id="lblValue"></span>
<input id="boxx2" type="text">
<br>
<br>Keno Games</br>
<input id="boxx3" type="text">
<br>
<p id="Keno"></p>
<input type="button" Value="Ascend" onClick="points.sort(sortAscending)">
</body>
It's actually incredibly simple to sort numbers in JavaScript. All you need to do is:
Split the initial string into an array with .split(" ") (splitting on a space).
Sort the numbers with .sort().
Join the numbers back to a string with .join().
Keep in mind that as the output box is an <input>, you'll need to use .value instead of .innerHTML:
function boxx1KeyPress() {
var boxx1 = document.getElementById("boxx1");
var s = boxx1.value.replace(/[ ,]+/g, ",");
var x = s;
var lblValue = document.getElementById("boxx2");
lblValue.value = "" + s;
// Fixed code for sorting the numbers
var points = boxx1.value.split(" ");
document.getElementById("boxx3").value = points.sort().join();
}
function ClearField() {
document.getElementById("boxx1").value = "";
document.getElementById("boxx2").value = "";
document.getElementById("boxx3").value = "";
}
<body>
<br>
<center>
<b>PASTE HERE</b>
<input id="boxx1" type="text" onKeyPress="boxx1KeyPress()" onKeyUp="boxx1KeyPress()">
<br>
<br>
<input type="button" Value="Clear Field" onClick="ClearField()">
<br>
<br>
11x5 GAMES
<span id="lblValue"></span>
<input id="boxx2" type="text">
<br>
<br>
Keno Games
<input id="boxx3" type="text">
<br>
<p id="Keno"></p>
<input type="button" Value="Ascend">
</center>
</body>
Also note that you had some slightly invalid HTML in your above snippet (primarily that <br> is a void element, so the tag self-closes and thus </br> is not valid). I've cleaned up the HTML in my snippet above.
Hope this helps! :)
Your main issue is that you are trying to sort something that is still a string... you have to make your string into an array first.
function boxx1KeyPress() {
var boxx1 = document.getElementById("boxx1");
var s = boxx1.value.replace(/[ ,]+/g, ",");
var x = s;
var lblValue = document.getElementById("boxx2");
lblValue.value = "" + s;
// get an array from our string s
var arr = s.split(',');
arr.sort(); // note that for strings or ints, the default sort is ascending
document.getElementById("boxx3").innerHTML = arr.join(',');
}
I used the String.split method to get an array, separated at the commas, and the Array.join method to turn it back into a string after it was sorted.
Convert comma separated string into Array. Use array sort function and you done.
function boxx1KeyPress() {
var boxx1 = document.getElementById("boxx1");
var s = boxx1.value.replace(/[ ,]+/g, ",");
var lblValue = document.getElementById("boxx2");
lblValue.value = "" + s;
}
function sortDisending() {
var numberArray = document.getElementById("boxx2").value.split(",");
numberArray.sort(function(a, b){return b-a});
document.getElementById("boxx3").value = numberArray;
}
function sortAsending() {
var numberArray = document.getElementById("boxx2").value.split(",");
numberArray.sort(function(a, b){return a-b});
document.getElementById("boxx3").value = numberArray;
}
function ClearField() {
document.getElementById("boxx1").value = "";
document.getElementById("boxx2").value = "";
document.getElementById("boxx3").value = "";
}
<B><br><center>PASTE HERE
<input id="boxx1" type="text" onKeyPress="boxx1KeyPress()"
onKeyUp="boxx1KeyPress()">
<br>
<br>
<br>11x5 GAMES
<span id="lblValue"></span>
<input id="boxx2" type="text">
<br>
<br>Keno Games
<input id="boxx3" type="text">
<br>
<p id="Keno"></p>
<input type="button" Value="Ascend" onClick="sortAsending()">
<input type="button" Value="Descend" onClick="sortDisending()">
<input type="button" Value="Clear Field" onClick="ClearField()">

Javascript value of input

This is supposed to calculate circumference, however, I am only getting a zero returned. What am I doing wrong?
<html>
<head>
<script type="text/javascript">
var index = false;
var text = "This text shifts";
var Pi = 3.14159265;
var dia = document.getElementById("txtdia");
var circumf = dia * Pi;
function DisplayText(){
document.getElementById("txtcircumf").value = circumf;
}
</script>
</head>
<body>
<form>
<input type="text" id="txt1"/>
<input type="text" id="txt2"/><br>
<input type="text" name="txtdia" />
<input type="text" name="txtcircumf" />
<input type="button" value="Change Text" onclick="DisplayText()"/>
</form>
</body>
</html>
The primary problem you have is that this script will run prior to your dom being ready. As a result, even if you were properly grabbing the diameter's value it still wouldn't work, since document.getElementById("txtdia") wouldn't return anything.
I would just fetch the diameter's value each time.
function DisplayText(){
var dia = document.getElementById("txtdia").value;
var circumf = dia * Pi;
document.getElementById("txtcircumf").value = circumf;
}
The other option of course is to put this entire script after your html. Ie
</body>
<script type="text/javascript">
var index = false;
var text = "This text shifts";
There are 3 distinct issues which you need to fix for this to work correctly.
txtcircumf and textdia are the name of the elements, not the id, so using document.getElementById will fail.
Fix: Add that as an id onto the elements in question:
<input type="text" name="txtdia" id="txtdia" />
<input type="text" name="txtcircumf" id="txtcircumf" />
The elements are not present when the script first runs. This is the issue described by #AdamRakis and his fix is probably best - always retrieve the value when you need it:
function DisplayText(){
var dia = document.getElementById("txtdia").value;
var circumf = dia * Pi;
document.getElementById("txtcircumf").value = circumf;
}
A minor point, but when you read the .value of a field you get text, as you are doing a mathematical equation it is common practice to ensure the value you're wouking with is numeric. You can use parseFloat for this:
function DisplayText(){
var dia = parseFloat(document.getElementById("txtdia").value);
var circumf = dia * Pi;
document.getElementById("txtcircumf").value = circumf;
}
I made a couple structural changes that improve the overall quality of your code :) (see the arrows for changes)
<html>
<body>
<form>
<input type="text" id="txt1"/>
<input type="text" id="txt2"/><br>
<input type="text" name="txtdia" />
<input type="text" name="txtcircumf" />
<input type="button" id="derp" value="Change Text" /> //<-- added ID, removed inline JS
</form>
<script type="text/javascript">
document.getElementById("derp").onclick = function() { //<-- use this style instead of inline onclicks!
var index = false;
var text = "This text shifts";
var dia = document.getElementById("txtdia").value; //<-- .value, not the whole element!
var circumf = dia * Math.PI; //<-- Math.PI is an object constant, very handy
document.getElementById("txtcircumf").value = circumf;
//no more standard function!
}
</script>
</body>
</html>

5 radio buttons fill up randomly?

Hi I am trying to make five buttons as you can see and I want a function when you push "click me" it will fill up the five button randomly.
It's like a random generator for stats for a game.
I don't know if I'm doing it all wrong but I think I need some other coding for this.
Can anyone that can help me?
This is what I have:
<button onclick='myFunction()'>click me</button>
<div id="demo">
<Input type = radio Name = r1>
<Input type = radio Name = r2>
<Input type = radio Name = r3>
<Input type = radio Name = r4>
<Input type = radio Name = r5>
</div>
<script type="text/javascript">
function myFunction() {
document.getElementById('demo').innerHTML = '';
var num = 3;
var noOfButtons = Math.floor(Math.random() * num);
console.log(noOfButtons);
for (var i = 0; i < noOfButtons; i++) {
var box = document.createElement();
document.getElementById('demo');
}
}
</script>
not exactly sure what your looking for. I threw this JSFiddle together. Take a look and see if its what you're looking for.
<button id='button1'>click me</button>
<div id="demo">
<input type='radio' id='r1'>
<input type='radio' id='r2'>
<input type='radio' id='r3'>
<input type='radio' id='r4'>
<input type='radio' id='r5'>
</div>
.
var button1 = document.getElementById('button1');
button1.onclick = function () {
var noOfButtons = 5;
var pick = Math.floor(Math.random() * noOfButtons) + 1;
var radioBtn = document.getElementById('r' + pick);
radioBtn.checked = true;
}
[edit]
I think what you're trying to do is randomly check a finite number of radios, in which case there's no need to set demo's html to ''. I added the class myRadios to the tags of your radios (just in case there are other radios on the page that you don't want to include in the random checking), and then used the following function:
function myFunction() {
var radios = document.getElementsByClassName('myRadios');
for (var i=0; i<radios.length; i++)
{
radios[i].checked = ( (Math.random()*10) > 5) ? true : false;
}
}
Here is a a working fiddle. Let me know if this is the functionality you were looking for or if you have any questions about how it works :)

execute a javascript on load

I want to execute this java script on load, but it doesn't seem to display the result after
the browser loads.
<script>
function displayNumber()
{
var card = document.getElementById('credit').value;
var str = "";
for(var i=1; i <= card.length-4; i++) {
str += "*";
}
ecard = str + card.substr(card.length-4);
document.getElementById('output').innerHTML = ecard;
}
</script>
<form id="myform">
<input type="text" id="credit" onLoad="displayNumber()" value="123456789012">
</form>
<label id="output"> </label>
The output should be
********9012
You cannot use onload with an input. Instead, put window.onload = displayNumber; in your JavaScript. The other option is to add a body tag and use onload="displayNumber()"

Categories