Sceneario:
I am making custom html in a WebBrowser control basically it is to enter student marks . On a column Total score when user enters number in it the grade in next column should be automatically populated, assuming for now score above 50 then grade = A , else grade = F.
My Code:
This is how i am making html :
for (int i = 0; i < studentData.Tables[0].Rows.Count; i++)
{
string fullname = studentData.Tables[0].Rows[i]["first name"].ToString().ToUpper() + " " + studentData.Tables[0].Rows[i]["surname"].ToString().ToUpper() + " " + studentData.Tables[0].Rows[i]["Other name"].ToString().ToUpper();
string studentNumber = studentData.Tables[0].Rows[i]["studentformnum"].ToString().ToUpper();
string tmptxt = string.Empty;
tmptxt = "<tr class=\"records\"><td><input onchange=\"doit('score" + i + "','grade_" + i + "')\" ";
tmptxt += "id=\"totalScore\" id=\"score" + i + "\" style=\"text-align:center\" type=\"text\" /></td>";
tmptxt += "<td><input id=\"grade_" + i + "\" style=\"text-align:center\" type=\"text\" /></td><td></td></tr>";
sb.Append(tmptxt);
}
And Javascript Funtion:
content = content.Replace("{JAVASCRIPT}", "<script type='text/javascript'>function doit(tag,tag2)
{ alert(tag); var score= document.getElementById(tag).value; alert(score);}</script>");
alert(tag) works then i get error.
This Does not work i get error popup , value null or undefined etc..
If i just do alert('abc'); i see alert .
Any suggestion what i am missing here?
The single/double quotes for tmptext are all wrong.
Related
I am new to javascript and I am creating a bookstore using the google API. I have a small issue which I couldn't figure out. In the below piece of code that I saw from example code of google api bookstore function, I am trying to create href for the title of the book and pass its selfLink to the destination page i.e book-description.html.
When I put alert(this.id) on onclick It works, but for a normal method get(this) it does not work. I do not need an alertbox I want to take the id of the link clicked in href and pass it to another html.
handleResponse(response) {
for (var i = 0; i < response.items.length; i++) {
var item = response.items[i];
var a = item.volumeInfo.title;
var selfL = item.selfLink;
//var b = a.link("book-description.html");
var image = item.volumeInfo.imageLinks.smallThumbnail;
document.getElementById("content").innerHTML += "</br>" + "</br>" + "<br>" + "<img src =" + "'" + image + "'" + " class='im'/>";
document.getElementById("content").innerHTML += "<h4 class='right'>" + "<a href = 'book-description.html'id = " + "'" + selfL + "'" +
"onclick ='get(this);'>" + a + "</a></h4>";
function get(e) {
var link = e.id;
localStorage.setItem("Link", link);
}
document.getElementById("content").innerHTML += "<h4 class='right'>" + "AUTHOR:" + item.volumeInfo.authors + "</h4>";
document.getElementById("content").innerHTML += "<h5 class='right'>" + "PUBLISHER:" + item.volumeInfo.publisher + "</h5>";
var rating = item.volumeInfo.averageRating;
if (rating) {
document.getElementById("content").innerHTML += "<h5 class='right' id='rating'>" + rating + "</h5>";
} else {
document.getElementById("content").innerHTML += "<h5 class = 'right' id ='rating'>Not Rated Yet</h5>";
}
//document.getElementById("content").innerHTML += "<br>" + "<br>" + "<br>" + item.volumeInfo.publisheddate;
}
}
There are a number of problems with your code, but specifically in answer to your question; your function get is scoped so it is only available within the function handleResponse. For it to be accessible from an onclick it must be in page scope.
Simply move this
function get(e) {
var link = e.id;
localStorage.setItem("Link", link);
}
Into the head of your page
In programming there is the concept of DRY (Don't repeat yourself). So store a reference to document.getElementById("content") and reuse that variable.
var content = document.getElementById("content");
content.innerHTML = ...
You're missing some spaces in your output html. This may work in some browsers, others will struggle
<a href = 'book-description.html'id=
Should have a space between the end of one attribute and the start of another
<a href='book-description.html' id=
And for heaven sake, sort out the concatenation of your strings. You dont need a + if its just a simple string
document.getElementById("content").innerHTML += "</br>" + "</br>";
should be
document.getElementById("content").innerHTML += "</br></br>";
I am trying to import information from an XML file, and create a name which, when clicked, will show more information. This information will be inside a div with no display until the header has been clicked.
This is the idea. Doesn't work.
$(document).ready(function () {
$.ajax({
type: "Get",
dataType: "xml",
url: 'service.xml',
success: function (xml) {
$(xml).find('Service[Name="j1979"]').find("Define").each(function () {
var PID = $(this).attr("PID");
var name = $(this).find("Name").text();
var source = $(this).find("source").text();
var doffset = $(this).find("DOffset").text();
var type = $(this).find("Type").text();
var length = $(this).find("Lenght").text();
var scale = $(this).find("Scale").text();
var noffset = $(this).find("NOffset").text();
var units = $(this).find("Units").text();
var moreinfo = "<div id='moreinfo'>source += '\r\n' += doffset += '\r\n' += type += '\r\n' += length += '\r\n' += scale += '\r\n' += noffset += '\r\n' += units</div>";
document.getElementById("j1979").innerHTML += PID += " ";
document.getElementById("j1979").innerHTML += < p onclick = "document.getElementById('moreinfo').style.display = 'inline-block'" > += "\r\n";
document.getElementById("j1979").innerHTML += moreinfo;
});
}
});
});
Sorry for any obvious mistakes and/or ugly code.
I assume that this is what you want to achieve: DEMO
just assume that the script in the demo is inside the success function
first, you have some error in here
document.getElementById("j1979").innerHTML += < p onclick = "document.getElementById('moreinfo').style.display = 'inline-block'" > += "\r\n";
this will not add the p element to the element with id j1979 because you write it like that, where you should be writing it like this
document.getElementById("j1979").innerHTML += "<p onclick=\"document.getElementById('moreinfo').style.display = 'inline-block';\" ></p>";
note the quotes at start and end, and the closing tag
second, there's no word or anything inside the p element that indicates that you could click it to show more information, so put the PID inside the p like this
document.getElementById("j1979").innerHTML += "<p onclick=\"document.getElementById('moreinfo').style.display = 'inline-block';\">" + PID + "</p>";
here's the full code with some CSS style to hide it before the user click on the PID
$(document).ready(function () {
var PID = "testPID";
var name = "Random Name";
var source = "Google";
var doffset = "1000";
var type = "A-9001";
var length = "50CM";
var scale = "100";
var noffset = "0";
var units = "Some Units";
var moreinfo = "<div id='moreinfo'>source: " + source + "</br>" + "doffset: " + doffset + "</br>" + "type: " + type + "</br>" + "length: " + length + "</br>" + "scale: " + scale + "</br>" + "noffset: " + noffset + "</br>" + "units: " + units + "</div>";
document.getElementById("j1979").innerHTML += "<p onclick=\"document.getElementById('moreinfo').style.display = 'inline-block';\">" + PID + "</p>";
document.getElementById("j1979").innerHTML += moreinfo;
});
#moreinfo {
display: none;
}
#j1979 {
color: blue;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.1/jquery.min.js"></script>
<div id="j1979"></div>
From the code you have, you can use '+' operator to concatenate strings.
When you need to use single quote inside string defined with single quote, you can use backslash (\) as escape character before it.
Also, you need to hide the div with class "moreinfo" initially.
As for new line, if you want each attribute in new line in moreinfo class, it can be achieved by using HTML "pre" tag or "br" tag or some other way.
So code would be:
var moreinfo = "<pre id='moreinfo' style='display:none'> source = " + source + "\r\n doffset = " + doffset + "\r\n type = " + type + "\r\n length = " + length + "\r\n scale = " + scale + "\r\n noffset = " + noffset + "\r\n units = " + units +"</pre>";
document.getElementById("j1979").innerHTML += '<p onclick="document.getElementById(\'moreinfo\').style.display = \'inline-block\'">\r\n' + PID + "</p>";
document.getElementById("j1979").innerHTML += moreinfo;
or
var moreinfo = "<div id='moreinfo' style='display:none'> source = " + source + "<br> doffset = " + doffset + "<br> type = " + type + "<br> length = " + length + "<br> scale = " + scale + "<br> noffset = " + noffset + "<br> units = " + units +"</div>";
document.getElementById("j1979").innerHTML += '<p onclick="document.getElementById(\'moreinfo\').style.display = \'inline-block\'">\r\n' + PID + "</p>";
document.getElementById("j1979").innerHTML += moreinfo;
If you want to toggle display on click, you can use ternary operator to give condition in onclick function:
var moreinfo = "<div id='moreinfo' style='display:none'> source = " + source + "<br> doffset = " + doffset + "<br> type = " + type + "<br> length = " + length + "<br> scale = " + scale + "<br> noffset = " + noffset + "<br> units = " + units +"</div>";
document.getElementById("j1979").innerHTML += '<p onclick="document.getElementById(\'moreinfo\').style.display == \'inline-block\' ? document.getElementById(\'moreinfo\').style.display = \'none\' : document.getElementById(\'moreinfo\').style.display = \'inline-block\'">\r\n' + PID + "</p>";
document.getElementById("j1979").innerHTML += moreinfo;
I wrote a program where I needed to toggle a div with javascript. I found a solution with this code.
function toggle( selector ) {
var nodes = document.querySelectorAll( selector ),
node,
styleProperty = function(a, b) {
return window.getComputedStyle ? window.getComputedStyle(a).getPropertyValue(b) : a.currentStyle[b];
};
[].forEach.call(nodes, function( a, b ) {
node = a;
node.style.display = styleProperty(node, 'display') === 'block' ? 'none' : 'block';
});
You can then call the function with:
toggle('.idOrClass');
make sure you use single quotes around the class or id name
Hope this helps! :)
I need to pass in the selector a hidden field to a javascript function.
This is my function
function deleteAttachments(id,selector){
$('#proof' + id).remove();
//show warning about save
var tmp = selector.val();
var sep = "";
if (tmp != "")
sep = ",";
selector.val(tmp + sep + id);
}
The above function call is inside the following method,
function listAttachments(proofs,selector,hiddenField,after){
//alert(hiddenField.id);
var rows = "<table width=\"70%\">";
for(var i=0; i<proofs.length; i++) {
var proof = proofs[i];
rows += "<tr id=\"proof" + proof["ID"] + "\" width=\"40%\">"
rows += "<td><input type=\"hidden\" value=\"" + proof["filename"] + "\" id=\"Proof" + i + "\" />Uploaded: " + proof["uploaded"] + "</td>"
rows += "<td width=\"90px\"><input type=\"button\" value=\"View...\" onclick=\"viewProof('" + proof["URL"] + "'); \" id=\"btnProof" + i + "\" class=\"btn\"></td>"
rows += "<td width=\"90px\"><input type=\"button\" value=\"Delete\" id=\"btnDelete" + i + "\" onclick=\"deleteAttachments(" + proof["ID"] + "," + hiddenField + ");\" class=\"btn\"/></td></tr>";
}
rows += "</table>";
if(after){
selector.after(rows);
}else{
selector.html(rows);
}
}
Please find the listAttachments function calls (I am using asp.net and tried different ways) below,
listAttachments(visualIds,$('#tblProofs'),$('#hidDeletedAttachments'),true)
or
listAttachments(visualIds,$('#tblProofs'),$('#' + <%= hidDeletedAttachments.ID%>'),true)
When this is rendered the deleteAttachments function accepts the argument as an object (as displayed in the image below).
My question is how I can pass the selector to the function and use it with in the calling function.
You are not passing the selector, you are passing a collection of elements that match the selector.
Instead of passing the hiddenField to listAttachments, pass the hiddenField id.
listAttachments(visualIds,$('#tblProofs'), 'hidDeletedAttachments'),true)
Then create the object in the deleteAttachment function
function deleteAttachments(id,hiddenFieldId){
var selector = $('#' + hiddenFieldId);
$('#proof' + id).remove();
//show warning about save
var tmp = selector.val();
var sep = "";
if (tmp != "")
sep = ",";
selector.val(tmp + sep + id);
}
Im new here, Im new in programming as well and I seldom code anything, but recently I've always wanted to improve my work place and I just want to create a simple form for my colleagues.
To make things short, I've created the form, what I need is just generating all the result of the form into a textarea.
Now my problem is, I've made several type of "Event" in the form that have different set of choices, and what I want is the result of that set of "Event" generated as well with the basic information.
Well, here example of my code; Begin Javascript
function generateresult() {
name = document.FORM.namefromtextarea.value;
phone = document.FORM.phonefromtextarea.value;
address = document.FORM.addressfromtextarea.value;
name2 = "Name: " + name + "\n";
phone2 = "Phone: " + phone + "\n";
address2 = "Address: " + address + "\n";
//problem type 1
lostitem = document.FORM.lostitemfromtextarea.value;
when = document.FORM.whenfromtextarea.value;
where = document.FORM.wherefromtextarea.value;
lostitem2 = "Lost Item?: " + lostitem + "\n";
when2 = "When?: " + when + "\n";
where2 = "Where?: " + where + "\n";
//problem type 2
lostperson = document.FORM.lostpersonfromtextarea.value;
personage = document.FORM.personagefromtextarea.value;
personcloth = document.FORM.personclothfromtextarea.value;
lostperson2 = "Person Name?: " + lostperson + "\n";
personage2 = "Age?: " + personage + "\n";
personcloth2 = "Wearing?: " + personcloth + "\n";
if (document.FORM.problemtype.value="Lost Item")
{
eventtype = type1;
}
else if (document.FORM.problemtype.value="Lost Person")
{
eventtype = type2;
}
type1 = lostitem2 + when2 + where2 ;
type2 = lostperson2 + personage2 + personcloth2 ;
document.FORM.generateresulttext.value = name2 + phone2 + address2 + eventtype ;}
End of javascript
And if a user clicked option that have value "Lost Person", the result for generated text will be taken from event "type2"
So I've managed to get the result for name, phone, and address, but as for lost item result, the value of the result became "undefined".
So... how exactly can I code this? I am not even sure if Im really doing the right script / method for my simple form... Thanks in advance
It looks to me like you might be trying to create a variable that takes data from an inexistant element. You might want to put the code you have inside another function.
function generateresult() {
name = document.FORM.namefromtextarea.value;
phone = document.FORM.phonefromtextarea.value;
address = document.FORM.addressfromtextarea.value;
name2 = "Name: " + name + "\n";
phone2 = "Phone: " + phone + "\n";
address2 = "Address: " + address + "\n";
//problem type 1
function firstType(){
lostitem = document.FORM.lostitemfromtextarea.value;
when = document.FORM.whenfromtextarea.value;
where = document.FORM.wherefromtextarea.value;
lostitem2 = "Lost Item?: " + lostitem + "\n";
when2 = "When?: " + when + "\n";
where2 = "Where?: " + where + "\n";
document.FORM.generateresulttext.value = name2 + phone2 + address2 + lostitem2 + when2 + where2 ;
}
//problem type 2
function secondType(){
lostperson = document.FORM.lostpersonfromtextarea.value;
personage = document.FORM.personagefromtextarea.value;
personcloth = document.FORM.personclothfromtextarea.value;
lostperson2 = "Person Name?: " + lostperson + "\n";
personage2 = "Age?: " + personage + "\n";
personcloth2 = "Wearing?: " + personcloth + "\n";
document.FORM.generateresulttext.value = name2 + phone2 + address2 + lostperson2 + personage2 + personcloth2 ;
}
if (document.FORM.problemtype.value="Lost Item")
{
firstType();
}
else if (document.FORM.problemtype.value="Lost Person")
{
secondType();
}
}
In the future, you should NOT put numbers in a variable's name. You should also NEVER declare variables like you're doing here. When you want to create a variable, you type var variableName = variableValue. You also NEVER use words like where or when for a variable name, but instead name it to something like lostWhere or lostWhen.
I have an ajax function that loads my inbox messages and each of the messages has a user_type and read field.
I'm looping over the messages and generating the html for them.
function initializeMailbox() {
// get all mailbox data
user.GetInboxMessages(function (response) {
if (response) {
inboxMessages['inbox'] = response;
$("#inbox-table").fadeIn();
loadInboxTable();
inboxDataTable = $("#inboxTable").dataTable();
$("#inbox-count").html(inbox_msg_count);
displayMessage(first_msg_id);
}
});
}
function loadInboxTable() {
for (var i = 0; i < inboxMessages['inbox'].length - 1; i++) {
first_msg_id = inboxMessages['inbox'][0].message_id;
var user_type = "";
if (inboxMessages['inbox'][i].user_type = 1)
user_type = "DONOR";
else if (inboxMessages['inbox'][i].user_type = 0)
user_type = "CANDIDATE";
else if (inboxMessages['inbox'][i].user_type = 2)
user_type = "GROUP";
$("#inbox-table-body").append(
"<tr class='data-row' style='height: 75px;'> " +
"<td>" +
"<input type='hidden' id='user_type' value='" + inboxMessages['inbox'][i].user_type + "'/>" +
"<input type='hidden' id='read' value='" + inboxMessages['inbox'][i].read + "'/>" +
"<input type='checkbox' id='" + inboxMessages['inbox'][i].message_id + "'></input></td>" +
"<td>" +
"<p class='left'>" +
"<img class='td-avatar' style='margin-top: 0px !important;' src='/uploads/profile-pictures/" + inboxMessages['inbox'][i].image + "' alt='avatar'/>" +
"<br/>" +
"<span class='user-type'>" + user_type + "</span>" +
"</p></td><td>" +
"<h2 onclick='displayMessage(" + inboxMessages['inbox'][i].message_id + ");'>" + inboxMessages['inbox'][i].firstname + " " + inboxMessages['inbox'][i].lastname + "</h2><br/>" +
"<h3 class='message-subject' onclick='displayMessage(" + inboxMessages['inbox'][i].message_id + ");'>" + inboxMessages['inbox'][i].subject + "</h3><br/><br/>" +
"<h3 style='font-size: 0.7em; margin-top: -25px; float:left;'><span>" + inboxMessages['inbox'][i].datesent.toString().split(" ")[0] + "</span></h3>" +
"</td>" +
"<td><button class='delete-item' onclick='deleteMessage(" + inboxMessages['inbox'][i].message_id + ");' src='/images/delete-item.gif' alt='Delete Message' title='Delete Message' style='cursor: pointer; float:left; margin-left: 5px; margin-top:-3px;'></button></td>" +
"</tr>"
);
// check if the message has been read
if (inboxMessages['inbox'][i].read == 0) {
// not read
$("#message-subject").addClass('read-message');
} else {
// read
$("#message-subject").removeClass('read-message');
}
inbox_msg_count++;
}
}
Now if I alert out the values of user_type and read, I get the correct values, based on the message it's iterating over. But when it outputs, it's only using the value of the first message.
I need to be able to dynamically style the messages with jquery, based on these values. Can someone please tell me why this isn't working...
Well, for one thing, you are using an ID selector:
$("#message-subject").addClass('read-message');
When you actually have a class:
<h3 class='message-subject'...
Use:
$(".message-subject").addClass('read-message');
Secondly, you are making an assignment (=) instead of doing a comparison (==) on user_type.
Might I suggest a different approach instead of a big if..then..else?
Use an array to index your user_types:
var user_type_labels = [ 'CANDIDATE', 'DONOR', 'GROUP' ];
function loadInboxTable() {
for (var i = 0; i < inboxMessages['inbox'].length - 1; i++) {
first_msg_id = inboxMessages['inbox'][0].message_id;
// One line instead of an if/then/else
var user_type = user_type_labels[ inboxMessages['inbox'][i].user_type ];
...
Third, you are adding multiple items with the same ID to your DOM. This is not legal and has undefined consequences.
<input type='hidden' id='user_type' value='...
<input type='hidden' id='read' value='...
You need to use classes for this.
<input type='hidden' class='user_type' value='...
<input type='hidden' class='read' value='...
In your code I think you meant to do the following
if (inboxMessages['inbox'][i].user_type === 1)
Notice the equal signs. What you currently have will always be true and user_type will always be assigned to DONOR