I am having little problem on JavaScript. What I am doing is copying data from a grid and pasting into another. I was able to access the value from the cell, but problem comes as I try to format those value to string.
my code:
var colseperator = '~';
var rowseperator = ' ';
var clipStr = "";
if(selecttype = "area")
{
for (var i = startrow; i <= endrow; i++)
{
for (var j = startcol; j <= endcol; j++)
{
var cellValue = objGrid.getCellValue(i,j);
if(this.gfn_isNull(cellValue))
{
cellValue = "Null";
}
clipStr = clipStr + cellValue;
if(j != endcol)
{
clipStr = clipStr + colseperator;
}
}
if(i != endrow)
{
clipStr = clipStr + rowseperator;
}
}
}
From code above, my intention is copy the data into string format and separate each data with separator(in my case '~' for columns and 'indent' for rows). However, when I select one column(multi rows) and copy it, it would add column separators to all the rows.
I was thinking that if(j != endcol){clipStr = clipStr + colseperator;} would stop it from adding unnecessary separator. Am I doing something wrong here? And any tips on iterating the selected grid cells or formatting string?
example:
When I select those three lines,
row
data
1
a
2
b
3
c
Output:
a~ b~ c~
My expected output:
a b c
You could add a variable for a cols and add the separator if not iteratng the first item.
var colseperator = '~',
rowseperator = ' ',
clipStr = "";
if (selecttype = "area") {
for (var i = startrow; i <= endrow; i++) {
var cols = "";
for (var j = startcol; j <= endcol; j++) {
var cellValue = objGrid.getCellValue(i, j);
if (this.gfn_isNull(cellValue)) cellValue = "Null";
if (j !== startcol) cols += colseperator;
cols += cellValue;
}
if (j !== startcol) clipStr += rowseperator;
clipStr += cols;
}
}
Related
I would like to know how to append to the DOM just once after these nested loops.
Also, the variable letters is dynamic, so I would need to 'reset' my appended grid when a new string is passed to letters
let letters = "abcdefghijkl"
for (let i = 0; i < letters.length; i++) {
var musicRowID = `${letters.charAt(i)}01`;
$("#music-grid").append(`<div id="music-row-${musicRowID}" class="row no-gutters"></div>`);
for (let j = 1; j <= 12; j++) {
var columnID = letters.charAt(i) + (j < 10 ? "0" : "") + j;
$(`#music-row-${musicRowID}`).append(
`<div class="col-1"><button id="${columnID}" class="btn bar song">${columnID.toUpperCase()}</button></div>`
);
}
}
Thank you in advance!
EDIT
After the answer from T.J. Crowder I tried to incorporate my code to be able to populate my grid from the inputs, but when I unselect one of the inputs, that row isn't cleared.
let letters = 'abcdefghijkl';
let html = "";
$(".list-checkbox-item").change(function() {
let chosenLetters = $(this).val();
if ($(this).is(":checked")) {
arrayOfChoices.push(chosenLetters);
} else {
arrayOfChoices.splice($.inArray(chosenLetters, arrayOfChoices), 1);
}
letters = arrayOfChoices.sort().join(""); // Gives me a string with chosen letters ordered alphabetically
console.log(
`This is my string in var 'letters' ordered alphabetically (Need to clear grid after each instantiation or append after the loop): %c${letters}`,
"color: red; font-weight: bold; font-size: 16px"
);
for (let i = 0; i < letters.length; i++) {
var musicRowID = `${letters.charAt(i)}01`;
html += `<div id="music-row-${musicRowID}" class="row no-gutters">`; // *** No `</div>` yet
for (let j = 1; j <= 12; j++) {
var columnID = letters.charAt(i) + (j < 10 ? "0" : "") + j;
html += `<div class="col-1"><button id="${columnID}" class="btn bar song">${columnID.toUpperCase()}</button></div>`;
}
html += "</div>";
}
$("#music-grid").html(html);
});
What am I doing wrong?
Assuming #music-grid is empty before you run this code the first time, build up the HTML in a string and then use html() to replace the contents of #music-grid rather than appending to it:
let html = "";
for (let i = 0; i < letters.length; i++) {
var musicRowID = `${letters.charAt(i)}01`;
html += `<div id="music-row-${musicRowID}" class="row no-gutters">`; // *** No `</div>` yet
for (let j = 1; j <= 12; j++) {
var columnID = letters.charAt(i) + (j < 10 ? "0" : "") + j;
html +=
`<div class="col-1"><button id="${columnID}" class="btn bar song">${columnID.toUpperCase()}</button></div>`;
}
html += "</div>";
}
$("#music-grid").html(html);
You also see people building up the HTML in an array and using array.join("") at the end to get a single string, but with modern JavaScript engines it's really a wash either way...
I am trying to create an X or plus(+) pattern using javascript for-loop but fail to do it.
here is my code
function drawCross(){
var inputVal = document.getElementById("input").value;
if (inputVal % 2 === 0) { // checks if the user's entered value is even
document.getElementById("output").innerHTML = "";
for (var row = 0; row < inputVal; row++) {
for (var col = 0; col < inputVal; col++) {
if (row == col + 3 || row == parseInt(inputVal / 1))
document.getElementById("output").innerHTML += "O";
else
document.getElementById("output").innerHTML += "..";
}
document.getElementById("output").innerHTML += "<br/>";
}
}
}
this is the final result I am trying to achieve
A few issues:
Make sure your output element uses a monospace font. For instance, you could use a pre element for this. Then you don't have to double the points to get something that is still imperfect.
The input number should be odd, not even. Otherwise you don't have a center column/row.
The formula for the second diagonal is not like you have it (division by 1 does not make much sense). Use row == +inputVal - col - 1
Apart from that, also try to interact less with the DOM: only update it when you have the final HTML string.
Here is the code:
function drawCross(){
var inputVal = +document.getElementById("input").value;
var html = "";
if (inputVal % 2 === 1) { // checks if the user's entered value is odd
for (var row = 0; row < inputVal; row++) {
for (var col = 0; col < inputVal; col++) {
if (row == col || row == inputVal - col - 1)
html += "O";
else
html += ".";
}
html += "<br/>";
}
document.getElementById("output").innerHTML = html;
}
}
Enter odd number: <input id="input">
<button onclick="drawCross()">Go</button>
<pre id="output"></pre>
I'm trying to avoid horizontal and vertical lines.
It stopped working with the Javascript array and for the rest of it.
I don't know how to create Javascript to randomly generate the first line and don't overlap with daeumjul. Please let me know. The code has been raised to jsfiddle.
Screenshot:
Javascript
var arr_person = ["#B22222","#0000cd","#FF00FF","#DAA520","#008000","#FF69B4","#4B0082","#E6E6FA","#ADD8E6","#90EE90"];
var arr_date = ['mon', 'tue', 'wed', 'thu','fri'];
var arr_subject = ['subject1','subject2','subject3','subject4','subject5'];
var arr_subject_check = new Array();
for(m=0; m < arr_subject.length; m++){
arr_subject_check[m] = new Array();
}
var arr_time = ['morning','after'];
var str = "";
function pickFromPool() {
var r = Math.floor(Math.random() * arr_pool.length);
return arr_pool.splice(r,1)[0];
}
str += "<table>";
for(var i=0; i < arr_date.length; i++){ // arr_date
var arr_pool = arr_person.slice();
str += "<tr>";
for(var j=0; j < arr_subject.length; j++ ){ //arr_subject
var arr_subject_check_cur = arr_subject_check[j].slice();
for(var n=0; n < arr_subject_check_cur.length; n++) {
var dup_index = arr_pool.indexOf(arr_subject_check_cur[n]);
if(dup_index < 0) {
} else {
arr_pool.splice(dup_index,1);
}
}
for(var k=0; k < arr_time.length; k++ ){
var pickedValue = pickFromPool();
arr_subject_check[j].push(pickedValue);
if(k == 0){
str += "<td style='border-left:#fff 4px solid;background-color:" + pickedValue + "'></td>";
} else {
str += "<td style='background-color:" + pickedValue + "'></td>";
}
}
for(var m=0; m < arr_subject_check_cur.length; m++) {
if(arr_subject_check_cur[m] !== '') {
arr_pool.push(arr_subject_check_cur[m]);
}
}
}
str += "</tr>";
}
str += "</table>";
jQuery('body').html(str);
https://jsfiddle.net/ipadorusa/vx8t25ts/1/
I'm trying to avoid horizontal and vertical lines.
I'm just learning now. Can you please help me, why am I not getting the correct output. This is my code:
//ask questions
var quiz = [
["When is Bulgaria established?", 681],
["What year was it before 16 years?", 2000],
["When does WWII ends?", 1945]
];
//variables
var answer = [];
var correct = [];
var wrong = [];
var correctAns = 0;
var wrongAns = 0;
var oList = "<ol>";
//function to print the result in ordered list
function printResult(result){
for(var j = 0; j < result.length; j++){
oList += "<li>" + result[i] + "</li>";
}
oList += "</ol>";
return oList;
}
function print(message) {
document.getElementById('output').innerHTML = message;
}
//looping, adding correct and wrong answeres
for(var i = 0; i < 3; i++) {
answer[i] = prompt(quiz[i][0]);
if(parseInt(answer[i]) == quiz[i][1]){
correct.push(quiz[i][0]);
correctAns++;
} else {
wrong.push(quiz[i][0]);
wrongAns++;
}
}
//print logic
if(correct.length < 1 || correct == undefined){
print("You did not guess any of the quiestions!");
} else if (correct.length >= 1){
print("You have guessed " + correctAns + " questions.");
print(printResult(correct));
print("You have " + wrongAns + " wrong answeres.");
if(wrongAns > 0){
print(printResult(wrong));
}
}
I have watched this code over and over again and I still can't understand why am I getting undefined as a result. In the debugger, after the loop I check my vars and everything seems ok.
In your printResult function you are using var i instead of j,
Also you better use innerHtml+=message;
//ask questions
var quiz = [
["When is Bulgaria established?", 681],
["What year was it before 16 years?", 2000],
["When does WWII ends?", 1945]
];
//variables
var answer = [];
var correct = [];
var wrong = [];
var correctAns = 0;
var wrongAns = 0;
//function to print the result in ordered list
function printResult(result){
//HERE:
var oList = "<ol>";
for(var j = 0; j < result.length; j++){
oList += "<li>" + result[j] + "</li>";
}
oList += "</ol>";
return oList;
}
function print(message) {
document.getElementById('output').innerHTML += message;
}
//looping, adding correct and wrong answeres
for(var i = 0; i < 3; i++) {
answer[i] = prompt(quiz[i][0]);
if(parseInt(answer[i]) == quiz[i][1]){
correct.push(quiz[i][0]);
correctAns++;
} else {
wrong.push(quiz[i][0]);
wrongAns++;
}
}
//print logic
if(correct.length < 1 || correct == undefined){
print("You did not guess any of the quiestions!");
} else if (correct.length >= 1){
print("You have guessed " + correctAns + " questions.");
print(printResult(correct));
print("You have " + wrongAns + " wrong answeres.");
if(wrongAns > 0){
print(printResult(wrong));
}
}
<div id="output">
</div>
Basically you have three problems.
reuse of oList, the variable should be inside declared and used only in printResult.
Inside of printResult, use of i where j have been used and
At print, you replace the actual content with new content.
Just a small hint with variable names for counting. It is good practise to start always with i instead of j and go on with the letters in the alphabet.
var quiz = [["When is Bulgaria established?", 681], ["What year was it before 16 years?", 2000], ["When does WWII ends?", 1945]],
answer = [],
correct = [],
wrong = [],
correctAns = 0,
wrongAns = 0;
//function to print the result in ordered list
function printResult(result) {
var oList = "<ol>"; // !!! move variable inside of the function
for (var j = 0; j < result.length; j++) {
oList += "<li>" + result[j] + "</li>"; // !!! use j indstead if i
}
oList += "</ol>";
return oList;
}
function print(message) {
document.getElementById('output').innerHTML += message; // !!! append message
}
//looping, adding correct and wrong answeres
for (var i = 0; i < 3; i++) {
answer[i] = prompt(quiz[i][0]);
if (parseInt(answer[i]) == quiz[i][1]) {
correct.push(quiz[i][0]);
correctAns++;
} else {
wrong.push(quiz[i][0]);
wrongAns++;
}
}
//print logic
if (correct.length < 1 || correct == undefined) {
print("You did not guess any of the quiestions!");
} else if (correct.length >= 1) {
print("You have guessed " + correctAns + " questions.");
print(printResult(correct));
print("You have " + wrongAns + " wrong answeres.");
if (wrongAns > 0) {
print(printResult(wrong));
}
}
Your main mistake is using i intead of j:
for(var j = 0; j < result.length; j++){
oList += "<li>" + result[j] + "</li>";// here was i before
}
function successCallback(caRecords) {
var x = document.getElementById("custAccount"); // select
var option1 = document.createElement("option"); //options
//var accno = 0;
// caRecords i am fetch from MS CRM
var count = caRecords[0].results.length;
if (caRecords != null && count > 0) {
alert("records are not null");
for (var i = 0 ; i < count; i++)
{
var text = caRecords[0].results[i].new_name;
// alert(text + "J=" + j);
option1.text = text;
option1.value = j;
x.add(option1);
j++;
}
}
I got six records and try to insert that values into select as option. It showing last value of my 6 values.
Can anyone help me to improve my code?
You can iterate your values like this...
function successCallback(caRecords) {
var x = document.getElementById("custAccount"); // select
var options = "";
var count = caRecords[0].results.length;
if (caRecords != null && count > 0) {
alert("records are not null");
for (var i = 0; i < count; i++) {
options += "<option value=" + j + ">" + caRecords[0].results[i].new_name + "</option>";
j++;
}
x.innerHTML = options;
}