Replacing image dynamically using jQuery - javascript

I'm trying implement a like button that changes color when clicked. I am trying to replace the image dynamically using jQuery.
<div class = "col-sm-10" style = "margin-top: 2%">
<input style = "width : 4%; height: 4%" type = "image" id = {{schedule.id}} + "image" class = "likes"
data-scheduleid = "{{schedule.id}}" data-user = "{{curruser.person.id}}"
src = "{% static 'img/notliked2.png' %}"/>
</div>
This is image file that gets pressed as a button. Essentially, I am trying to change the image file on click.
$(document).ready(function() {
$('.likes').click(function(e){
var sched_id;
var curruser;
sched_id = $(this).attr("data-scheduleid");
curruser_id = $(this).attr("data-user");
$.get('/profiles/like_schedule/', {schedule_id: sched_id, current_user: curruser_id}, function(data){
var first = data.split("/")
$('#' + sched_id).html(first[0]);
console.log(first[1])
//$('#likes').html("<input style = 'width : 4%; height: 4%' type = 'image' id = {{schedule.id}} class = 'likes' data-scheduleid = '{{schedule.id}}' data-user = '{{curruser.person.id}}' src = {% static 'img/" + first[1] + "' %}/>");
$('.' + sched_id + "image").attr("src", "{% static 'img/" + first[1] + "' %}")
e.preventDefault();
});
});
});
This is the jQuery. I logged first[1], and it is correct. It alternates between "notliked2.png" and "liked2.png" when someone likes and unlikes. But for some reason replacing the image source doesn't work. I even tried replacing the entire html, and it still doesn't work. Does someone know what is going on?
Thank you,
Albert Jin
edit:
Here is the views code.
def like_schedule(request):
sched_id = None
if request.method == 'GET':
sched_id = request.GET['schedule_id']
curruser_id = request.GET['current_user']
likes = 0
liked = "liked2.png"
if sched_id:
sched = schedules.objects.get(id = int(sched_id))
curruser = person.objects.get(id = int(curruser_id))
if curruser in sched.person_likes.all():
liked = "notliked2.png"
sched.likes -= 1
sched.person_likes.remove(curruser)
else:
sched.likes += 1
sched.person_likes.add(curruser)
likes = sched.likes
sched.save()
return HttpResponse(str(likes) + "/" + str(liked))
As for the repeat posts, I did try those but they do not work.

