Dynamic content data id not working in jquery - javascript

Have a dynamic html div
<a data-id="17" onclick="getcustomer();">
<div class="note note-success">
<h4 class="block">A</h4>
<p>Email : a#gmail.com</p>
<p>Mobile : 8</p>
<p>DOB : 0000-00-00</p>
</div>
</a>
On the above anchor's on click.it calls this function
function getcustomer(){
var id = $(this).data('id');
alert (id);
$.post(base_url+'who/customer', {
customer_id: id
}, function(data, status){
console.log(data);
});
}
But alert receiving is undefined.
How will I take data-id value?
This is dynamic field. This a's are added after dom load.

this does not refer to the element but to window
Pass this as argument for getcustomer function
function getcustomer(elem) {
var id = $(elem).data('id');
alert(id);
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<a data-id="17" onclick="getcustomer(this);">
<div class="note note-success">
<h4 class="block">A</h4>
<p>Email : a#gmail.com</p>
<p>Mobile : 8</p>
<p>DOB : 0000-00-00</p>
</div>
</a>
Or better use jQuery event binding using .on method
$('.eventBinding').on('click', function() {
var id = $(this).data('id');
alert(id);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<a data-id="17" class='eventBinding'>
<div class="note note-success">
<h4 class="block">A</h4>
<p>Email : a#gmail.com</p>
<p>Mobile : 8</p>
<p>DOB : 0000-00-00</p>
</div>
</a>

Pass the object to the method,
<a data-id="17" onclick="getcustomer(this);">
Then the code will be,
function getcustomer(obj) {
var id = $(obj).data('id');
alert(id);
$.post(base_url + 'who/customer', {
customer_id: id
},
function(data, status) {
console.log(data);
});
}

Try this:
<a data-id="17" onclick="getcustomer(this);">
function getcustomer(curr_obj){
var id = $(curr_obj).data('id');
alert (id);
$.post(base_url+'who/customer',
{
customer_id: id
},
function(data, status){
console.log(data);
});
}

What if you use $(this).attr('data-id');

Try this as well, if it works. Its just simple one line of code.
$('a').on('click', function(){
var id = $(this).attr("data-id");
alert(id);
});
Or you can try this as well, according to your code,
function getcustomer(){
var id = $(this).attr('data-id');
alert (id);
$.post(base_url+'who/customer',
{
customer_id: id
},
function(data, status){
console.log(data);
});
}

Use this script
function getcustomer(){
var id = $(this).attr('data-id');
alert (id);
$.post(base_url+'who/customer',
{
customer_id: id
},
function(data, status){
console.log(data);
});
}

Related

jQuery nth-child only selecting first element

I am trying to add a on click function on the specific child of .article which will show certain wikipedia link base on the pageid received from the request. But all the .article are pointing to the same page.
HTML:
<section id="body-article">
<div id="body-container">
</div>
</section>
JavaScript(jQuery):
function SendRequest(searchEntry){
$.ajax({
url: `https://en.wikipedia.org/w/api.php?action=query&list=search&format=json&srsearch=${searchEntry}`,
type: 'GET',
dataType: 'jsonp',
headers: {'Api-User-Agent': 'WikiReader/0.1.0'}
}).done(function(data, status) {
console.log(data);
GenerateArticle(data);
}).fail(function(data, status) {
console.log("ERROR! " + status);
});
}
function GenerateArticle(data){
//shows all the article in a div
var totalArticleLength = data.query.search.length;
for(var i=0;i<totalArticleLength;i++){
var title= data.query.search[i].title;
var pageid=data.query.search[i].pageid;
var snippet=data.query.search[i].snippet;
//responsible for showing single data
CreateSingleArticle(title,pageid,snippet);
// PROBLEM IS WITH THE BELOW LINE
$(`.article:nth-child(${i+1})`).on("click",function(){
window.open(`https://en.wikipedia.org/?curid=${pageid}`, 'Wikipedia', 'window settings');
})
}
}
function CreateSingleArticle(title,pageid,snippet){
//creates a individual data
html =
`<div class="article">
<div class="side-bar"></div>
<div class="article-container">
<div class="article-header">
${title}
</div>
<div class="snippet">
${snippet}
</div>
</div>
</div>`
$("#body-container").append(html);
}
Answer is quite simple. You ran into javascript scope problem. Have a look at the immediate function call. Read more here. http://tobyho.com/2011/11/02/callbacks-in-loops/
for(var i=0;i<totalArticleLength;i++){
(function(index, pageId){
var title= data.query.search[index].title;
var pageid=data.query.search[index].pageid;
var snippet=data.query.search[index].snippet;
//responsible for showing single data
CreateSingleArticle(title,pageid,snippet);
// PROBLEM IS WITH THE BELOW LINE
$(`.article:nth-child(${index+1})`).on("click",function(){
window.open(`https://en.wikipedia.org/?curid=${pageId}`, 'Wikipedia', 'window settings');
})
})(i, data.query.search[i].pageid)
}

Wikipedia API sandbox, search by user's input

Trying to search in Wikipedia by user's input but it doesn't work for some reason. First I thought it could be due to cross domain problem. But .ajax should help with that.
Here is codepen: http://codepen.io/ekilja01/pen/pRerpb
Here is my HTML:
<script src="https://use.fontawesome.com/43f8201759.js">
</script>
<body>
<h2 class="headertext">WIKIPEDIA <br> VIEWER </h2>
<div class="row">
<div class="col-10-md">
<input class="searchRequest blink_me" id="cursor" type="text" placeholder="__"></input>
</div>
<div class="searchIcon col-2-md"> </div>
</div>
<div>
<p class=results></p>
</div>
</body>
Here is my jQuery:
$(document).ready(function() {
var icon = "<i class='fa fa-search fa-2x'></i>";
$('#cursor').on("keydown", function() {
$(this).removeClass("blink_me");
var searchIcon = $(".searchIcon");
searchIcon.empty();
if ($(".searchRequest").val().length > 0) {
searchIcon.append(icon);
}
searchIcon.on("click", function() {
console.log("clicked!");
var search = $(".searchRequest").val();
var url = "https://en.wikipedia.org/w/api.php?action=opensearch&format=json&search=" + search + "&format=json&callback=?";
$.ajax({
dataType: "jsonp",
url: url,
success: function(data) {
$(".results").html(data[0]);
console.log(data[0]);
}
});
});
});
});
What am doing wrong? Please help.
There's an error in the order of load for your js.
The data object contains the text of the results in the array with index 2, which i assume is what you want to show, change it to
$(".results").html(data[2]);
You can check a modified version of your original code here
http://codepen.io/anon/pen/mRmGXG

bind multiple id using on()

<a id="abc">First</a>
<a id="xyz">Second</a>
$('body').on('click','#a,#b',function(){
btn = $(this).attr('id');
if(btn == "abc"){ //do something };
});
Why my above code worked when I click abc id but not the later button? Did I bind it wrongly?
Your selectors are not correct and do not match your IDs:
$('body').on('click','#abc,#xyz',function(){
var btn = $(this).attr('id');
alert(btn);
if(btn === "abc") {
// Do something
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<a id="abc">First</a>
<a id="xyz">Second</a>

Jquery ajax change class clicked by data-id

i have one question about jquery on click.
This is DEMO from jsfiddle.net
When you click the demo you can see there is a green and yellwo div.
The question is when you click the data-id="1" and change this div class:
<div class="icon-kr icon-globe"></div>
change icon-globe to icon-contacs
and when you click data-id="2" then change:
change icon-globe to icon-lock-1
also same think is for data-id="0"
How can i do that anyone can help me in this regard ?
HTML
<div class="container" id="1">
<div class="icon_ar"><div class="icon-kr icon-globe"></div>1</div>
<div class="pr_type">
<div class="type_s change_pri" data-id="0"><div class="icon-pr icon-globe"></div>1</div>
<div class="type_s change_pri" data-id="1"><div class="icon-pr icon-contacs"></div>2</div>
<div class="type_s change_pri" data-id="2"><div class="icon-pr icon-lock-1"></div>3</div>
</div>
</div>
JS
$('.change_pri').click(function(){
var dataid = $(this).attr('data-id');
var id = $(this).closest('.container').attr('id');
$.ajax({
type: "POST",
url: "chage_number.php",
data: { dataid : dataid, id: id }
}).success(function(result){
alert(result);
});
});
One way to do this is below. I have only done the class changing bit based on click. I am not sure about your ajax code. Let me know if you need further help.
$('.change_pri').click(function(){
var class_name = $(this).find(".icon-pr").attr("class");
class_name = class_name.replace(/icon\-pr\s+/gi, "");
$(this).closest(".container").find(".icon-kr")
.removeClass().addClass("icon-kr " + class_name);
});
Updated fiddle
You need to use .data(), you are not accessing the data correctly.
https://api.jquery.com/jquery.data/
var dataid = $(this).data('id');
You are accessing this data-* attribute incorrectly,
Use this,
$('.change_pri').click(function(){
var dataid = $(this).data('id');
$(this).parent().siblings('.icon_ar').find('div').removeClass("icon-globe icon-contacs icon-lock-1");
if(dataid=="0")
{
$(this).parent().siblings('.icon_ar').find('div').addClass("icon-globe");
}
else if(dataid==1)
{
$(this).parent().siblings('.icon_ar').find('div').addClass("icon-contacs");
}
else
{
$(this).parent().siblings('.icon_ar').find('div').addClass("icon-lock-1");
}
//AJAX CODE.
});

How to get the clicked element's ID

I want to retrieve the ID of the clicked element (on the 'onclick; event.
<script>
function myFunction(element)
{
var $id = element.id;
$($id).click(function() {
$.get('ajaxTestSrvlt?test=1', function(responseText) {
$('#firstName').val(responseText); with the response text.
});
});
};
</script>
This is the element this function was called upon. I would like to get the ID of this raw from the above script. This only works when I directly give the "clickableRow" as to id to the Script. The "ID" is to be changed dynamically
<tr id="clickableRow" style="cursor: pointer;" class='clickable-row' data-href="#" data-toggle="modal" data-target="#editModal" onclick="myFunction(this)">
There is no need to have a inline event handler
<tr id="clickableRow" style="cursor: pointer;" class='clickable-row' data-href="#" data-toggle="modal" data-target="#editModal">
then
jQuery(function () {
$('.clickable-row').click(function () {
var $this = $(this),
id = this.id;
$.get('ajaxTestSrvlt?test=1', function (responseText) {
$('#firstName').val(responseText);
//here `id` is the id of the clicked tr
});
});
})
Try this
function myFunction(ele)
{
var id=$(ele).attr("id");
$('#'+id).click(function() {
//code here
});
}
Simply use this
onclick="myFunction(this.id)
Instead of
onclick="myFunction(this)
Get your id on my function
function myFunction(getid) {
alert(getid);
}

Categories