Take the 2-minute tour ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

I have the following html table which contains two buttons. Both buttons are handled by the same click handler.

 <div id="replaceme">

</div>
<table>
    <tr>
        <input name="edit" class="edit button" type="button" value="edit" />
    </tr>
     <tr>
        <input name="edit" class="edit button" type="button" value="edit" />
    </tr>
</table>

When i click one of those buttons, the following javascript gets executed:

$(document).on('click', '.edit', function (event) {
   document.getElementById("replaceme").innerHTML +="textshouldbedynamic <br/>";
});

This works, and the text in 'replaceme' div is replaced properly.

Question: I want do this in a table which is created via asp.net mvc while iterating on a list which is part of my model. I now like to put parts of my model into the javascript function. pseudo code:

<tr>
    <input name="edit" class="edit button" type="button" value="edit" data="foo"/>
</tr>
 <tr>
    <input name="edit" class="edit button" type="button" value="edit" data="bar"/>
</tr>

How can i get such data dynamically into a javascript function?

edit: Is it a correct solution to add a json string, and parse it in the javascript function?

<div id="replaceme">

</div>
<table>
    <tr>
        <input name="edit" class="edit button" type="button" value="edit" id='{"FirstValue":11,"SecondValue":42}' />
    </tr>
     <tr>
        <input name="edit" class="edit button" type="button" value="edit" id='{"FirstValue":22,"SecondValue":33}'/>
    </tr>
</table>



 $(document).on('click', '.edit', function (event) {
       document.getElementById("replaceme").innerHTML +="textshouldbedynamic <br/>";

        var obj = jQuery.parseJSON( this.id );

        document.getElementById("replaceme").innerHTML += obj.FirstValue + " " + obj.SecondValue + "<br/>";
    });

jsfiddle sample

share|improve this question

2 Answers 2

Have you thought about template binding with a client side framework like KnockoutJs?

share|improve this answer
    
I'm new to javascript, and like to learn it without frameworks at the moment. –  Manuel Mar 14 at 23:57

on asp.net mvc the code rendered on server side and js is a client side languge you can not make the javascript to run on server . however you can make a call for javascript to run on client side on ready state. let say you want to run:

function foo(data){
//Do somthing
}

so you can bind to onready event this call :

$(document).ready(function(){
   $('.edit button').each(function(){
      val data = $(this).attr('data');
      foo(data);
   });
});

is that what you needed?

share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.