You are using django sytax in your javascript code. You cant use the static function like this:
$('.' + sched_id + "image").attr("src", "{% static 'img/" + first[1] + "' %}")
I would replace the current url and only replace the dynamic part of the url, like so:
var src = $('.' + sched_id + "image").attr("src");
$('.' + sched_id + "image").attr("src", src.slice(0, src.indexOf('img/')) + 'img/" + first[1]);

Not sure of how is the format of the $.get response (you don't show it in the question), but looking at your code this should be enough...
$(document).ready(function() {
$('.likes').click(function(e) {
e.preventDefault();
var $img = $(this);
$.get('/profiles/like_schedule/',{ schedule_id: $img.data("scheduleid"), current_user: $img.data("user") }, function(data) {
$img.attr('src','img/' + data.split("/")[1])
});
});
});
One posible problem is that you're having a caching problem, so your get call is not being executed. If that's your case, you can force your server to execute that call just adding some extra inconstant parameter...
$.get('/profiles/like_schedule/',{ dummy: (new Date()).getTime(), schedule_id: $img.data("scheduleid"), current_user: $img.data("user") }, function(data) {
$img.attr('src','img/' + data.split("/")[1])
});
NOTE: When you want to get the value of a data-whatever attribute in jquery, you have the .data('whatever') function (is designed for that).

Related

How to concatenate and pass parameters values in html using jQuery

I'm using jQuery to get values from ajax rest call, I'm trying to concatenate these values into an 'a' tag in order to create a pagination section for my results (picture attached).
I'm sending the HTML (divHTMLPages) but the result is not well-formed and not working, I've tried with double quotes and single but still not well-formed. So, I wonder if this is a good approach to accomplish what I need to create the pagination. The 'a' tag is going to trigger the onclick event with four parameters (query for rest call, department, row limit and the start row for display)
if (_startRow == 0) {
console.log("First page");
var currentPage = 1;
// Set Next Page
var nextPage = 2;
var startRowNextPage = _startRow + _rowLimit + 1;
var query = $('#queryU').val();
// page Link
divHTMLPages = "<strong>1</strong> ";
divHTMLPages += "<a href='#' onclick='getRESTResults(" + query + "', '" + _reg + "', " + _rowLimit + ", " + _startRow + ")>" + nextPage + "</a> ";
console.log("Next page: " + nextPage);
}
Thanks in advance for any help on this.
Pagination
Rather than trying to type out how the function should be called in an HTML string, it would be much more elegant to attach an event listener to the element in question. For example, assuming the parent element you're inserting elements into is called parent, you could do something like this:
const a = document.createElement('a');
a.href = '#';
a.textContent = nextPage;
a.onclick = () => getRESTResults(query, _reg, _rowLimit, _startRow);
parent.appendChild(a);
Once an event listener is attached, like with the onclick above, make sure not to change the innerHTML of the container (like with innerHTML += <something>), because that will corrupt any existing listeners inside the container - instead, append elements explicitly with methods like createElement and appendChild, as shown above, or use insertAdjacentHTML (which does not re-parse the whole container's contents).
$(function()
{
var query=10;
var _reg="12";
var _rowLimit="test";
var _startRow="aa";
var nextPage="testhref";
//before divHTMLPages+=,must be define divHTMLPages value
var divHTMLPages = "<a href='#' onclick=getRESTResults('"+query + "','" + _reg + "','" + _rowLimit + "','" + _startRow + "')>" + nextPage + "</a>";
///or use es6 `` Template literals
var divHTMLPages1 = `` + nextPage + ``;
$("#test").append("<div>"+divHTMLPages+"</div>");
$("#test").append("<div>"+divHTMLPages1+"</div>");
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="test"></div>

Umbraco Razor - Pass Array to Javascript

I have a foreach loop in Razor which takes images from the Multiple Media Picker in Umbraco. The Response.Write just allows me to see that the images are displaying fine (which they are) so you can ignore this bit.
My question is, how do I populate the image tag with the image URL using the Javascript function? (see below which currently doesn't work).
Razor View/CSHTML
var imagesList = portfolioItem.GetPropertyValue<string>("Images").Split(new string[] { "," }, StringSplitOptions.RemoveEmptyEntries);
var imagesCollection = Umbraco.TypedMedia(imagesList);
foreach (var imageItem in imagesCollection)
{
Response.Write("<img src='"+ #imageItem.Url +"' />");
}
Javascript
openInfoWindow = function (name, imagesCollection, location, mw, url, marker) {
var infoText = "<img src='" + imagesCollection + "' alt='" + imagesCollection + "'title='" + imagesCollection + "' />";
}
try using jquery, if u use razor to set the url as an invisible input value. Then use jquery to pull that value out and add it to the img tag itself by using the following:
var inputVal = $("input").val();
$("#my_image").attr("src",inputVal );
if you put the invisble input value as a variable you can set the img atr ursing jquery like I've shown above.

javascript change anchor tag title value from PHP Echo

I have a class assigned to an anchor tag called status_button. On click of the image associated with the anchor tag it runs the attached function. Two variables are passed to a php script and a 3 piece data response is echo'ed back separated by semicolon's. I have set up alerts to ensure the correct data is coming back from php.
The thing I need help with is how to change the anchor tag title value using the echo'ed response. There are 5 examples out of probably 20 that I have tried. None of them work, but I get no error's either. Any help would be greatly appreciated.
$(".status_button").on('click', function () {
var element = $(this);
var I = element.attr("id");
var id = $("#id" + I).val();
var sname = $(this).attr("title");
$.post("openclose.php", {
id: id,
sname: sname
},
function (data) {
var response = (data).split(";", 3);
alert(response[0]);
alert(response[1]);
alert(response[2]);
$("#messageA" + I).innerhtml = (response[0]);
$("#messageA" + I).hide();
$("#messageA" + I).fadeIn(1500);
$("#messageB" + I).html(response[1]);
$("#messageB" + I).hide();
$("#messageB" + I).fadeIn(1500);
***$(this).attr("title",(response[2]));
***$(I).attr("title", (response[2]));
***$("#id" + I).attr("title" , (response[2]));
***document.getElementById(I).title = (response[2]);
***document.getElementById("#id" +I).setAttribute("title",(response[2]));
});
return false;
});
This will work:
$("#1").attr("title", (response[2]));
Your attempts:
***$(this).attr("title",(response[2])); //this is no longer referring to the clicked element when inside the callback
***$(I).attr("title", (response[2])); //Missing # for ID
***$("#id" + I).attr("title" , (response[2])); //Not your element ID
***document.getElementById("#id" +I).setAttribute("title",(response[2])); //Not your ID
Well.... I had to change a few things around to get this to work the way I needed it to. First off I removed the title from my anchor tag and placed it in my div tag. I then reduced my response from my php file from 3 down to 2 pieces of data.
$(".status_button").on('click', function () {
var element = $(this);
var I = element.attr("id");
var id = $("#id" + I).val();
var xname = $("#messageA" + I).attr('title');
$.post("openclose.php", {
id: id,
xname: xname
},
function (data) {
var response = (data).split(";", 2);
$("#messageA" + I).attr('title', (response[0]));
$("#messageB" + I).html(response[1]);
$("#messageB" + I).hide();
$("#messageB" + I).fadeIn(1500);
});
return false;
});

Passing a value from html to javascript function on click?

Basically, on clicking any image on a html page I want the id associated to be passed to a function.
This is what I have tried. It seems I am making a minor mistake here as I am getting the first id passed no matter what image I click from the array. I tried $(this).attr("id") as well, but did not work.
for(var i=0;i<jsonObj.length-1;i++){
var rows = '';
var bg_img = jsonObj[i].img;
var bg_img = decodeURIComponent(bg_img);
rows = "<img id='" + jsonObj[i].source_id + "' src='" + bg_img + "'/>";
document.getElementsByClassName('subscription')[i].innerHTML = rows;
}
$("body").delegate(".subscription", "click", function() {
// var id = $(this).attr("id");
alert("Welcome Test " + $('img').attr("id"));
return false;
});
$("img").click(function()
{
var id = $(this).attr("id");
});
Your $('img') selector is not confined to any specific area, so it will give you the first image on the entire page.
Try $('img',this) instead.

How to access a parameter from second page?

I have a page that lists courses. When a student clicks on one of the course titles, it will use AJAX to pass the parameter (courseId) to a second page which will return the course details. How can the parameter (courseId) be accessed in the second page? If I put a value directly in the source instead of accessing the parameter, it shows the details:
var idInput = 12345;
var regNoInput = 098766;
When I tried getElementById to access the parameter, it didn't show any details:
var idInput = document.getElementById("courseId").value;
var regNoInput = document.getElementById("regNo").value;
I also tried accessing the parameter as a PHP variable, but still no details:
var idInput = "${courseId}";
var regNoInput = "${regNo}";
this is my first page script, the parameter is pass using url:
success: function(json_results){
$('#list').append('<ul data-role="listview" data-inset="true"</ul>');
listItems = $('#list').find('ul');
$.each(json_results.rows, function(key) {
html = "<li data-mini='true' id='icon'><a href='MRegisteredClassesDetail.html?
courseId=" + [json_results.rows[key].courseId] + "&regNo=" +
[json_results.rows[key].regNo] +"' rel='external'>" +
json_results.rows[key].courseName+ "</a>" + "<a
href='http://137.57.102.146:8080/Training/MRateCourse.phone?courseId="+
[json_results.rows[key].courseId] + "&regNo=" +
[json_results.rows[key].regNo] + "' rel='external'>RATE THIS COURSE</a>
</li>" ;
listItems.append(html);
});
and this is my second page, it should read the parameter value:
var idInput = "${courseId}";
var regNoInput = "${regNo}";
success: function(json_results){
$('#list').append('<ul data-role="listview" data-inset="true"</ul>');
listItems = $('#list').find('ul');
$.each(json_results.rows, function(courseId) {
html ='<h1 align=center>'+json_results.rows[courseId].courseName+'</h1>';
html +='<li>Registration Number:'+json_results.rows[courseId].regNo+'</li>';
html +='<li>Registration Date:'+json_results.rows[courseId].regDate+'</li>';
listItems.append(html);
});
if the parameter in the url,try this:
var params=window.location.search.substr(1).split("&"),
idInput=params[0].split("=")[1],
regNoInput=params[1].split("=")[1];
i declare a variable
var idInput = getParameterByName('courseId');
and define the function
function getParameterByName(name) {
var match = RegExp('[?&]' + name + '=([^&]*)').exec(window.location.search);
return match && decodeURIComponent(match[1].replace(/\+/g, ' '));
}
it works well.

Categories