I am using javascript to fill some contents in my form,but when i use a variable to get the object,there post a error "TypeError: mytitle is null"
Here is my code:
var num=0;
function add(){
var tr1=document.getElementById('itable').insertRow(1);
var c0=tr1.insertCell(0);
var c1=tr1.insertCell(1);
var c2=tr1.insertCell(2);
var c3=tr1.insertCell(3);
var c4=tr1.insertCell(4);
c0.innerHTML="<input type='checkbox' name='ck'/>";
c1.innerHTML="<input type='text' style='width:150px;'id='news_title"+ num + "' name='news_title"+num+ "' value="+ document.getElementById('news_title').value+"></input>";
c1.className="titlelimit";
$(".titlelimit").wordLimit(10);
c2.innerHTML="<input type='text' style='width:200px;' id='news_content"+num+"' name='news_content"+num+"' value="+ document.getElementById('news_content').value+"></input>";
c2.className="detailindex";
$(".detailindex").wordLimit(50);
c3.innerHTML="<input type='text' readonly='readonly 'maxlength='4' style='width:70px;' id='news_type"+num+"' name='news_type"+num+"' value="+ document.getElementById('news_type').value+"></input>";
c4.innerHTML="<input type='button' value='删除' onclick='del(this)' />";
num=num+1;
$("#news_title").attr("value","");
$("#news_content").attr("value","");
$("#news_type").attr("value","");
}
window.onload = loadtable;
function loadtable() {
var newstitle = myform.mynewstitle.value
alert(newstitle)
var titlearray = newstitle.split(",");
for(i = 0;i<titlearray.length;i++){
alert(titlearray[i]);
add();
var mytitle = document.getElementById('news_title'+num);
mytitle.value = titlearray[i];
num = num +1;
}
}
num has a global scope, so at the end of add() its value it's 1
when you are in the for cycle, you are using incorrectly num to create your id name.
You have to use i.
var mytitle = document.getElementById('news_title'+i);
and this instruction it's usless, remove it last one of cicle for:
num = num +1;
so:
function loadtable() {
var newstitle = myform.mynewstitle.value
alert(newstitle)
var titlearray = newstitle.split(",");
for(i = 0;i<titlearray.length;i++){
alert(titlearray[i]);
add();
var mytitle = document.getElementById('news_title'+i);
mytitle.value = titlearray[i];
}
You are creating an element with num - 'news_title"+ num
You then increment that with num=num+1;
You then try and find an element with 'news_title'+num
If you created an element 'news_title0', by the time your look for it you're looking for an element with id 'news_title1'
Remove the num=num+1; from your add function, since it already correctly exists in the loop in the loadtable function.
The error is in the following line,
var mytitle = document.getElementById('news_title'+num);
mytitle is not finding any element, you might want to check what 'news_title'+num returns.
Related
I have the below json object and i want to loop through it and display the value in a div.
My json object and the function to run it is below
photos = [{"photo1":"myimage1.jpg",
"photo2":"myimg2.jpg",
"photo3":"myimg3.jpg",
"photo4":"myimg4.jpg",}]
function showPhotoOnLoad(photos,$imgUrl){
var $photoData = photos;
var photoLength = Object.keys($photoData[0]).length;
var i, key;
var $containerWidth = 110;
//alert(photoLength);
if(photoLength >0){
$(".mycarousel-container").show();
for (i in $photoData) {
for (key in $photoData[i]) {
a = $photoData[i][key];
imgsrc = $imgUrl = $imgUrl+a;
var div = $("<div class='mycarousel' style='left:"+left+"px'></div>");
var imgPreview = "<img class='myimg' src="+imgsrc+">";
div = div.append(imgPreview);
$(".carouser-inner").append(div);
left = left+$containerWidth;
}
}
}
//console.log($imgUrl);
}
After i run this function i got 4 div created as expected but only the first child of the div has image shown and the other 3 has broken img, i try to debug and i see var a which is suppose to be the img name like myimg1.jpg and the result i got is
`a=myimg1.jpg` //at first iteration of the for loop which make the img display correctly,
`a=myimg1.jpgmyimg2.jpg` //at the second iteration
`a=myimg1.jpgmyimg2.jpgmyimg3.jpg` //at the third iteration
`a=myimg1.jpgmyimg2.jpgmyimg3.jpgmyimg4.jpg` //at the last iteration
What i want to get is like below so all div created will have the right link to the img
`a=myimg1.jpg` //at the first iteration
`a=myimg2.jpg` //at the second iteration
`a=myimg3.jpg` //at the third iteration
`a=myimg4.jpg //at the last iteration
Problem is with imgsrc = $imgUrl = $imgUrl + a;
Here is the working snippet
var photos = [{"photo1":"myimage1.jpg",
"photo2":"myimg2.jpg",
"photo3":"myimg3.jpg",
"photo4":"myimg4.jpg"}];
showPhotoOnLoad(photos,"imageurl");
function showPhotoOnLoad(photos,$imgUrl){
var $photoData = photos;
var photoLength = Object.keys($photoData[0]).length;
var i, key;
var $containerWidth = 110;
//alert(photoLength);
if(photoLength >0){
$(".mycarousel-container").show();
for (i in $photoData) {
for (key in $photoData[i]) {
a = $photoData[i][key];
imgsrc = "a="+a;
var div = $("<div class='mycarousel' style='left:20px'></div>");
var imgPreview = "<img class='myimg' src="+imgsrc+">";
div = div.append(imgPreview);
$(".carouser-inner").append(div);
console.log(imgsrc);
// left = left+$containerWidth;
}
}
}
//console.log($imgUrl);
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
I am not sure what this line is doing. imgsrc = $imgUrl = $imgUrl + a; you can simply loop over your data like this given your array will have only one object. If it has more you need a for loop wrapping the current loop to get all the objects.
photos = [{"photo1":"myimage1.jpg",
"photo2":"myimg2.jpg",
"photo3":"myimg3.jpg",
"photo4":"myimg4.jpg",}];
function showPhotoOnLoad(photos,$imgUrl){
var $photoData = photos[0];
var $containerWidth = 110;
//alert(photoLength);
if($photoData.length >0){
$(".mycarousel-container").show();
for (var i in $photoData){
imgsrc = $photoData[i];
var div = $("<div class='mycarousel' style='left:"+left+"px'></div>");
var imgPreview = "<img class='myimg' src="+imgsrc+">";
div = div.append(imgPreview);
$(".carouser-inner").append(div);
left = left+$containerWidth;
}
}
}
//console.log($imgUrl);
}
Use Object.keys.length to get the length of the object.
Use for..in to get value of each key
var photos = [{
"photo1": "myimage1.jpg",
"photo2": "myimg2.jpg",
"photo3": "myimg3.jpg",
"photo4": "myimg4.jpg",
}]
var _div = ("<div class='mycarousel' style='left:2px'></div>");
var _divCache = "";
if (Object.keys(photos).length > 0) { // will check if the length is greater than 0
$(".mycarousel-container").show()
// loop through each of the key. 0 since photos is an array of object
for (var keys in photos[0]) {
//photos[0][keys] will return values
var imgPreview = $("<img class='myimg' alt='img' src='" + photos[0][keys] + "'>");
$(".carouser-inner").append($(_div).append((imgPreview)[0]));
}
}
JSFIDDLE
Enjoy ONE-LINE code that replaces almost All your code:
$(photos.map((item)=>
Object.keys(item).map((key)=>
`<div class='mycarousel' style='left:${left}px'>
<img src="${item[key]}" class="myimg" />
</div>`
).join('')
).join('')).appendTo('.carouser-inner')
Known that : $(A).append(B) is the same of $(B).appendTo(A)
DEMO
There is some part of my code that gives me headaches. I've missed something. I want to create, declare variables by array but it won't work. It works fine when I declare them manually (like am1=1; am2=2;...). But the problem is when I try the for loop and to create variables that way.
There is the FIDDLE of my problem
myhtml.html
1.Question:<br/>
<textarea name="question11" ></textarea><br/><div id="inner1"></div><button type="button" onClick="addmore1();">Add more</button>
<br/><br/>
2.Question:<br/>
<textarea name="question21" ></textarea><br/><div id="inner2"></div><button type="button" onClick="addmore2();">Add more</button>
myscript.js
var am = [];
for(var i=1; i<3; i++){
am[i] = 1;
}
function addmore1() {
am1++;
n=1;
var textarea = document.createElement("textarea");
textarea.name = "question" + n + am1;
var div = document.createElement("div");
div.innerHTML = textarea.outerHTML;
document.getElementById("inner"+n).appendChild(div);
}
function addmore2() {
am2++;
n=2;
var textarea = document.createElement("textarea");
textarea.name = "question" + n + am2;
var div = document.createElement("div");
div.innerHTML = textarea.outerHTML;
document.getElementById("inner"+n).appendChild(div);
}
Here is the fiddle with the fix for your problem.
If you look at the developer console (F12 in most browsers), you can see the error: am1 and am2 are undefined.
I guess what you meant to do is to refer to am[1] instead of am1. Althought the code is working after that change, there is a lot of room for improvement: you could reuse more code by having only one addmore function, etc . e.g.:
function addmore(index) {
am[index]++;
var textarea = document.createElement("textarea");
textarea.name = "question" + index + am[index];
var div = document.createElement("div");
div.innerHTML = textarea.outerHTML;
document.getElementById("inner"+index).appendChild(div);
}
if you are declaring them by array, why aren't you using them by array?
var am = [];
for(var i=1; i<3; i++){
am[i] = 1;
}
function addmore1() {
am[1]++;
n=1;
var textarea = document.createElement("textarea");
textarea.name = "question" + n + am[1];
var div = document.createElement("div");
div.innerHTML = textarea.outerHTML;
document.getElementById("inner"+n).appendChild(div);
}
function addmore2() {
am[2]++;
n=2;
var textarea = document.createElement("textarea");
textarea.name = "question" + n + am[2];
var div = document.createElement("div");
div.innerHTML = textarea.outerHTML;
document.getElementById("inner"+n).appendChild(div);
}
or am I missing something?
You must use .push() to add values to an array.
var am = [];
for(i=1; i<3; i++){
am.push(1);
}
Sorry if I didn't answer your question completely.
JavaScript is not calling a function when parameter is passed.
I am creating HTML dynamically.
checkbox2 = document.createElement("<input type=\"checkbox\" name=\"wdrs_contact\" checked=\"Yes\" onclick =\"setPartnersInfo('\"+id+\"');\" />");
function setPartnersInfo(ch)
{
alert(ch)
}
But when I do not have parameter in the function call, it is working.
details below:
function createPartnerTable() {
var partnerInfo = document.getElementById("partnersInfo");
var data = partnerInfo.value;
// everything was successful so now come back and update, first clear the old attributes table
var partnersBody = document.getElementById("partnersBody");
var rowCount = partnersBody.rows.length;
for( var i = 0; i < rowCount; i++ )
{
partnersBody.deleteRow(0);
}
if (data ==null || data.length==0)
return;
// now parse and insert each partner row
//alert("data : "+data);
var index = 0;
var lastIndex = 0;
while( index < data.length && index != -1 )
{
lastIndex = data.indexOf("|", index);
if( lastIndex == -1 ){
break;
}
var id = data.substring(index, lastIndex);
index = lastIndex + 1;
lastIndex = data.indexOf("|", index);
var name = data.substring(index, lastIndex);
index = lastIndex + 1;
lastIndex = data.indexOf("|", index);
var partnerType = data.substring(index, lastIndex);
index = lastIndex + 1;
lastIndex = data.indexOf("|", index);
var status = data.substring(index, lastIndex);
index = lastIndex + 1;
lastIndex = data.indexOf(";", index);
var jdeCode = data.substring(index, lastIndex);
//ganessin
index = lastIndex + 1;
lastIndex = data.indexOf("#", index);
var wdrsContact = data.substring(index, lastIndex);
row = partnersBody.insertRow(partnersBody.rows.length);
//check box with id for removal
var checkboxCell = row.insertCell(0);
checkboxCell.align="center";
var checkbox = document.createElement('<input type="checkbox" name="selectedPartnerIds" />');
//var checkbox = document.createElement("input");
//checkbox.type = 'checkbox';
//checkbox.checked=false;
//checkbox.name = 'selectedPartnerIds';
checkbox.value=id;
//checkbox.style.align = "center";
//checkbox.style.width = '40%';
checkboxCell.appendChild(checkbox);
var check = document.getElementsByName('selectedPartnerIds');
//Name
var nameCell = row.insertCell(1);
nameCell.appendChild(document.createTextNode(name));
//Partner Type
var partnerTypeCell = row.insertCell(2);
partnerTypeCell.align="center";
partnerTypeCell.appendChild(document.createTextNode(partnerType));
//Status
var statusCell = row.insertCell(3);
statusCell.align="center";
statusCell.appendChild(document.createTextNode(status));
//JDE Code
var jdeCodeCell = row.insertCell(4);
jdeCodeCell.align="center";
jdeCodeCell.appendChild(document.createTextNode(jdeCode));
//ganessin
var checkboxCell2 = row.insertCell(5);
checkboxCell2.align="center";
var checkbox2 = "";
//alert("wdrsContact "+wdrsContact);
var x = "setPartnersInfo("+id+")";
alert("x = "+x);
if(wdrsContact == "true")
{
alert("true");
//checkbox2 = document.createElement('<input type="checkbox" name="wdrs_contact" checked="Yes" onclick="+x+" onchange="+x+" />');
checkbox2 = document.createElement("<input type=\"checkbox\" name=\"wdrs_contact\" checked=\"Yes\" onclick =\"setPartnersInfo(\"+id+\");\" />");
//String(document.createElement('<input type="checkbox" name="wdrs_contact" checked="Yes" onchange="setPartnersInfo("+id+");"/>'))
}
else
{
alert("false");
//checkbox2 = document.createElement('<input type="checkbox" name="wdrs_contact" onclick="+x+" onchange="+x+" />');
checkbox2 = document.createElement("<input type=\"checkbox\" name=\"wdrs_contact\" onclick=\"setPartnersInfo(\"+id+\");\" />");
}
//alert("id "+id);
//checkbox2.value=id;
// alert("checkbox2 "+checkbox2);
checkboxCell2.appendChild(checkbox2);
// increment the index to process next
index = lastIndex + 1;
}
}
The following will generate a syntax error:
"onclick =\"setPartnersInfo('\"+id+\"');\""
You should use:
"onclick =\"setPartnersInfo(\'"+id+"\');\""
Or if your id is numeric (you don't need quotes):
"onclick =\"setPartnersInfo("+id+");\""
If you wish to use double quotes within a html attribute you have to convert them to "
So the following should work too:
"onclick =\"setPartnersInfo(""+id+"");\""
Although should isn't really the right word as generating html with event listeners like this is not the best approach.
So overall your string should be:
("<input type=\"checkbox\" name=\"wdrs_contact\" checked=\"Yes\" onclick =\"setPartnersInfo('"+id+"');\" />");
Although to get around the escaping all the time why not use:
('<input type="checkbox" name="wdrs_contact" checked="Yes" onclick ="setPartnersInfo(\''+id+'\');" />');
in the interest of improvement
The better way to achieve what you are doing is to split your code from your markup, and leave the browser to generate your markup, this is easier to read and tends to be faster - plus it means you don't have to worry so much about escaping quotes ;)
checkbox2 = document.createElement('input');
checkbox2.type = 'checkbox';
checkbox2.name = 'wdrs_contact';
checkbox2.checked = 'checked';
checkbox2.onclick = function(){
setPartnersInfo(id);
}
One major difference to be aware of in the above is that before when you placed your id var in the html string - it's current value was recorded in that string. With the above the reference to the id variable is remembered but not the value. If you change the value of id at any point after this, it will still change whereever it is referenced. To get around this you can use a closure.
This works by passing the value of id into a function, which basically changes the variable being used to store your value of id to stored_id, this function then returns a function that is used as your event handler. This event handler function has access to the stored_id var, and no matter how much you change id, stored_id wont be changed. It's a bit complicated, if you don't know about closures then it's a good topic to read up on.
checkbox2.onclick = (function(stored_id){
return function(){setPartnersInfo(stored_id);};
})(id);
To improve the above even further you should be avoiding using inline event handlers, so:
checkbox2 = document.createElement('input');
checkbox2.type = 'checkbox';
checkbox2.name = 'wdrs_contact';
checkbox2.checked = 'checked';
/// for modern browsers
if ( checkbox.addEventListener ) {
checkbox.addEventListener('click', function(){
setPartnersInfo('your id here');
});
}
/// for old ie
else {
checkbox.attachEvent('onclick', function(){
setPartnersInfo('your id here');
});
}
For some reason i can't get the variable 'total' to define at all...
I defined it on like 74 but it does't want to stick for some reason.. what am i doing wrong? Thanks in advance!
$(document).ready(function() {
function getParameterByName(name)
{
name = name.replace(/[\[]/, "\\\[").replace(/[\]]/, "\\\]");
var regexS = "[\\?&]" + name + "=([^&#]*)";
var regex = new RegExp(regexS);
var results = regex.exec(window.location.search);
if(results == null)
return "";
else
return decodeURIComponent(results[1].replace(/\+/g, " "));
}
$(".tab-content").hide(); //Hide all content
$("ul.tabs li:first").addClass("active").show(); //Activate first tab
$(".tab-content:first").show(); //Show first tab content
$('.question-form-submit').click(function(e) {
e.preventDefault();
var activeTab = '#'+$(this).attr('name');
var activeClass = activeTab.substr(5);
$("ul.tabs li").removeClass("active");
$('ul li:nth-child('+activeClass+')').addClass("active"); //Add "active" class to selected tab
$(".tab-content").hide(); //Hide all tab content
$(activeTab).fadeIn(); //Fade in the active ID content
$('.meter-value').removeClass('meter-width');
switch (activeClass) {
case '2' :
$('.meter-value').attr('style', 'background-color: #9496c9; width: 46.5%;');
break;
case '3' :
$('.meter-value').attr('style', 'background-color: #9496c9; width: 67%;');
break;
case '4' :
$('.meter-value').attr('style', 'background-color: #9496c9; width: 100%;');
break;
}
return false;
});
$('.quantity, .init_cost').change(function() {
var row_id = $(this).attr('id');
var row_number = row_id.substr(9);
var item_cost = $('#cost_'+row_number).attr('value');
var item_quantity = $('#quantity_'+row_number).attr('value');
var final_cost = item_cost * item_quantity;
$('#final_cost_'+row_number).val(final_cost).formatCurrency();;
});
$('.row input').each(function(index) {
var row_id = $(this).attr('id');
var row_number = row_id.substr(9);
var item_cost = $('#cost_'+row_number).attr('value');
var item_quantity = $('#quantity_'+row_number).attr('value');
var final_cost = item_cost * item_quantity;
$('#final_cost_'+row_number).val(final_cost).formatCurrency();;
});
var total = 0;
$('.final_cost').each(function(index) {
var final_cost = $(this).attr('value').substr(1);
var total = total + final_cost;
console.log(total);
})
});
The inner declaration on the line var total = total + final_cost; hides the outer declaration from the line var total = 0;.
The total in the each function is shadowing the outer one.
A simpler example of the same thing is here:
(function()
{
var total = 1;
console.log("total 1: " + total);
(function()
{
console.log("total 2: " + total);
var total = total + 3;
console.log("total 3: " + total);
})()
})();
In addition to the shadowing, you have to consider hoisting. Because the inner var is hoisted to the top, the inner function is roughly equivalent to:
function()
{
var total = undefined;
console.log("total 2: " + total);
total = total + 3;
console.log("total 3: " + total);
}
In this case, I think you simply don't want the inner var keyword. In other cases, you would use a different variable name.
You're redefining total every time you loop through
$('.final_cost').each(function(index) {
var final_cost = $(this).attr('value').substr(1);
var total = total + final_cost;
console.log(total);
})
Why not try this?
$('.final_cost').each(function(index) {
var final_cost = $(this).attr('value').substr(1);
total = total + final_cost;
console.log(total);
})
Try to remove second var before the total.
total = total + final_cost;
That's because you declare the variable two times (everytime you write var total it's declared anew. So you have one outside of the "final_cost" function and one inside, which is set to total from outside + final_cost. So in effect you always log the value of final_cost.
Just write total = total + final_cost; and it should work.
Syntax error, killing your script:
$('#final_cost_'+row_number).val(final_cost).formatCurrency();;
^--- extra ;
Next time, check your browser's console (shift-ctrl-J in FF/Chrome) for errors. Things like this are reported instantly.
I'd replace the line:
var total = total + final_cost;
with:
total += final_cost
Not sure about this answer but, try defining the variable total first with a default value like 0 and then use the total + final_cost operation.
var total = 0;
total += final_cost;
why is that? when you declare the total without a default value, the value will be "undefined" so the javascript will represent the following as :
var total = "undefined" + final_cost;
I guess that's the error.
I want to pass a Javascript variable as a argument of a function called on onclick event of a checkbox, and the checkbox is created in innerHTML.
The code snippet is:
function populateValue(Result) {
var valueSet = new Array();
valueSet = Result.split("##");
for (i = 1; i < valueSet.length - 3; i++) {
var tr = document.createElement("tr");
var td = document.createElement("td");
tr.setAttribute("align", "left");
tr.className = "table_ce11";
td.setAttribute("align", "center");
var code = String(valueSet[i - 1]);
td.innerHTML = "<input type='checkbox' name='pCheckBox' value='111' id ='" + code + "' onClick=\"javascript:decide('" + code + "')\">";
tr.appendChild(td);
}
}
function decide(code) {
alert("here");
alert(document.getElementById(code).value);
if (document.getElementById(code).checked) alert("chked");
else alert("unchked");
}
while running this, neither am able to set the id nor to pass the argument of the function decide(). I get the error:
"undetermined string constraint".
But if I hardcode the values the function runs fine.
Any suggestions on this?
Just for starters
Split creates an array.
var valueSet = Result.split("##");
You need to test if there ARE at least 4 items in the array
if (valueSet.length <= 3) return
for (var i = 1; i < valueSet.length - 3; i++) {
no need to create a string when you string concatenate a string anyway
var code = valueSet[i - 1];
No need to use javascript: prefix and no need to pass the code when it is the same as the ID:
td.innerHTML = '<input type="checkbox" name="pCheckBox" value="111" id ="' + code + '" onClick="decide(this.id)">';
Also default align is left and you align center on the cell so get rid of
// tr.setAttribute("align", "left");
can you post more of the code and tell where things are going wrong exactly?