I'd really appreciate any help!
I have a working jquery script. When a div is clicked, it updates the css class to active and executes a working ajax response.
I also have a filter functionality that works too. When a checkbox is ticked it calls a new list of div's from mysql with all the same class properties. However, when any of these new div's are clicked the ajax response doesn't work. If anyone could help I would be incredibly grateful!
HTML:
<div id="result" class="results">
<div class="w-embed"><img src="images/loader.gif" id="loader" width="" "200px"="" style="display:none;">
<?php
$sql="SELECT * FROM `posts`";
$result=$con->query($sql);
while($row=$result->fetch_assoc()){
?>
<div class="c-card" data-id="<?=$row['id'];?>">
<h1 class="s-h2">
<?=$row['title'];?>
</h1>
<!-- <div class="s-para m-light m-small"><?=$row['description'];?></div> -->
<div class="c-stats">
<div class="s-stat">Pay:
<?=$row['pay'];?>
</div>
<div class="s-stat">Deadline:
<?=$row['deadline'];?>
</div>
<div class="s-stat">Location:
<?=$row['location'];?>
</div>
<div class="s-stat">Cat:
<?=$row['category'];?>
</div>
</div>
<p class="s-para">
<?=$row['description'];?>
</p>
Find Out More
</div>
<?php }?>
</div>
</div>
Javascript:
<script>
$('.c-card').on('click', function(event){
event.preventDefault();
$('.c-card').removeClass('active'); //Removes class to all
$(this).toggleClass('active'); //Applies class
var action = 'data';
var dataId = $(this).data("id");
$.ajax({
type:"POST",
url:"ajax/selected.php",
data:{action:action,id:dataId},
success: function(response){
$("#jobber").html(response);
$("#changeme").text("altered");
}
});
});
</script>
This is the outputted response from the filters:
'<div class="c-card" data-id="'.$row['id'].'">
<h1 class="s-h2">'.$row['title'].'</h1>
<div class="c-stats">
<div class="s-stat">Pay:'.$row['pay'].'</div>
<div class="s-stat">Deadline:'.$row['deadline'].'</div>
<div class="s-stat">Location: '.$row['location'].';</div>
<div class="s-stat">Cat: '.$row['category'].'</div>
</div>
<p class="s-para">'.$row['description'].'</p>
Find Out More
</div>';
So my question is how do i make the new divs (called from the filter) to continue to be triggered and change class + execute the ajax query.
Thanks so much in advance!
I have been thought your actual problem was the ajax response is getting null.
<div class="c-card" data-id="<?=$row['id'];?>">
You are using the data-id attribute in the HTML section. But the script handles the id attribute using for getting the id. So the id is getting null for ajax call, Please use the below code or change the data-id attribute to id in the HTML section as you like.
var action = 'data';
var dataId = $(this).data("data-id");
"id" and "data-id" are different attributes for HTML. Please use same attributes in HTML and script
maybe because there is no html(div|| p || span ||...) element that have id of id="jobber"
Related
i have a DOM Element
<div class="list-item">
<div class="name"></div>
<div class="id" data-id=""></div>
Link
</div>
I want to get the HTML like $('.list-item').html();
Then i want to fill parts like data-attributes and content with own variables so i can get for example this:
<div class="list-item">
<div class="name">NAME CONTENT</div>
<div class="id" data-id="123456">CONTENT</div>
Link
</div>
Then i want to store that as string in a varibale like
var htmlCode = '<div class="list-item">.....';
The tricky part here is to do that all in Javascript without changing the DOM Element. I hope for help. Thanks!
You can use .clone() to clone your div and then use .attr() to change attr from id class .
Demo Code :
var htmls = $(".list-item").clone()
$(htmls).find(".id").attr('data-id', 'somehting');
console.log($(htmls).html()) //store in variable..
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="list-item">
<div class="name"></div>
<div class="id" data-id=""></div>
Link
</div>
You can use this
<script>
var html = $('.list-item').html();
console.log(html);
var list = $('<li></li>')
$('.list-item').children().each(function(index,elem){
$(list).append($(elem).clone());
})
$(list).children().each(function(i,e) {
$(e).data("id","1234")
$(e).html("ll");
})
console.log($(list).children());
</script>
Thank you all. With your help i got this solution:
var $temp = $('.list-item').html();
var $code = temp.replace('data-id=""', 'data-id="1234"').replace('href=""', 'href="https://link.de"');
So $code is my varibale wich stores the html as string without changing the DOM Element :)
let say i have this div
<div id='parent'>
<button id='button'></button>
<div id='child'>
<div id='grandchild' class='lookAtMe'>
Some JSON text
</div>
</div>
</div>
I wanted to give the #button an on click event that returned the text at #lookAtMe div, specific to the div whom it shares parent/grandparent (in this case, the #parent div)
I tried using:
$("#button").on("click",function(){
var ReturnedText = $(this).parent(".lookAtMe").text();
console.log(RetrunedText);
});
But the console log would retruned (empty string).
Where did i do wrong? please help. Thankyou very much.
Because there is n o parent with that class. You need find().
Actually you need to write
var ReturnedText = $(this).parent().find(".lookAtMe").text();
$("#button").on("click",function(){
var ReturnedText = $(this).parent().find(".lookAtMe").text();
console.log(ReturnedText);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id='parent'>
<button id='button'></button>
<div id='child'>
<div id='grandchild' class='lookAtMe'>
Some JSON text
</div>
</div>
</div>
I am having an issue with getting the value of an ID element of the item that is dynamically generated from the data obtained from the database. I have a query SELECT ItemID, ItemName, ItemImageName FROM Items. Than I have the following code that will generate ID for each <div> for all rows returned from the database by concatenating the value of ItemID to each ID name.
for ($i=0; $i <$numrows; $i++) {
$stmt->fetch()
<div> <img class="itemImage" id="Image" .$ItemID src=/images/itemImage . $itemID> $ItemID </div>
<div id= "ItemID" .$ItemID> $ItemID </div>
<div id= "ItemName" .$ItemID> $ItemName" </div>
}
This should return a similar result to this for an item with ItemID=002:
<div> <img class="itemImage" id=Image002 src=/images/Image002 > </div>
<div id= ItemID002> 002 </div>
<div id= ItemName002> SomeNameOfItem002" </div>
Then I want to be able to click an image with an ID=Image002 and I want to get a value of ItemID with the getElementById("ItemID").innerHTML. I have the following code:
var itemID = document.getElementById("ItemID").innerHTML;
$( ".itemImage" ).click(function() {
var itemID= document.getElementById("ItemID").innerHTML;
console.log(itemID);
This however returns itemID as undefined. Any help would be greatly appreciated!
<div> <img class="itemImage" id=Image001 src="/images/Image001"> </div>
<div id=ItemID001> 001 </div>
<div id=ItemName001> SomeNameOfItem001" </div>
<div> <img class="itemImage" id=Image002 src="/images/Image002"> </div>
<div id=ItemID002> 002 </div>
<div id=ItemName002> SomeNameOfItem002" </div>
<div> <img class="itemImage" id=Image003 src="/images/Image003"> </div>
<div id=ItemID003> 003 </div>
<div id=ItemName003> SomeNameOfItem003"> </div>
<script>
$(document).ready(function () {
$(".itemImage").click(function () {
var imgID = $(this).prop('id').replace("Image", "");
// you can directly use value imgID variable if its same. or you
//can use from ItemID inner html
var yourValue = $("#ItemID" + imgID).html();
alert(yourValue);
})
});
</script>
getElementById("ItemID").innerHTML returns undefined, because it is undefined. The correct id is ItemID002. You need to be able to tell which it is.
First, change your PHP to create HTML like this.
<div id="ItemID002" onclick="clicked(002)" />
Then, go to your Javascript and create this function.
function clicked(id){
var itemID= document.getElementById("ItemID"+id).innerHTML;
console.log(itemID);
}
Lastly, you're PHP creates <div id="ItemID"002>, you need to fix that by changing it from <div id= "ItemID" .$ItemID> $ItemID to <div id='ItemID.$itemId'>
EDIT: Also, I'd like to point out that in some places in your example, you forgot to use quotes when specifying the value of an attribute in HTML. I would recommend you fix that.
Good luck!
Alternatively you can achieve this by javascript only. So you don't need to change markup or PHP.
Here is a sample fiddle https://jsfiddle.net/L3bwfyve/
The key part is extraction of part of id of clicked element:
var itemIdPart = e.target.id.substr(5);
Be sure to check for nulls in e.target id etc...
Personally I would consider this solution a bit hacky... but you ask for javascrit, you get it ;-)
i am currently trying to create pagination feature. I am using bootstrap for css and jQuery.
There are total of 8 divs that contains a tags.
in my html file, i wrote
<div id="articleArea" class="row">
<div class="col-md-4 postTitle">
post title
</div>
<div class="col-md-4 postTitle">
post title
</div>
<div class="col-md-4 postTitle">
post title
</div>
<div class="col-md-4 postTitle">
post title
</div>
<div class="col-md-4 postTitle">
post title
</div>
<div class="col-md-4 postTitle">
post title
</div>
<div class="col-md-4 postTitle">
post title
</div>
<div class="col-md-4 postTitle">
post title
</div>
</div>
what I want to do is replacing each href in a tags, based on the response from my ajax call. I will just post success part of .ajax since other parts are completely functional and irrelevant to my question. my ajax call is returned in json format and var result is an array that contains 8 different hrefs that need to be assigned to each a tags in postTitle divs.
success: function(data){
var result = data["result"];
for(i=0; i < result.length; i++{
postTitle = result[i];
$(".postTitle.a").html(postTitle);
}
},
If i execute this code, a href are shown briefly but it disappears within a second. How can I fix this? and if there is better way to implement this feature, please do comment! Would love to be hear any feedbacks.
You need to run iteration over a tags instead of running iteration over results
$(".postTitle a").each(function(i) {
postTitle = result[i];
$(this).attr("href",postTitle);
});
This would run over each href tag and replace the values accordingly
EDIT: it should be .postTitle a
Your selector would select all of the elements
$(".postTitle.a")
You should select each tag and set its href, in addition it is missing a space:
$(".postTitle a").each(function(index, value){
$(value).attr('href', result[index]);
});
$(document).ready(function() {
$('#pdf').change(function() {
var newurl = $('#pdf').val();
$('a.target').attr('href', newurl);
});
});
I have a div like below in HTML page:
When I click on any div I am saving the span text in DB and when again come back to the same page I am getting the response as saved text. on the basis of the text I need repopulate the clicked view.
I am adding all the code I have used, not able to populate the data.
<div class="panel-body">
<div class='score score-exel'>
<div class='arrow'></div><span class='scoreText'> 750-850 Excellent</span>
</div>
<div class='score score-good'>
<div class='arrow'></div><span class='scoreText'> 700-749 Good</span>
</div>
<div class='score score-ok'>
<div class='arrow'></div><span class='scoreText'> 650-699 OK</span>
</div>
<div class='score score-fair'>
<div class='arrow'></div><span class='scoreText'> 600-649 Fair</span>
</div>
<div class='score score-poor'>
<div class='arrow'></div><span class='scoreText'> 300-599 Poor</span>
</div>
<div class='btnHold'>
<button class='btn btn-success idkBtn'>I Don't Know</button>
<button class='btn btn-success submitBtn'>Submit</button>
</div>
</div>
In the below code for variable I am adding the selected value when the user clicks the div.
$('.score').bind('click', function(){
$('.arrow').hide();
$(this).find('.arrow').fadeIn();
userCreditScore = $(this).find('span').text().toString();
});
In below code I am getting response and trying to repopulate the data but not possible.
function fillData(){
var response = nav.scorm.getResponse('CREDIT_SCORE');
if(response != ''){
var jsonData = jQuery.parseJSON(response);
*** used many codes like below but not useful
//$('.score').find('span.scoreText:contains('+jsonData.CREDIT_SCORE+')').parent().css('display', 'block');
//$('.score').find('span.scoreText:contains('+jsonData.CREDIT_SCORE+')').parent().click();
}
I assume that you're missing the callback in your nav.scorm.getResponse method - if it's a AJAX call. Check the commented code you have:
//here we do the request
var response = nav.scorm.getResponse('CREDIT_SCORE');
//this line and is executed immediately, while 'response' var is still undefined
if(response != ''){
So depending on code you have in nav.scorm.getResponse you might have smth like
nav.scorm.getResponse('CREDIT_SCORE', function(response){
if(response != ''){
//put it to DOM
console.log(response);
}
});
UPD
The problem was with the spaces in your scores texts,
' 600-649 Fair' won't work, while '600-649 Fair' will do.
Check this fiddle - https://jsfiddle.net/shershen08/v3gxy8rL/