JavaScript function doesn't execute everything - javascript

I have an array Orte that contains postcode and the name of the city.
Now I want to change the dropdown depending on the number entered in the input field.
The input field has an onchange function. The function is the one below.
The script works so far except the last line after the for loop. It never adds the last part and I don't know why.
Can someone help me please.
Thanks in advance for the anwsers!
Burzi
function updateOrt(eingabe){
document.getElementById("ort_platzhalter").innerHTML = '<select name="ort">'
for (var i = 1; i <= Orte.length; i++){
if(Orte[i].PLZ == eingabe){
document.getElementById("ort_platzhalter").innerHTML += '<option value="' + Orte[i].id + '">' + Orte[i].Ort + '</option>'
}
}
document.getElementById("ort_platzhalter").innerHTML += "</select>"
}

You should update the innerHTML in one shot. Build up the string first, then assign it. Also, arrays are zero-indexed, so I am guessing you want to start at 0, and end once it is the length of Orte (i = Orte.length).
function updateOrt(eingabe){
var str = '<select name="ort">'
for (var i = 0; i < Orte.length; i++){
if(Orte[i].PLZ == eingabe){
str += '<option value="' + Orte[i].id + '">' + Orte[i].Ort + '</option>'
}
}
str += "</select>"
// now assign the str to innerHTML
document.getElementById("ort_platzhalter").innerHTML = str;
}

your problem is in the array loop.
You are going from 1 to Orte.length, when it reaches Orte.length it throws an exception and the code after the loop does not execute.
you should do it this way:
function updateOrt(eingabe){
document.getElementById("ort_platzhalter").innerHTML = '<select name="ort">'
for (var i = 0; i < Orte.length; i++){
if(Orte[i].PLZ == eingabe){
document.getElementById("ort_platzhalter").innerHTML += '<option value="' + Orte[i].id + '">' + Orte[i].Ort + '</option>'
}
}
document.getElementById("ort_platzhalter").innerHTML += "</select>"
}
because arrays in javascript are 0 indexed and go up to length-1

Related

Invoking a function multiple times but losing past data

Simply working on a homework assignment, at the end, just need to display this method 5 times. Issue is as title states once I invoke the function the next invoke overwrites past invoke.
Heres what I am currently doing.
<p id="table">
<script type="text/javascript">
showResults(race[0], name1, party1, votes1);
showResults(race[1], name2, party2, votes2);
showResults(race[2], name3, party3, votes3);
showResults(race[3], name4, party4, votes4);
showResults(race[4], name5, party5, votes5);
</script>
</p>
I have used a debugger to try and find a fix, browsed the internet for about an hour now, tried to use a .call but couldn't quite get that working either and I know document.write isn't a viable option because it rewrites everything.
Any help or useful links on the issue would be really appreciated!
Here is the showresults function
function showResults(race, name, party, votes)
{
var totalV = totalVotes(votes);
var result = "";
result += "<h2>" + race + "</h2>";
result += "<table cellspacing = '0'>";
result += "<tr>";
result += "<th>Candidate</th>"
result += "<th class='num'>Votes</th>";
result += "<th class='num'>%</th>";
result += "</tr>";
for (var i = 0; i < name.length; i++)
{
result += "<tr>";
result += "<td>" + name[i] + '(' + party[i] + ')' + "</td>";
result += "<td class='num'>" + votes[i] + "</td>";
var percent = calcPercent(votes[i], totalV)
result += "<td class='num'>(" + percent + "%)</td>";
result += createBar(party[i], percent);
result += "</tr>";
}
result += "</table>";
document.getElementById("table").innerHTML = result;
}
The Statement
document.getElementById("table").innerHTML = result;
Sets the innerHTML of your "table" element, thus overwriting it each time you set it.
try to
append(result);
to a existing DOM node so your result gets appended to the document.

Dynamic option list from an array

