c# - Moving javascript from view to javascript file -
i have several views contain same javascript.
<script type="text/javascript"> $(function () { $("#addanother").click(function () { $.get('/questiongroup/questionentryrow', function (template) { $("#questioneditor").append(template); }); }); }); </script>
i decided move logic javascript file. here did.
on view added data-attr.
<a method="get" action="@url.action("questionentryrow", "questiongroup")" href="#">add another</a>
in javascript file added following code.
var insertrow = function () { var $a = $(this); var options = { url: $a.attr("action"), type: $a.attr("method") }; $.ajax(options).done(function (data) { var $target = $($a.attr("data-cban-target")); $target.append(data); }); return false }; $("a[data-cban-a]").click(insertrow);
when user click link "add another". javascript not getting executed.
target
<ul data-cureurban-target="questioneditor" style="list-style-type: none"> </ul>
here controller logic
public actionresult questionentryrow() { viewbag.questionid = new selectlist(db.questions, "questionid", "questiondesc"); return partialview("_questionentryeditor"); }
try following .js file:
var insertrow = function () { var $a = $(this); var options = { url: $a.attr("action"), type: $a.attr("method") }; $.ajax(options).done(function (data) { var $target = $($a.attr("data-cban-target")); $target.append(data); }); return false }; $(document).ready(){ $("a[data-cban-a]").click(insertrow); }