Moving javascript from view to javascript file - javascript

I have several views that contain this same javascript.
<script type="text/javascript">
$(function () {
$("#addAnother").click(function () {
$.get('/QuestionGroup/QuestionEntryRow', function (template) {
$("#questionEditor").append(template);
});
});
});
</script>
I decided to move this logic to a javascript file. So here what I did.
On my view I added a data-attr.
<a method="get" action="#Url.Action("QuestionEntryRow", "QuestionGroup")" href="#">Add another</a>
In the javascript file I added the 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 the user click the link "Add another". The javascript is not getting executed.
Target
<ul data-cureurban-target="questionEditor" style="list-style-type: none">
</ul>
Here the controller logic
public ActionResult QuestionEntryRow()
{
ViewBag.QuestionID = new SelectList(db.Questions, "QuestionID", "QuestionDesc");
return PartialView("_QuestionEntryEditor");
}

Try the following for your .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);
}

Try adding javascript:void(0) in href of anchor tag.
<a method="get" action="#Url.Action("QuestionEntryRow", "QuestionGroup")" href="javascript:void(0)">Add another</a>
Refer this stackoverflow post for more details

Default event propogation for (a)anchor tag needs to be stopped.
<script type="text/javascript">
$(function () {
$("#addAnother").click(function (e) {
e.preventDefault();
$.get('/QuestionGroup/QuestionEntryRow', function (template) {
$("#questionEditor").append(template);
});
});
});
</script>

Related

jquery=>Sending data