I have the following code which works perfectly, but can I make the drop menu dynamic using quantityAllowed as the maximum the drop menu goes to. at the moment I have added 10 options for every print, but what i would prefer is the drop menus only have the correct quantity in. I think the loop I need would go where the options begin using the value of the loop, but when i have tried, i just get an error, so I know I have done something wrong.
function arrayData() {
var index;
var text = "<ul>";
var htmlTable = '';
var calcTable = [];
calcTable = [
{ printName:"Name1", printPrice:8000000, quantityAllowed:6},
{ printName:"Name2", printPrice:12000000, quantityAllowed:5},
{ printName:"Name3", printPrice:20000000, quantityAllowed:4},
{ printName:"Name4", printPrice:2000000, quantityAllowed:3},
];//end of array
for (index = 0; index < calcTable.length; index++) {
var myclass = 'class="printwant"';
$("#tbNames tr:last").after("<tr>" +
"<td style='padding:0px 0px 0px 36px;'>" + calcTable[index].printName + "</td>" +
"<td class='printpoints'>" + calcTable[index].printPrice + "</td>" +
"<td>" + calcTable[index].quantityAllowed + "</td>" +
"<td><select " + myclass + "><option value=0>0</option><option value=1>1</option><option value=2>2</option><option value=3>3</option><option value=4>4</option><option value=5>5</option><option value=6>6</option><option value=7>7</option><option value=8>8</option><option value=9>9</option><option value=10>10</option></select></td><td></td> </tr>");
}//end of loop
$("#tbNames tr:last").after("<tr>" + "<td colspan = '5' height=40 > </tr>");
}
You can separate out your HTML generation code from the jQuery DOM assignment. This makes it a little easier to read and manipulate. When you come to your select/option area, drop it into a for... loop to generate the appropriate number of options.
function arrayData() {
var index;
var text = "<ul>";
var htmlTable = '';
var calcTable = [];
calcTable = [
{ printName:"Name1", printPrice:8000000, quantityAllowed:6},
{ printName:"Name2", printPrice:12000000, quantityAllowed:5},
{ printName:"Name3", printPrice:20000000, quantityAllowed:4},
{ printName:"Name4", printPrice:2000000, quantityAllowed:3},
];//end of array
for (index = 0; index < calcTable.length; index++) {
var myclass = 'class="printwant"';
var output = '';
output += "<tr>";
output += "<td style='padding:0px 0px 0px 36px;'>" + calcTable[index].printName + "</td>";
output += "<td class='printpoints'>" + calcTable[index].printPrice + "</td>";
output += "<td>" + calcTable[index].quantityAllowed + "</td>";
output += "<td><select " + myclass + ">";
for( var i=0, x=calcTable[index].quantityAllowed; i<x; i++ ){
output += '<option value="' + i + '">' + i + '</option>';
}
output += "</select></td><td></td> </tr>";
$("#tbNames tr:last").after(output);
}//end of loop
$("#tbNames tr:last").after("<tr>" + "<td colspan = '5' height=40 > </tr>");
}
arrayData();
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table id="tbNames">
<tr></tr>
<tr></tr>
</table>

JavaScript-How to make Html Table editable

I have a function of creating table from a .csv file using JavaScript. I want to make the last column of the table editable. Part of that function where table is being generated is
for (var i = 0; i < CSVLines.length; i++) {
OutputTableRows += "<tr>";
var CSVValues = CSVLines[i].split(",");
for (var j = 0; j < CSVValues.length; j++) {
OutputTableRows += "<td>" + "<p>" + CSVValues[j] + "<p>" + "</td>";
}
OutputTableRows += "</tr>";
}
I have tried
OutputTableRows += "<td>" + "<p contenteditable="true">" + CSVValues[j] + "<p>" + "</td>";
but it's not working
I think you should say in your inner loop:-
if(j == CSVValues.length-1){
tableRow = '<td><input type="text" value="VALUE"/></td>';
tableRow = tableRow.replace('VALUE',CSVValues[j]);
OutputTableRows += tableRow;
}
else{
OutputTableRows += "<td>" + "<p>" + CSVValues[j] + "<p>" + "</td>";
}
I'd suggest, at first glance:
OutputTableRows += "<td>" + "<p" + (j === (CSVValues.length - 1) ? " contentEditable" : "") + ">" + CSVValues[j] + "</p>" +"</td>";
The relevant part, of course, is:
"<p" + (j === (CSVValues.length - 1) ? " contentEditable" : "") + ">"
If j is equal to the length of CSVValues minus 1, then it's reasonable to assume that this must be the last iteration of that for loop, and therefore this is the row that should have the contentEditable attribute, otherwise it should not (and must be an earlier iteration of the loop).
Also, note the changed </p> (from your original <p>), which closes the already-open <p>, as opposed to creating a new, sibling, paragraph element.
References:
Conditional ('ternary') operator.
contentEditable attribute.

