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;
}
Related
I am using this JS code to do some magic. Working perfect to get a variabele and remove unwanted text and display the correct text in a text field.
values 2 or 3 or 5 or 7 etc. in <input type="text" id="calc_dikte[0][]" name="calc_dikte[]" value="">
function copy_dikte()
{
var i;
var elems = document.getElementsByName('dxf_var_dikte_copy[]');
var elems_1 = document.getElementsByName('dxf_vars[]');
var elems_2 = document.getElementsByName('calc_dikte[]');
var elems_3 = document.getElementsByName('calc_ext[]');
var l = elems.length;
var z;
z=0;
for(i=0; i<l; i++)
{
if(elems_3[i].value == 'dxf')
{
elems[i].value = document.getElementById('dxf_var_dikte').value;
var elems_1_split_1 = (elems_1[i].value).split(elems[i].value+'=');
var elems_1_split_2 = (elems_1_split_1[1]).split(',');
if(isNaN(elems_1_split_2[0])) { elems_2[i].value = ''; }
else { elems_2[i].value = parseFloat(elems_1_split_2[0]); }
}
}
}
So this works, but now the form field has changed from text to select like:
<select id="calc_dikte[0][]" name="calc_dikte[]">
<option value="">
<option value="2|2000">2</option>
<option value="3|2000">3</option>
<option value="5|2000">5</option>
<option value="7|2000">7</option>
</select>
Therefore I have changed my JS code (with some tips from here) to:
function copy_dikte()
{
var i;
var elems = document.getElementsByName('dxf_var_dikte_copy[]');
var elems_1 = document.getElementsByName('dxf_vars[]');
var elems_2 = document.getElementsByName('calc_dikte[]');
var elems_3 = document.getElementsByName('calc_ext[]');
var l = elems.length;
var z;
z=0;
for(i=0; i<l; i++)
{
if(elems_3[i].value == 'dxf')
{
elems[i].value = document.getElementById('dxf_var_dikte').value;
var elems_1_split_1 = (elems_1[i].value).split(elems[i].value+'=');
var elems_1_split_2 = (elems_1_split_1[1]).split(',');
var sel = elems_2[i];
var val = parseFloat(elems_1_split_2[0]);
for(var m=0, n=sel.options.length; m<n; m++)
{
if(sel.options[i].innerHTML === val)
{
sel.selectedIndex = m;
break;
}
}
}
}
}
But this is not working, no item is selected in the select list, no errors are shown.
Please help me out change to a working code to have the correct line selected. It should not select on the value but in the text between the ><
option value="5|2000">5</option
If I check with
for(var m=0, n=sel.options.length; m<n; m++) {
alert('sel = '+sel.options[i].innerHTML+'\nval = '+val);
}
I see that val is correct. But sel is just the number as used in $i so 0 1 2
You are using a strict equals operator to compare a Number (parseFloat) agains .innerHTML, which is always a string.
Convert sel.options[i].innerHTML to a Number aswell:
if (parseFloat(sel.options[i].innerHTML) === val) {
sel.selectedIndex = m;
break;
}
If you want to filter out invalid numbers (NaNs), use !isNaN(val) aswell.
Code to get this working:
function copy_dikte()
{
var i;
var elems = document.getElementsByName('dxf_var_dikte_copy[]');
var elems_1 = document.getElementsByName('dxf_vars[]');
var elems_2 = document.getElementsByName('calc_dikte[]');
var elems_3 = document.getElementsByName('calc_ext[]');
var l = elems.length;
var z;
z=0;
for(i=0; i<l; i++)
{
if(elems_3[i].value == 'dxf')
{
elems[i].value = document.getElementById('dxf_var_dikte').value;
var elems_1_split_1 = (elems_1[i].value).split(elems[i].value+'=');
var elems_1_split_2 = (elems_1_split_1[1]).split(',');
var val = parseFloat(elems_1_split_2[0]);
var sel = elems_2[i];
var opts = sel.options;
for (var opt, j = 0; opt = opts[j]; j++)
{
if (opt.text == val)
{
sel.selectedIndex = j;
break;
}
}
}
}
}
function goOneYear() {
//changing the value of the no rabbits entree
var x = parseInt(document.getElementById("numRabbits").value) + parseInt(document.getElementById("rateBirth").value) * birthRate - parseInt(document.getElementById("rateDeath").value) * deathRate;
if (x < 2000) {
alert("FOX HUNT");
}
document.getElementById("numRabbits").value = x;
//incementing year by 1
document.getElementById("numYears").value++;
//adding this year to the list
var temp = "";
for (int i = 0; i < parseInt(document.getElementById("numRabbits").value); i++) {
temp += "*";
}
printTable.push(document.getElemernyById("numYears").value + " " + temp);
//making the text area the new set
if (document.getElementById("drawGraph").checked == true) {
if (temp.length > document.getElementById("rabbitTable").cols) {
document.getElementById("rabbitTable").cols = temp.length;
}
document.getElementById("rabbitTable").rows = printTable.length;
changeTextArea();
}
//setting conditions back to normal
setRabbitConditions(document.getElementById("normal"));
setRates("normal");
}
use var i = 0 instead of int i = 0
I used arrays of strings to populate drop downs. How do I set the value of each drop down option to the same as the text content?
el.value = opt; doesn't appear to work.
var validCoursesKeys = ['opt 1','opt 2','opt 3','opt 4']
var validKeys = document.getElementsByClassName("validKeys");
setFields("courses");
function setFields(browser) {
//document.getElementById("result").value = browser;
var menuCounter = 1;
if (browser == "courses") {
for (var i = 0; i < validCoursesKeys.length; i++) {
var opt = validCoursesKeys[i];
var el = document.createElement("option");
el.textContent = opt;
el.value = opt;
for (var j = 0; j < validKeys.length; j++) {
var elementClone = el.cloneNode(true);
elementClone.id = menuCounter;
menuCounter++;
validKeys[j].appendChild(elementClone);
}
}
} else if (browser == "rooms") {
var menuCounter = 1;
for (var i = 0; i < validRoomsKeys.length; i++) {
var opt = validRoomsKeys[i];
var el = document.createElement("option");
el.textContent = opt;
el.value = opt;
for (var j = 0; j < validKeys.length; j++) {
var elementClone = el.cloneNode(true);
elementClone.id = menuCounter;
menuCounter++;
validKeys[j].appendChild(elementClone);
}
}
}
};
<select class="validKeys"></select>
<select class="validKeys"></select>
<select class="validKeys"></select>
You can achieve this using jquery. See below updated code using jquery
var validKeys = document.getElementsByClassName("validKeys");
function setFields(browser) {
//document.getElementById("result").value = browser;
var menuCounter = 1;
if (browser == "courses") {
$.each(validCoursesKeys , function(index, keys) {
var content='<option value="' + keys + '">' + keys + '</option>';
validKeys.append(content);
});
} else if (browser == "rooms") {
var menuCounter = 1;
$.each(validRoomsKeys , function(index, keys) {
var content='<option value="' + keys + '">' + keys + '</option>';
validKeys.append(content);
});
}
};
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
}
I am new to coding Javascript. I am trying to to shuffle list of names inputted on a textarea. The user selects the number of groups desired, and shuffle on click, then show the divided groups as output result. Below is my code but it is not working as it should be, pls help!
<script>
function ArrayToGroups(source, groups){
var groupList = [];
groupSize = Math.ceil(source.length/groups);
var queue = source;
for(var r = 0; r < groups; r++){
groupList.push(queue.splice(0,groupSize));
}
return groupList;
}
function textSpliter(splitText){
var textInput = document.getElementById("inputText").value;
var splitText = textInput.split(',');
var newList = [];
for(x = 0; x <= splitText.length; x++) {
var random = Math.floor(Math.random() * splitText.length);
var p = splitText[random];
newList.push(p);
splitText.splice(p,groupList);
}
for(var i = 0; i < newList.length; i++){
var s = newList[i];
document.getElementById('resInput').value += s + "\n" ;
}
return splitText;
}
</script>
Below is my input and output textareas
</head>
<body>
<form>
<textarea id="inputText" placeholder="text" rows="10" cols="40"></textarea>
<input type="number" name="number" max="6" value="1" id="groupNumber">
<textarea id="resInput" placeholder="text" rows="10" cols="40"></textarea>
<input type="button" name="Shuffle" value="shuffle" onclick="textSpliter()">
</form>
</body>
</html>
function shuffle() {
// Get list
// Example: element1, element 2, ele ment 3, ...
var list = document.getElementById("inputText").value.replace(/\s*,\s*/g, ",").split(",");
// Get number of groups
var n = parseInt(document.getElementById("groupNumber").value);
// Calculate number of elements per group
var m = Math.floor(list.length / n);
// Enought elements
if (n * m == list.length) {
// Create groups
var groups = new Array();
for (i = 0; i < n; i++) {
groups[i] = new Array();
for (j = 0; j < m; j++) {
// Random
rand = Math.floor(Math.random() * list.length);
// Add element to group
groups[i][j] = list[rand];
// Remove element to list
list.splice(rand, 1);
}
}
// Output
var text = "";
for (i = 0; i < n; i++) {
text += "Group " + (i + 1) + ": ";
for (j = 0; j < m; j++) {
if (j != 0) { text += ", "; }
text += groups[i][j];
}
text += "\n";
}
document.getElementById("resInput").value = text;
} else {
alert("Add more elements");
}
}
I rewrote your code. It's pretty self-explanatory.
FIDDLE
function textSpliter() {
var input = document.getElementById("inputText").value;
var names = input.split(",");
var groupSize = document.getElementById("groupNumber").value;
var groupCount = Math.ceil(names.length / groupSize);
var groups = [];
for (var i = 0; i < groupCount; i++) {
var group = [];
for (var j = 0; j < groupSize; j++) {
var random = Math.floor(Math.random() * names.length);
var name = names[random];
if (name != undefined) {
group.push(name);
names.splice(names.indexOf(name), 1);
}
}
group.sort();
groups.push(group);
}
printGroups(groups);
}
function printGroups(group) {
var output = document.getElementById("resInput");
output.value = "";
for (var i = 0; i < group.length; i++) {
var currentGroup = "";
for (var j = 0; j < group[i].length; j++) {
currentGroup = group[i].join(",");
}
output.value += currentGroup + "\r";
}
}
ES6 version ;-)
http://jsfiddle.net/dLgpny5z/1/
function textSpliter() {
var input = document.getElementById("inputText").value;
var names = input.replace(/\s*,\s*|\n/g, ",").split(",");
var groupSize = document.getElementById("groupNumber").value;
var groupCount = Math.ceil(names.length / groupSize);
var groups = [...Array(groupCount)].map(() => Array());
var i = 0
while (names.length > 0) {
var m = Math.floor(Math.random() * names.length);
groups[i].push(names[m]);
names.splice(m, 1);
i = (i >= groupCount - 1) ? 0 : i + 1
}
printGroups(groups);
}
function printGroups(groups) {
var output = document.getElementById("resInput");
output.value = groups.map(group => group.join(',')).join('\r');
}