-1

I'm trying to insert a div element on click of every anchor tag that is inside a set of elements of a dynamically generated html table. So far i'm only able to click the tag but not able to identify which row's tag is clicked.

//response from ajax call which is of json array 
// form (data retrieved is actually a hashmap in the serverside)

$.each(response, function(key, value) {
    $("#Table1Id").append('<tr><td><a  id= '+curId+ 'class="achor" href='+""+ '>' + key + '</a></td><td>' + value.Date+ '<br>' + value.userName + '</td><td>' + value.userEmail + '</td><td>' + .... </tr> 
});

//to capture the on click event and identify which row is clicked so 
//that I can place the corresponding key's value in Div element.
$('#container1').on('click','a', function (event) {
    event.preventDefault();

    alert('Anchor clicked!');

    var  inkey = $('#container1 a').html() ;
    alert("the key at the anchor clicked is " + inkey) ; 
    // this value is always the first key's value, in this case it's 1 
    //even if I click row 2's <a> tag.

    var sibling = $(this).next('div');

    if(sibling.is('.expanded')){  
        sibling.toggle();  
    }  
    else{  
    alert("reached else") ; 
    control reaches here but won't execute the below line

    $(this).after("<div class='expanded'><table class='border1' width = 39%   style= 'float: left'> " + "<td> date : <div align=left>" + inkey.value.cusip + "</div></td></tr></table></div>");

});

HTML table format after first ajax call :

    Serial#      Date              Name           Email 
    1            08/16             testuser        blablabla
    2           08/17               testuser       blablabal

Please let me know to to handle this and if generating dynamic table this way is inefficient or poor programming plz provide suggestions to improve this code. Thanks.

kkk
  • 166
  • 2
  • 18
  • You may need to create a [fiddle](http://jsfiddle.net/) since you are not posting the whole relevant chunks of HTML and JS codes. – tmarwen Aug 16 '14 at 10:19
  • You code looks incomplete and invalid. Typos? You didn't close the `else` bracket. There's a comment line that's actually not commented (`//` missing). And the last line is not closed (finishes with a `+`). – emerson.marini Aug 16 '14 at 10:22
  • Tip: Use `console.log()` for debugging and not `alert()`. – emerson.marini Aug 16 '14 at 10:22
  • I've tried to make the code complete using this fiddle [link](http://jsfiddle.net/mwyt8sfe/3/) though it's not working can get the complete code to see the flow or what is the expected behavior. – kkk Aug 16 '14 at 10:54

2 Answers2

0

I'm working from the fiddle, not the original code, since it's more up-to-date.

I don't think the general approach is wrong. But there are several bugs:

  • In the HTML, you've got id= "input1". It should be id="input1", without a space. (Also on input2.) It seems to work on my browser though (Firefox), but it's not standard and I wouldn't trust it to work on all browsers. In generateTable1 you've done the same thing, and you've also missed a space between curId and class="anchor", which will result in something like <a id=myLinkIdField1class="anchor" href=>. (Note the space you have is not inside quotation marks, so will be ignored.)
  • When you run the jsfiddle, you get an error in the console: "ReferenceError: $ is not defined". This means you need to tell jsfiddle to import jQuery. (Use the dropdown menu under "Frameworkd & Extensions" in the left sidebar.)
  • "ReferenceError: input1Val is not defined". This is because you called the variable input1, not input1Val. Use either name, but be consistent. Similarly with input2.
  • Not sure what you're trying to do with the url parameter to $.ajax, but it didn't work, at least in jsfiddle: The console says it was trying to access the URL "http://fiddle.jshell.net/_display/$%7BpageContext.request.contextPath%7D" (which is clearly based on your url parameter with %-encoding).
  • Furthermore the error message is garbled. [object Object] is what you get when javascript tries to convert an object that's not a string into a string but doesn't know how. Check the docs for $.ajax to see what type of object message is.
  • It looks like you've tried to get round the failure to load the URL by overriding the response variable. But actually when you define the function you redeclare the variable, which means that inside the function body the original declaration is overridden. The upshot is the success handler still uses the response from the server instead of the variable you've defined. If you want to use the variable you've defined, change function(response) to function() (since you're not using this variable anyway).
  • Once you've fixed all these things, and triggered the change event, most of the new entries in the table are undefined. These come from value.Field1, value.Field2 and value.Field3 in generateTable1; and value is a value in response, such as {"field1" : "01/08", "field2": "someval", "field3" : "someval3"}. The problem here is that you've named the fields in value as field1 etc, but then tried to access them as Field1 etc; javascript is case sensitive.
  • You should always escape unreliable text that's being inserted into HTML, as it could enable a security breach. For example, suppose field1 is the name of a user. If I register with the username <script>alert('malicious code!');</script>, then my malicious code will run in the browser when someone loads data about me from your server. And because the browser thinks the script comes from you, it will give the script access to the user's cookies, javascript global variables, etc; so I could possibly use it to do something very bad. Demonstrating this in jsfiddle is tricky though, since it doesn't seem to like <script> tags in the javascript; but "field1": "<scr" + "ipt>alert('malicious code!');</scr" + "ipt>" will do it. Even if you trust the source of the data, or if it's filtered in some way so it can't possibly have <script> tags, you should still get into the habit of preventing this. On a less serious note, the display may be garbled if someone tries to use characters such as < or & in these fields. Basically you want to write $("#Tbody1Id").append('<tr><td id= "cellId"><a id='+curId+ ' class="achor" href='+""+ '>' + key + '</a></td><td>' + escape(value.field1)+ '<br>' + escape(value.field2) + '</td><td>' + escape(value.field3) + '</td><td>' + escape(value.field3) + '</td><td>' + '</tr>') ;, where escape is a function that converts <script>alert('malicious code!');</script> to &lt;script&gt;alert('malicious code!');&lt;/script&gt;, which will display the username correctly. I don't know of any such function in raw javascript or jQuery, but a bit of searching on stackoverflow should find an answer.
David Knipe
  • 3,417
  • 1
  • 19
  • 19
  • Thanks a lot for taking the pain to read the entire code and for your patience to reply with such elaborate details. I'll correct all those points you've mentioned. I've just started learning jQuery and have never used a fiddle. Can you tell me how to see the error messages in console ? – kkk Aug 16 '14 at 19:46
  • The console isn't a jQuery or jsfiddle thing; it's always available in a browser, along with a lot of other useful debugging tools. In Firefox the package is an add-on called Firebug; in Internet Explorer I think it's called Developer Tools. You might be able to access it by pressing F12. Those error messages will be under a tab called Console or something. Also, as MelanciaUK pointed out, if you write `console.log('my message');`, the message `my message` will appear here. – David Knipe Aug 16 '14 at 21:17
0

Thanks all for your valuable time. My first problem is solved. I'm now getting the value associated with each anchor tag. The problem was very simple I was assigning my 'inkey' variable as

    ('#container1 a').html() instead $(this).html() 

was sufficient! Again my div element is not populated with the values associated with my key but for that I guess I've to trigger another ajax call.

kkk
  • 166
  • 2
  • 18