Enable selectBox after selecting another one

I trying to set two select-boxes to work by enabling the second select-box after choosing an option from the first.
The results comes from a json with js to a div on my page.
The 2nd select is set to disabled
First try:
JavaScript:
$(document).ready(function () {
$.getJSON('./system/feeds/built.search.php', function (json) {
var output = '';
output += '<div class="search_block">';
output += '<h2><img src="images/search_icon_big.png" alt=""> Search used cars</h2>';
output += '<form id="form1" class="form-style" method="post">';
output += '<label><strong>Company</strong><br>';
output += '<span class="select1">';
output += '<select name="companies" id="companies">';
output += '<option>All</option>';
output += '<option value="company">Company</option>';
for (var i = 0; i < json.company_models.length; i++) {
output += '<option value=' + json.company_models[i].company + '>' + json.company_models[i].company + '</option>';
}
output += '</select>';
output += '</span>';
output += '</label>';
output += '<label><strong>Model</strong><br>';
output += '<span class="select1">';
output += '<select name="models" id="models" disabled>';
output += '<option>Choose Company</option>';
$('#companies').change(function () {
if (this.value) {
document.getElementById('#models').disabled = true;
} else {
document.getElementById('#models').disabled = false;
}
});
for (i = 0; i < json.company_models.length; i++) {
output += '<option value=' + json.company_models[i].model + '>' + json.company_models[i].model + '</option>';
}
output += '</select>';
output += '</span>';
output += '</label>';
$('#search').html(output);
});
});
HTML:
<div id="search" class="grid_12"></div>
jsfiddle.net/mJdmQ
To make it more easy:
Company | Model: To choose the options from Model i must choose first an option from Company
PS: To save you sometime referring about similar questions, I already looked them...
You're looking for a .change() event with jQuery (onchange in pure js), and since this is dynamically loaded data, you'll need to use .on():
$(document).on("change", "#companies", function() {
this.value == "All" ? $("#models").prop("disabled", true) : $("#models").prop("disabled", false);
});

Pass value from loop to javascript function

I have following code:
var storedNames = JSON.parse(localStorage.name);
var mytable = "<table> cellpadding=\"0\" cellspacing=\"0\"><tbody><tr>";
for (var i = 0; i < storedNames.length; i++) {
if (i % 2 == 1 && i != 1) {
mytable += "</tr><tr>";
}
mytable += "<td>" + storedNames[i].name +" "+ storedNames[i].email+"</td><td><img id='arrow' src='arrow.png' height='20' width='20' onclick='redirectToDetail();' ></td></tr>";
}
mytable += "</tbody></table>";
document.write(mytable);
here, in redirectToDetail function i want to i value . How can I pass this?
Any idea?
thank u in advance
try this
mytable += "<td>" + storedNames[i].name +" "+ storedNames[i].email+"</td><td><img id='arrow' src='arrow.png' height='20' width='20' onclick='redirectToDetail(\'"+ i +"\');' ></td></tr>";
and take that in redirectToDetail
function redirectToDetail(val){
alert(val);
}
Just add the value as a literal constant that is passed to the onclick event and you are home free. In addition, I would strongly encourage you to consider using an array and joining the strings as you will yield much better performance particularly in IE.
var storedNames = JSON.parse(localStorage.name);
var mytable = ['<table cellpadding="0" cellspacing="0"><tbody><tr>'];
for (var i = 0; i < storedNames.length; i++) {
if (i % 2 == 1 && i != 1) {
mytable.push("</tr><tr>");
}
mytable.push('<td>' + storedNames[i].name + ' ' + storedNames[i].email + '</td><td><img id="arrow" src="arrow.png" height="20" width="20" onclick="redirectToDetail(' + i + '"></td></tr>"');
}
mytable.push("</tbody></table>");
document.write(mytable.join());
Now you can declare you onclick function like so:
function redirectToDetail(value) {
//do stuff with the value
}
try this
onclick='redirectToDetail(\'"+i+"\')
I think this will do. check it.
mytable += "<td>" + storedNames[i].name +" "+ storedNames[i].email+"</td><td><img id='arrow' src='arrow.png' height='20' width='20' onclick='redirectToDetail(" + i + ");' ></td></tr>";

Categories

Resources