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.
Related
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>
Hello I have function which take text with my own tag and convert this tag to a:
//<link src="" title=""> -> title
function ProceedLinkTag(text) {
var items = text.filter("link");
items.each(function () {
var currentElement = $(this);
var title = currentElement.attr("title");
var source = currentElement.attr("src");
var newElement = $("<a>" + title +"</a>");
newElement.attr("href", source);
$(this).replaceWith("<a href='" + source + "'>" + title + "</a>"); //don't work
});
}
It work fine(it is detect my own tag even without close tag), I don't get any errors, but it is don't replaceWith().
Try it:
var text = "<link src='http://lenta.ru/' title='title'>";
ProceedLinkTag($(text));
alert(text);
I also try use it with close tag:
var text = "<link src='http://lenta.ru/' title='title'/>";
ProceedLinkTag($(text));
alert(text);
But it don't work too.
#sqykly find error:
Text in my instance was not a part of document. I change it and now it work.
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;
});
$("#jqxTree-ReportGroups ul").append("<li id=" + [data[i].Id] + " item-checked='true' item-expanded='true' class='treeLi'>
<a class='report-tree-expand' href=''>+</a>
<a class='reportData' id='12345' href=''>" + [data[i].Name] + "</a></li>");
How to get the attribute value of "id" by class name "reportData" when its clicked?
EDIT:
click doesnt work.. If i use Live that function is getting called... How to do get the reportData's Id inside a live function
Take a look at this Code:
$(document).on('click' , '.reportData' , function(){
var idProp= $(this).prop('id'); // or attr()
var idAttr = $(this).attr('id');
console.log('using prop = ' + idProp + ' , using attr = ' + idAttr);
console.log();
return false; // to prevent the default action of the link also prevents bubbling
});
done use live it has been deprecated (on requires jquery version 1.7 and above)
but here is the code using live()
$('.reportData').live('click' , function(){
var idProp= $(this).prop('id'); // or attr()
var idAttr = $(this).attr('id');
console.log('using prop = ' + idProp + ' , using attr = ' + idAttr);
console.log();
return false; // to prevent the default action of the link also prevents bubbling
});
jsfiddle to prove working
http://jsfiddle.net/uvgW4/1/
You can do
$(document).on("click", ".reportDatan", function() {
var id = this.id;
});
Use event delegation since it looks like your adding this dynamically.
Try this:
$('.reportDatan').click(function(){
$(this).attr('id');
});
if you are using jquery 1.9
$('.reportDatan').click(function(){
$(this).prop('id');
});
Your concatenation of HTML String inside jQuery is wrong, take a look at this Code which has live function or if you want this to be readable, you can use JavaScript Template Engine Mustache also
HTML:
<div id="jqxTree-ReportGroups">
<ul>
<li>First</li>
</ul>
</div>
jQuery:
$(document).ready(function () {
var yourLiID = 100;
var aValue = 'Report Data';
var yourLi = "<li id='" + yourLiID + "' item-checked='true' item-expanded='true' class='treeLi'>";
var yourAnchor = "<a class='report-tree-expand' href=''>Your Text</a> ";
var secondAnchor = "<a class='reportData' id='12345' href=''>" + aValue + "</a>";
var yourLiClose = '</li>';
$("#jqxTree-ReportGroups ul").append(yourLi + yourAnchor + secondAnchor + yourLiClose);
$('.reportData').live("click", function(){
var yourAnchorID = $(this).attr('id');
alert('yourAnchorID: ' + yourAnchorID);
return false;
});
});
Refer this jsFiddle Link for demo
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] + "®No=" +
[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] + "®No=" +
[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.