i have minimum of two select box in html form to insert through POST but user can add more select boxes.Now i have to show relations between each n every inserted id.
like we have inserted 1,2,3,4 id..so i want it inserted in a table in two column as
(1-2) (1-3) (1-4) (2-3) (2-4) (3-4)
plzz reply to this and tell some idea about this
any help??
Simply iterate your array and make couples of next elements in same array:
function calculate() {
var nums = document.getElementById('nums');
nums = nums
.value
.split(',')
.sort(function(a, b) {
return parseInt(a) - parseInt(b);
});
for (var i = 0; i < nums.length; i++) {
for (var j = i + 1; j < nums.length; j++) {
console.log('(' + nums[i] + ' - ' + nums[j] + ')');
}
}
}
<input type="text" placeholder="1,2,5,8" id="nums" />
<button onClick="calculate()">Calculate</button>
Related
I'm trying to solve a problem I have that requires arrays and loops.
The task is just to take a random string and write out all the letters so that it looks like this:
R, Ra, Ran, Rand ,Rando , Random, RandomS, RandomSt, RandomStr, RandomStri, RandomStrin, RandomString.
I solved that part like this:
function sometext() {
var temptext = document.getElementById("textinput").value;
var temparray = [];
temparray = temptext.slice();
for (var i = 0; i <= temparray.length; i++) {
document.getElementById("printit").innerHTML += temparray.slice(0, i) + "<br/>";
}
}
<input id="textinput" onchange="sometext()">
<div id="printit"></div>
The code runs that string that it gets from an inputbox that anyone writes in.
The next step is to have this string remove the first letter and then write it out like above so it would look like this: a, an, and, ando, andom, andomS, andomSt, andomStr, andomStri, andomStrin, andomString and then remove the first letter again so the output would be: n, nd, ndo, ndom, ndomS, ndomSt, ndomStr, ndomStri, ndomStrin, ndomString and so on until it runs out of letters to remove from. I don't know how to make it work for any amount of letters.
Example output
R
Ra
Ran
Rand
Rando
Random
a
an
and
ando
andom
n
nd
ndo
ndom
d
do
dom
o
om
m
How about a map and shift
const output = document.getElementById("printit");
function sometext(fld) {
let temptext = [...fld.value]; // or fld.value.split("")
const arr = []
while (temptext.length > 0) {
arr.push(
temptext.map((_, i) => temptext.slice(0, i + 1).join("")).join("<br>")
)
temptext.shift(); // drop first letter
}
output.innerHTML = arr.join("<br/>")
}
<input id="textinput" oninput="sometext(this)">
<div id="printit"></div>
When you get array with all needed values, just iterate through and print it as you want or to html or to console
const text = 'Random';
const result = [...text].flatMap((ch, index) => {
const righPart = text.slice(index, text.length);
const leftParts = [...righPart].map((ch, index) => righPart.slice(0, index + 1))
return leftParts;
});
console.log(result)
.as-console-wrapper{min-height: 100%!important; top: 0}
Update
It just combination of two similar functions
First return array with only right parts of string:
const text = 'Random'
[...text].map((ch, index) => text.slice(index, text.length))
// ['Random', 'andom', 'ndom', 'dom', 'om', 'm']
Second is similar and returns only left parts:
const text = 'Random'
[...text].map((ch, index) => text.slice(0, index + 1))
// ['R', 'Ra', 'Ran', 'Rand', 'Rando', 'Random']
In solution I use .flatMap() to make result array flatten. That's all.
<script>
function sometext() {
var temptext = document.getElementById("textinput").value;
var temparray = [];
temparray = temptext.slice();
for (var i = 0; i <= temparray.length; i++)
{
document.getElementById("printout").innerHTML += temparray.slice(0, i) + "<br/>";
if (i == temparray.length)
{
for (var i = 1; i <= temparray.length; i++)
{
document.getElementById("printout").innerHTML += temparray.slice(1, i) + "<br/>";
if (i == temparray.length)
{
for (var i = 2; i <= temparray.length; i++)
{
document.getElementById("printout").innerHTML += temparray.slice(2, i) + "<br/>";
if (i == temparray.length)
{
for (var i = 3; i <= temparray.length; i++)
document.getElementById("printout").innerHTML += temparray.slice(3, i) + "<br/>";
if (i == temparray.length)
{
for (var i = 4; i <= temparray.length; i++)
{
document.getElementById("printout").innerHTML += temparray.slice(4, i) + "<br/>";
if (i == temparray.length)
{
for (var i = 5; i <= temparray.length; i++)
{
document.getElementById("printout").innerHTML += temparray.slice(5, i) + "<br/>";
if (i == temparray.length)
{
for (var i = 6; i <= temparray.length; i++)
{
document.getElementById("printout").innerHTML += temparray.slice(6, i) + "<br/>";
}
}
}
}
}
}
}
}
}
}
}
}
}
</script>
<p><input type="text" id="textinput" value=""></p>
<p><input type="button" value="Check it out" onclick="sometext()">
</p>
<div id="printout"></div>
I'm showing how I first answered it, it runs a loop and prints out the first iteration, then when i == temparray.length it starts on a new loop with i starting on the next number and prints out the next iteration and when it reaches the length of the array it starts again with the next number and this process continues for 6 iterations. Now this doesn't look very nice since it's not a generalized solution, and that's what I'm trying to figure out but with no success. As the code is now, it does it for 6 character words, in order to make it for 7 characters I just need to add another if (i == temparray.length) and for (var i = [previousNumber +1]; i< temparray.length; i++) and then write it out on the div element. It works but it isn't very pretty in my opinion.
I have loop inside loop like this:
var len = bolumlerUnique.length;
function bolumleriGonder() {
for (i = 0; i < bolumlerUnique.length; i++) {
elementBolumler = $("[bolumid=" + bolumlerUnique[i] + "]:checked");
console.log(elementBolumler);
for (j = 0; j < len; j++) {
console.log(elementBolumler[j])
}
}
}
bolumlerUnique is an array --> ["1", "2", "3", "4"]I have radio inputs and find elements with this code
$("[bolumid=" + bolumlerUnique[i] + "]:checked");
But in the second loop console.log writes undefined.
But elementBolumler is defined global variable.
Check your len variable is have a value it must work with your codes.
in the second loop console.log writes undefined.
To answer the question as (almost) presented: "why do I get undefined with $()[j]?"
Within jquery, if you attempt to get an element by index that's larger than the number of items in the jquery collection, you get undefined (not array out of bounds as it's not an array), ie:
var divs = $(".d");
console.log(divs[0])
console.log(divs[1]) // undefined
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="d">d1</div>
The issue is with:
var len = bolumlerUnique.length;
for (j = 0; j < len; j++) {
When you iterate over
$("[bolumid=" + bolumlerUnique[i] + "]:checked")
it will only have as many items as are checked that match the one id. So it's highly likely that
elementBolumler.length !== len
As noted in the comments to the question, [bolumid=" + bolumlerUnique[i] + "] is a radio so it will only ever return one item.
Your logic for the inner loop index len is incorrect, but it's not clear what it should be - possibly:
elementBolumler.length
as in:
function bolumleriGonder() {
for (i = 0; i < bolumlerUnique.length; i++) {
elementBolumler = $("[bolumid=" + bolumlerUnique[i] + "]:checked");
console.log(elementBolumler);
for (j = 0; j < elementBolumler.length; j++) {
console.log(elementBolumler[j])
}
}
}
const checkboxesIWantToMessWith = [2, 4, 6]
checkboxesIWantToMessWith.forEach(id => {
const checkbox = document.querySelector(`input[bolumid="${id}"]`)
if (checkbox.checked) {
// Do my stuff
console.log(`checkbox bolumid="${id}" is checked`)
} else {
// Do other stuff
console.log(`checkbox bolumid="${id}" is NOT checked`)
}
})
<input type="checkbox" bolumid="1" checked />
<input type="checkbox" bolumid="2" checked />
<input type="checkbox" bolumid="3" checked />
<input type="checkbox" bolumid="4" />
<input type="checkbox" bolumid="5" checked />
<input type="checkbox" bolumid="6" checked />
I am currently trying to create a double nested loop that adds a number to itself, given the number of instances you want it to be added by.
So when you input something in the Number, for example "5" and you input "3" for the number of instances, then the following would be printed:
5=5
5+5=10
5+5+5=15
More information on my JsFiddle
<div>
<h2>Loop</h2>
Number
<input type='text' id='tbox'>
<br>
Number of Instances
<input type='text' id='theNumber'>
<button onclick=doubleLoop;>
Add Numbers.
</button>
</div>
<div id="content">
</div>
<script>
function doubleLoop(){
var theText = document.getElementById('tbox').value;
var theNumber = document.getElementById('theNumber').value;
var content = document.getElementById('content');
content.innerHTML = '';
for (var i = 0; i < theNumber; i++) {
content.innerHTML = content.innerHTML + (i + 1) + ')';
//start of the second part of the Double Loop
for (var j = 0; j < (i + 1); j++){
if (i === 0){
content.innerHTML = content.innerHTML + theText + '=' + theText + '<br>';
} else if (i > 0) {
content.innerHTML = content.innerHTML + theText.repeat(j) + '=' + (theText * (i+1));
}
}
}
}
</script>
Here you go
https://jsfiddle.net/mkarajohn/qkn2ef4L/
function createString(number, times) {
/*
* We will create each side of the equation separately and we will concatenate them at the end
*/
var leftSide = '',
rightSide = '',
i;
for (i = 1; i <= times; i++) {
leftSide += number.toString();
if ((times > 1) && (i < times)) {
leftSide += '+';
}
}
rightSide = number * times
return (leftSide + '=' + rightSide);
}
function loop(){
// .value returns a string, so we make sure the values are converted to integers by calling parseInt()
// See https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/parseInt
var theText = parseInt(document.getElementById('tbox').value);
var theNumber = parseInt(document.getElementById('theNumber').value);
var content = document.getElementById('content');
var output = '';
content.innerHTML = '';
for (var i = 1; i <= theNumber; i++) {
output += createString(theText, i);
output += '<br />'
}
content.innerHTML = output;
}
var button = document.getElementById('run');
run.addEventListener('click', loop);
If there is something that is not clear feel free to ask.
EDIT: If you are hell bent on doing it with two nested loops, here's how it would go:
function loop(){
// .value returns a string, so we make sure the values are converted to integers by calling parseInt()
// See https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/parseInt
var theText = parseInt(document.getElementById('tbox').value);
var theNumber = parseInt(document.getElementById('theNumber').value);
var content = document.getElementById('content');
var output = '';
var leftSide = '',
rightSide = '';
content.innerHTML = '';
for (var i = 1; i <= theNumber; i++) {
leftSide = '';
for (var j = 1; j <= i; j++) {
leftSide += theText.toString();
if ((i > 1) && (j < i)) {
leftSide += '+';
}
}
rightSide = theText * i;
output += (leftSide + '=' + rightSide);
output += '<br />'
}
content.innerHTML = output;
}
var button = document.getElementById('run');
run.addEventListener('click', loop);
First things first: You're naming your variables very poorly, it's really difficult to understand what you're trying to do, specially when you don't say what you want directly in the question. doubleLoop says how your function works but not what it does. getMultiplicationProcess would have been a better name. Also, you could be passing the values as arguments and just returning the result, it would look A LOT better.
Anyway, I couldn't figure how you were trying to achieve this. I've renamed your variables and did everything my way. Never name a variable theNumber or theText because doing so says nothing about what information it holds. You could have named them firstInput and secondInput but even that way it would not be clear.
Here's the code, scroll down for explanation:
var submit = document.getElementById("submit"),
firstInput = document.getElementById("tbox"),
secondInput = document.getElementById("theNumber"),
answerField = document.getElementById("content");
submit.addEventListener("click", function () {
answerField.innerHTML = getMultiplicationProcess(Number(firstInput.value), Number(secondInput.value), "<br/>");
});
function getMultiplicationProcess(multiplicand, multiplier, lineBreak) {
var result = "";
for (var i = 0; i < multiplier; ++i) {
for (var j = 0; j < i + 1; ++j) {
if (i === j) {
result += multiplicand + " = " + (multiplicand * (i + 1));
} else result += multiplicand + " + ";
}
result += lineBreak || "\n";
}
return result;
}
JSFiddle
Explanation:
The outer for loop runs as many times as the second input, or multiplier. So if you input 5 and 3 respectively this loop will run three times. It represents each line of the resulting string.
The inner loop runs as many times as the current iteration number of the outer loop more one. So for our example inputs it will run like this:
0: 1; 1: 2; 2: 3;
I use it to place the multiplicand multiple times in the current line.
The first line will contain a single 5 (not including the answer for this multiplication) so j is i + 1 which is 1 because during the first iteration from the outer loop i equals 0:
5 = 5
The second line contains 2 5s and i is 1 because we're in the second iteration for the outer loop, so j = i + 1 = 2 which is how many fives we'll place in the string:
5 + 5 = 10
if it's the last iteration of the inner loop instead of adding "5 + " to the resulting string it places "5 = (i + 1) * multiplier" which will be the result for the current line. Then the inner loop ends, the outer loop adds a line break and restarts the process for the next line.
I got an array like so: ["abc", "cde", "efg"].
I want to loop through a set of elements and apply the strings from this array to each n:th (the length of the array) element.
<p>abc</p>
<p>cde</p>
<p>efg</p>
All I've managed is how to loop and apply the same string (the last one) to each element like:
<p>efg</p>
<p>efg</p>
<p>efg</p>
EDIT:
Currently I'm working with something like this:
for (var j = 0; j < noOfTableCells.length; j++) {
var heading = "";
for (var k = 0; k < myArray.length; k++) {
heading = headingArray[k];
}
}
But I can't figure out how to get it to every n:th (3rd in this case) element.
See the jsfiddle:
var elements = ["abc", "cde", "efg"].map(function(str) {
return '<p>' + str + '</p>';
});
elements.forEach(function(element) {
$('body').append(element);
});
Or you could shorten it:
["abc", "cde", "efg"].map(function(str) {
return '<p>' + str + '</p>';
}).forEach(function(element) {
$('body').append(element);
});
This uses jQuery. If you want to be a super random badass, you can do this (jsfiddle):
var elements = ["abc", "cde", "efg"].map(function(str) {
return '<p>' + str + '</p>';
}),
parser = new DOMParser();
elements.forEach(function(element) {
document.body.appendChild(parser.parseFromString(element, "text/xml").firstChild);
});
There are a 1000 other random, or 1000 other more efficient, solutions to this. Pick your poison.
When looping through the other elements, if there is a numbering system associated with that, you can use the numbering system. Otherwise, you can loop through those elements with a C-style for loop, as follows:
var myArray = ["abc", "cde", "efg"];
var i;
for (i = 0; i < myArray.length; i++) {
var j = i % 3;
j = (i - j) + 2;
//do something with the element that you wanted
//do something with myArray[j];
}
Eventually solved it with the following:
var laps = totalItems / myArray.length;
for (var row = 0; row < laps; row++) {
for (var cell = 0; cell < myArray.length; cell++) {
//Do the stuff
}
}
I have this problem I have been working on for a few days. I need to make a page that requests the user for 12 letters, and click the submit button. I cannot make what I have come up with work. Suggestions are welcomed! The Javascript that is run should do the following: Generate a random number 1-3, for the number of rows, and put the 12 characters into a formatted table. For example, a random generated table might produce the following:
Text entered: abcdefghijkl
a b c
d e f
g h i
j k l
Or:
a b c d
e f g h
i j k l
etc.
My HTML:
<form name="table">
<p>Enter 12 letters</p>
<input type="text" id= "userVal" size="12">
<input type="button" value="submit" onclick="createTable()">
Javascript:
var numrows= randomnumber=Math.floor(Math.random()*4)
var numcols=4
document.write ("<table border='1'>")
for (var i=1; i<=numrows; i++)
{
document.write ("<tr>");
for (var j=1; j<=numcols; j++)
{
document.write ("<td>" + i*j + "</td>");
}
document.write ("</tr>");
}
document.write ("</table>");
function createTable(){
See if this is the behavior you are looking for:
http://jsfiddle.net/sDbkw/
I modified the loops to be zero based and referenced the textbox:
var createTable = function () {
var numrows = Math.floor(Math.random()*3) + 1; // x3 gets 0, 1, or 2 so increment 1
var numcols = 12 / numrows; // if always printing 12 chars
var userText = $('#userVal').val();
var output = "<table border='1'>";
for (var i=0; i < numrows; i++)
{
output += "<tr>";
for (var j=0; j<numcols; j++)
{
output += '<td>' + userText[i*numcols + j] + '</td>';
}
output += "</tr>";
}
output += "</table>";
$('#output').html(output);
};