I've run into a problem here. I have a text box that is only returning an empty string.
var myFields = [];
for(var i = 0; i < fields.length; i++){
var newField = document.createElement('input');
newField.type = 'text';
prompt.innerHTML += fields[i] + ': ';
prompt.appendChild(newField);
prompt.innerHTML += '<br>';
myFields.push(newField);
}
var finishPrompt_Action = function(){
var results = {}
for(var i = 0; i < myFields.length; i++){
console.log(fields[i], myFields[i], myFields[i].value);
results[fields[i]] = myFields[i].value;
}
container.removeChild(shield);
container.removeChild(prompt);
callback(results);
}
So, in the second function myFields[i].value returns an empty string.
Although myFields[i] does point to the correct input element.
Anyone got any ideas?
This is the only code that touches the textbox, and I type in the value using my keyboard.
It's sensible to change prompt to something else, to prevent confusion with javascripts native prompt function. Furthermore it looks like your code can work. See this jsfiddle
promptDiv.innerHTML += '<br>';
This was the problem line. If anyone knows why or how this was breaking the code I would REALLY like to know. Commenting out this single line, fixes the problem.
Thanks,
Greg
Related
so I wrote a script to display 5 random arrays, but the page doesn't display anything.
here's the code:
<html>
<head>
<script>
function start(){
var arr(5),result;
result=document.getElementById("arraying");
result="<p>";
for(var i=0; i<5;i++){
arr[i]=Math.floor(Math.random()*10);
result+="arr["+i+"]= "+arr[i]+"</p><p>";
}
result+="</p>";
}
window.addEventListener("load",start,false);
</script>
</head>
<body>
<div id="arraying"></div>
</body>
</html>
I tried removing result=document.getElementById and write document.getElementById.innerHTML=result in the end of the function but didn't work. what's the error?
You cannot use the same variable for different purposes at the same time. First you assign a DOM element to result, and immediately on the next line you overwrite result with a string.
Build a string htmlStr inside your loop, and when that is done, assign this string to result.innerHTML property:
function start() {
let arr = [],
result, htmlStr = '';
result = document.getElementById("arraying");
htmlStr += "<p>";
for (let i = 0; i < 5; i++) {
arr[i] = Math.floor(Math.random() * 10);
htmlStr += "arr[" + i + "]= " + arr[i] + "</p><p>";
}
htmlStr += "</p>";
result.innerHTML = htmlStr;
}
window.addEventListener("load", start, false);
<div id="arraying"></div>
Looking at the code you seem to be missing some basic javascript concepts.
array size
This is probably your main issue:
var arr(5)
This does not make sense in javascript. Array length does not need to be predefined since all arrays are of dynamic length. Simply define an array like this:
var arr = []
Then later when you want to append new elements use push like this:
arr.push( Math.floor(Math.random()*10) )
adding html using innerHTML
There are different ways to dynamically inject html into your page. (It looks like) you tried to append the html as a string to the parent element. This is not possible.
You said you tried using innerHTML. That should work if used correctly.
A working implementation would work like this:
function start() {
var arr = []
var result = "<p>"
for(var i = 0; i < 5; i++) {
arr.push( Math.floor(Math.random()*10) ) // Btw this array isn't actually needed.
result += "arr[" + i + "] = " + arr[i] + "</p><p>"
}
document.getElementById("arraying").innerHTML = result
}
window.addEventListener("load", start, {passive: true});
adding html using createElement
A generally better way of dynamically adding html elements is via createElement.
This way you dont have to write html and are therefore less prone for making errors. It is also more performant and easier to integrate into javascript.
I think the best explaination is a commented implementation:
function start() {
var myDiv = document.getElementById("arraying") // get parent node
var arr = []
for(var i = 0; i < 5; i++) {
arr.push( Math.floor(Math.random()*10) )
var p = document.createElement("p") // create p element
p.innerText = "arr[" + i + "] = " + arr[i] // add text content to p element
myDiv.append(p) // append p element to parent element
}
}
window.addEventListener("load", start, {passive: true});
small tips
The let keyword works mostly the same as the var keyword, but is generally preferred because of some edge cases in which let is superior.
Fusing strings and variables using the plus operator is generally considered bad practice. A better way to do the string concatenation would have been
result += `arr[${i}] = ${arr[i]}</p><p>`
I have an array of records. I want to search a string at the specific position of the array. But some how I am not able to do so. Kindly see the code below:
var match_index = [];
var count = 0;
var keyword1 = csvvalue[1][9].replace(/\"/g, '');
var search_text="इलाहाबाद";
$("#leng").html(csvvalue.length);
for(var i=0; i<csvvalue.length; i++){
$("#index").html("loop");
var keyword1 = csvvalue[i][9].replace(/\"/g, '');
if (search_text === keyword1)
{
match_index[count] = i;
count++;
$("#index").html("match");
}
$("#index").append("<br />" + i.toString());
}
In the above code, the control is is not going inside the if statement, though the string is available in the array at index 1 and 2. Also only the last value of i is getting printed (last line of the code) though it should print all the values of i starting from 0.
My actual requirement is to search through entire array for a specific string. I have changed the code to suit my requirement better.
Edited
I tried every thing but the control is not going inside the if statement though there are two matching records
You are comparing two values set before the loop
I guess it should be more like :
var match_index = [];
var count = 0;
var keyword1 = "";
var search_text="इलाहाबाद";
$("#leng").html(csvvalue.length);
for(var i=0; i<csvvalue.length; i++){
keyword1 = csvvalue[i].replace(/\"/g, '');
$("#index").html("loop");
if (search_text === keyword1)
{
match_index[count] = i;
count++;
$("#index").html("match");
}
$("#index").append("<br />" + i.toString());
}
Or depending on how your csvvalue array is structured.
keyword1 = csvvalue[1][i].replace(/\"/g, '');
Why loop through the whole array if you want to check a specific variable in the array.
You could just do something like
if (search_text === csvvalue[1][9].replace(/\"/g, '') {
//do something
}
Unless you really need to know how many times you run through the array.
Here http://jsfiddle.net/SW5NH/5/ I created some automatically generated table (DOM + JavaScript).
I want to compare whether checkbox's Input1[z] value (true/false) is equal to Input2's[z] value.
If they are not equal value[z] should change.
Tried in several ways (below the table are some test results), but can not achieve it.
I would appreciate for any help/comments.
function valCheck() {
for (var y2 = 0; y2 < empl.length; y2++) {
var Id1 = 'Option1'+y2+'';
var Id2 = 'Option2'+y2;
var input1 = document.getElementById(Id1).checked;
var input2 = document.getElementById(Id2).checked;
var value = 'Value'+y2+'';
var valEntry = document.getElementById(value);
var debt = (input1==input2) ? 'no debt' : 'debt';
document.getElementById('tabinfo').innerHTML = Id1+input1+ ' ' +Id2+input2+ ' ' +(input1&&input2)+value+valEntry+ ' ' + debt;
document.getElementById(value).createTextNode(debt);
}
}
don't work
UPDATE: Solved. Solution in my last post.
Your comparsion is right but you should be using 'change' eventListener like this
document.addEventListener('change', valCheck, false);
Check this JSFiddle and share your suggestion.
Also use === instead of ==
Here what you need, DEMO HERE
function checkValue() {
var a = document.getElementById('a');
var b = document.getElementById('b');
if (a.checked != b.checked) {
document.getElementById('lab').innerHTML="Not equal";
}
else
document.getElementById('lab').innerHTML = "equal";
}
Thank You all.
My table works now and it rocks already :) It is still in progress, but there are waiting only some cosmetic amendments.
Here is the actual JSFidle http://jsfiddle.net/5tcPz/1
You are welcome to use it if you find it usefull.
My mistake was - document.createTextNode element can't have an ID, so the value of Element value[z] was null.
I solved it in such way:
var fifthCell = document.createElement('DIV');
fifthCell.id = "Value" + y + '';
fifthCellText = document.createTextNode('no debt');
fifthCell.appendChild(fifthCellText);
UPDATE.
http://jsfiddle.net/5dmrW finished table!!! This was my first JavaScript project after codeacademy and a lot of JS online tutorials :) It's a very simple, but I'm proud of it. Regards
Hi I'm stuck I need to pass the Status into the Apply() function. But when I put Apply("+ Status +"); into the for loop it doesn't seem to work. But if Status is equal to some number it works. Please help. Here is my code.
Status is equal to "Complete, Uncomplete".
function querySuccess(tx, results, Type, Status, Amount, Years){
var len = results.rows.length;
var display = "";
display +="<table>";
display +="<tr>";
display +="<td>First Year Rate</td>";
display +="<td>Apply Now</td>";
display +="</tr>";
for (var i=0; i<len; i++){
display +="<tr>";
display +="<td>"+ results.rows.item(i).first_year+"</td>";
display +="<td><input type'button' onClick='Apply();' value='Apply'/></td>";
display +="</tr>";
}
display +="</table>";
}
Try Apply(\""+ Status +"\");. The escaped quotes tells JS that there is a text, otherwise it thinks there are some variables.
You can use single-quotes Apply('"+ Status +"');, but this need some modifications in your code.
if status is a string you need to encapsulate it like this:
display +="onClick=\"Apply('"+ Status +"');\" ";
Note the different usage of single and double quotes
If you Status is string you have to use "" for example "String". In your case this should work:
display +="<td><input type'button' onClick='Apply("'+Status+'");' value='Apply'/></td>";
Number works because they dont need apostrophe and thats why they are processed correctly.
I made simplier example and used your code to show it. Check your JavaScript console to see a result:
http://jsfiddle.net/EE8hN/
check this one.this wil work
display += '<td><input type="button" onClick="Apply('+status+')" value="Apply"/></td>'
function querySuccess(tx, results, Type, Status, Amount, Years){
var len = results.rows.length;
var display = document.createElement('table');
var tr = document.createElement('tr');
var td = document.createElement('td');
var tmpEl;
var tmpTr = tr.cloneNode();
var tmpTd = td.cloneNode();
tmpTd.textContent = "First Year Rate";
tmpTr.appendChild(tmpTd);
tmpTd = td.cloneNode();
tmpTd.textContent = "Apply Now";
tmpTr.appendChild(tmpTd);
display.appendChild(tmpTr);
for (var i=0; i<len; i++){
tmpTr = tr.cloneNode();
tmpTd = td.cloneNode();
tmpTd.textContent = result.rows.item[i].first_year;
tmpTr.appendChild(tmpTd);
tmpEl = document.createElement('input');
tmpEl.type = 'button';
tmpEl.value = 'Apply';
tmpEl.onclick = Apply; // yeah, just like this
tmpTd = td.cloneNode();
tmpTd.appendChild(tmpEl);
tmpTr.appendChild(tmpTd);
}
}
I'm trying to change the value of an input field with Javascript.
I tried everything, but nothing seems to works. I tried putting the 5 between quotation marks and using jquery. I also double-checked the array and everything.
Here is the input code:
<input type="number" id="id_[SOME_ID_HERE]" value="0">
and the loop used to update the values.
for (var i = 0; i < shoppingCart.length; i++) {
var val = shoppingCart[i];
document.getElementById("id_" + val.substring(3)).value = 5;
}
jsfiddle: http://jsfiddle.net/zkTud/
EDIT: Seems like it doesn't work with type="text" as well...
EDIT2: Thank you everyone who answered. My problem was actually something else.
The input was loaded from another page, and it took time and the for loop I had problem with (see above) was executed before the file was done loading.
All I did was to move the for loop as is to the callback function and it works now.
Thanks anyways!
I really appreciate the help I'm getting in this site! :)
The problem is that your call to substring is returning too much of the string, so there are no elements found by getElementById. Change it to this:
for(var i = 0; i < shoppingCart.length; i++) {
var val = shoppingCart[i];
document.getElementById("id_" + val.substring(5)).value = 5;
}
Here's an updated fiddle.
The substring method (when called with one argument) returns the characters from the index specified to the end of the string. Since you are specifying index 3, you get "d_1", "d_2" etc. when actually you just want the number.
Alternatively, you could of course change the string to which you append the substring, but I think that would be more confusing to read (not immediately obvious which element will be returned):
document.getElementById("i" + val.substring(3)).value = 5;
demo http://jsfiddle.net/bY4EV/6/
sustring(3) gives d_1 : How to substring in jquery
hope this helps
code
var shoppingCart = new Array();
shoppingCart[0] = "prod_1";
shoppingCart[1] = "prod_3";
shoppingCart[2] = "prod_2";
for(var i = 0; i < shoppingCart.length; i++) {
var val = shoppingCart[i];
$("#id_" + val.substring(5)).val("5");
}
Check this, JSFiddle , Updated and corrected your problem.
Code:
var shoppingCart = new Array();
shoppingCart[0] = "prod_1";
shoppingCart[1] = "prod_3";
shoppingCart[2] = "prod_2";
for(var i = 0; i < shoppingCart.length; i++) {
var val = shoppingCart[i];
$("#id" + val.substring(4)).val( "5");
}