Iam working on adding an event planner to my Html form ,
and i cant figure out how to pass this data ("meetup","startEvent","break") from html to my Database .
ive used jQuery to show the data on my browser console like this and it work
$(document).ready(function(){
$('#bang').on("click", function(){
$("#editable > li").each(function(){
$e=($(this).text());
console.log($e);
but i cant get it to send to another page
$(document).ready(function(){
$('#bang').on("click", function(){
$("#editable > li").each(function(){
$e=($(this).text());
console.log($e);
$("#submit").click(function(){
$.ajax(
{
url: "test.php",
type: "POST",
data: {$e},
success: function (result) {
alert('success');
jQuery('#bang').on("click", function () {
var data = [];
jQuery("#editable > li").each(function () {
data.push(jQuery(this).text());
});
console.log(data);
jQuery.post('test.php', data).done(function () {
console.log('Done!');
}).fail(function () {
console.log('Nopo!');
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<ul id="editable">
<li>test</li>
<li>me</li>
<li>out</li>
</ul>
<button id="bang">bang!</button>

Increasing the amount of likes displayed (custom ones,not facebook)

I would like to display total amount of likes on page, the likes are displayed in:
<input type="tekst" id="<?php echo $item->getId();?>">
add like function button:
$(function () {
$('a.like').on('click', function () {
var url = $(this).attr('href');
$.post(url, {}, function () {
});
return false;
});
});
So not I have to click on $('a.like') and then refresh page to see the like added, I would like to skip refreshing the page. Any ideas?
EDIT there is also a script:
<script>
document.getElementById("<?php echo $item->getId();?>").value =<?php echo getVotesValue($item->getId());?>
</script>
If I understand correctly, you need to replace your code by this:
var likesCounter = $('#<?php echo $item->getId();?>');
$(function () {
$('a.like').on('click', function () {
var url = $(this).attr('href');
$.post(url, {}, function () {
likesCounter.val(parseInt(likesCounter.val()) + 1);
});
return false;
});
});

preventDefault is not working

I am trying to send an ajax request to complete a task when a link is clicked. For some reason the e.preventDefault is not working and I still get sent to the page. Is there something I am missing?
It is simply supposed to go to the page set the check-box to checked (or unchecked) then redirect. But again it just goes to the page. Any help would be great!
here is the main.js
$(function() {
$('.ajax-task-complete').on({
click: function(e) {
e.stopPropagation();
e.preventDefault();
var href = $(this).attr('href');
$('<div></div>').load(href+' form', function() {
// Set Form
var form = $(this).children('form');
// Set Checkbox
var cb = form.find('input[type="checkbox"]');
// Taggle Checkbox
cb.prop('checked', !cb.prop('checked'));
// Form Action URL
var url = form.attr('action');
// Set Data
var data = form.serialize();
$.ajax({
url: url,
data: data,
method: 'post',
dataType: 'json',
cache: false,
success: function(obj) {
var tic = $('#task-complete-' + obj.id + ' .ajax-task-complete');
},
complete: function() {
console.log('complete');
},
error: function(err) {
console.log(err);
}
});
});
}
});
});
here is the requested button
<td id="task-complete-{{ entity.id }}">
{% if entity.completed %}
<a class="check ajax-task-complete" href="{{ path('task_edit_complete', { 'id': entity.id }) }}">✔</a>
{% else %}
<a class="uncheck ajax-task-complete" href="{{ path('task_edit_complete', { 'id': entity.id }) }}">✔</a>
{% endif %}
</td>
This is your problem:
Uncaught ReferenceError: $ is not defined?
Read HERE from SO how you load your jQuery-plugin the right way.
you might need to stop bubbling depending on where the click event is occurring. Try adding this and see what happens.
e.stopPropagation();
**"$"**
is missing before (function() {
javascript pageload event should be like
$(function(){
//code here
});
or
function will be called by themself
(function(){
//code here
)}();
or
(function($){
//code here
})(jQuery)
You can check the fiddle here
Your scope is wrong, you are missing the () after (function)(). The function is never called :
(function() {
$('.ajax-task-complete').on({
click: function(e) {
e.stopPropagation();
e.preventDefault();
var href = $(this).attr('href');
$('<div></div>').load(href+' form', function() {
// Set Form
var form = $(this).children('form');
// Set Checkbox
var cb = form.find('input[type="checkbox"]');
// Taggle Checkbox
cb.prop('checked', !cb.prop('checked'));
// Form Action URL
var url = form.attr('action');
// Set Data
var data = form.serialize();
$.ajax({
url: url,
data: data,
method: 'post',
dataType: 'json',
cache: false,
success: function(obj) {
var tic = $('#task-complete-' + obj.id + ' .ajax-task-complete');
},
complete: function() {
console.log('complete');
},
error: function(err) {
console.log(err);
}
});
});
}
});
})(); //Add () here
But is the scope really needed here?
Maybe you meant a ready handler, then it should be like this :
$(function); //Missing '$'
Try placing the preventDefault event at the end of the function as below
$('.ajax-task-complete').on({
click: function(e) {
//
//your code here then,
e.preventDefault();
e.stopPropragation();
});
I can't test if it works or not, as I'm on mobile.

Show a loading image is not working well

I have defined the following script as part of implementing paging :-
var getPage = function () {
var $a = $(this);
var options = {
url: $a.attr("href"),
data: $("form").serialize(),
type: "get"
};
$.ajax(options).done(function (data) {
$(".loadingimage").show();
var target = $a.parents("div.pagedList").attr("data-tms-target");
$(target).replaceWith(data);
});
return false;
};
$(document).ready(function () {
$(".main-content").on("click", ".pagedList a", getPage);
})
And part of the mark-up is as follow:-
<div id="AuditTable">
<div class="pagedList" data-tms-target="#AuditTable">
#Html.PagedListPager(Model , page => Url.Action("Index",new { page }),
PagedListRenderOptions.ClassicPlusFirstAndLast)
</div> <img src="~/Content/Ajax-loader-bar.gif" class="loadingimage" id="progress2" />
<table class="table table-striped table-bordered bootstrap-datatable datatable">
<thead><tr>
The paging will work well , but the problem is that the
$(".loadingimage").show();
Will not show the hidden loading image during data retrieval, can anyone advice on this problem ?
Try these
You can load the image in your browser (e.g. http://yourdomain.com/Content/Ajax-loader-bar.gif) If you can, consider writing full url as image src.
Try id as selector (e.g. $("#progress2).show(); )
If those are not leading you to anywhere you can put the image into a div, remove its class (assume that you hide it with css), .show(); and .hide(); within getPage function.
HTML:
<div id="loadcontainer"><img src="Content/Ajax-loader-bar.gif" id="progress2" /></div>
Javascript:
var getPage = function () {
$("#loadcontainer").show();
var $a = $(this);
var options = {
url: $a.attr("href"),
data: $("form").serialize(),
type: "get"
};
$.ajax(options).done(function (data) {
$("#loadcontainer").hide();
var target = $a.parents("div.pagedList").attr("data-tms-target");
$(target).replaceWith(data);
});
return false;
};

append.html jquery is not working the same as the existing html?

i have a situation where im apending html to load more posts(pagination), and each post has a reply link, the appened html is not functioning properly:
the jquery post:
$(function () {
//More Button
$('.more').live("click", function () {
var ID = $(this).attr("id");
if (ID) {
$("#more" + ID).html('<img src="moreajax.gif" />');
$.ajax({
type: "POST",
url: "ajax_more.php",
data: "lastmsg=" + ID,
cache: false,
success: function (html) {
$("ul.statuses").append(html);
$("#more" + ID).remove();
}
});
} else {
$(".morebox").html('The End');
}
return false;
});
});
html file:
return <<<ENDOFRETURN
<li>
<img class="avatar" src="images/$picture" width="48" height="48" alt="avatar" />
<div class="tweetTxt">
<strong>$username</strong> $auto
<div class="date">$rel</div>
<a class ="reply" href="home.php?replyto=#$username&status_id=$id&reply_name=$username"> reply </a>
</div>
<div class="clear"></div>
</li>
ENDOFRETURN;
the reply link jquery:
function insertParamIntoField(anchor, param, field) {
var query = anchor.search.substring(1, anchor.search.length).split('&');
for (var i = 0, kv; i < query.length; i++) {
kv = query[i].split('=', 2);
if (kv[0] == param) {
field.val(kv[1]);
return;
}
}
}
$(function () {
$("a.reply").click(function (e) {
insertParamIntoField(this, "status_id", $("#status_id"));
insertParamIntoField(this, "reply_name", $("#reply_name"));
insertParamIntoField(this, "replyto", $("#inputField"));
$("#inputField").focus()
$("#inputField").val($("#inputField").val() + ' ');
e.preventDefault();
return false; // prevent default action
});
});
I'm taking a shot in the dark but it sounds like you haven't used a .live() event on the reply buttons. Any new buttons being appended to the document will not have the click event that you specified for them attached.
So in short make sure any buttons that are loaded dynamically and need to fire off an event are using a 'live' event binding.
Change your click handler to use .live() like this to make it work on links added later as well.:
$(function () {
$("a.reply").live("click", function (e) {
insertParamIntoField(this, "status_id", $("#status_id"));
insertParamIntoField(this, "reply_name", $("#reply_name"));
insertParamIntoField(this, "replyto", $("#inputField"));
$("#inputField").val(function(i, v) { return v + ' '; }).focus();
return false;
});
});

Categories

Resources