How can i get the value of a div class id?
I have this so far:
HTML
<div class="bolas-grad" id="<?php echo $list_titles[$zz]; ?>">
<?php
$list_titles = array();
foreach( $list_posts as $post ) {
$list_titles[] = $post->post_title;
}
echo $list_titles[$zz];
?>
</div>
JS
$(".bolas-grad").click(function() {
$(this).prop('id');
alert('id');
});
But instead of defining the 'id', how can i retreive the ID witch was clicked by the user?
Alert the ID, not the string 'id'
$(".bolas-grad").click(function() {
var id = $(this).prop('id');
alert(id);
});
Related
is that posible to load same data with jquery tooltip?
for example i have a data like this.
<div class="content"><span id="user_801130021">text1</span></div>
<div class="content"><span id="user_801130021">text2</span></div>
<div class="content"><span id="user_1301193710">text3</span></div>
the tooltip only showing for text1 and text3 but not showing data for text2, i think that because same id there.
here my js code
$(document).ready(function(){
// initialize tooltip
$( " span" ).tooltip({
track:true,
open: function( event, ui ) {
ui.tooltip.css("max-width", "100%");
var id = this.id;
var split_id = id.split('_');
var userid = split_id[1];
$.ajax({
url:'fetch_details.php',
type:'post',
data:{userid:userid},
success: function(response){
// Setting content option
$("#"+id).tooltip('option','content',response);
}
});
}
});
$(" span").mouseout(function(){
// re-initializing tooltip
$(this).tooltip();
$('.ui-tooltip').hide();
});
});
my fetch_details.php
<?php
$userid = $_POST['userid'];
$query = $db->prepare ("SELECT * FROM master_post WHERE id_master_post =".$userid);
$query->execute();
$html = '<div>';
while ($value = $query->fetch()) {
$information = html_entity_decode ($value['information']);
$dom = new DOMDocument();
#$dom->loadHTML($information);
$image = $dom->getElementsByTagName('img')->item(0)->getAttribute('src');
$html .= "<img src='".$image."' height='300px' width='250px'>";
}
$html .= '</div>';
echo $html;
?>
If they are not going to be unique as in your code, you can do different things.
Class
You can use class instead of id.
Use <span class="user_801130021"> instead of <span id="user_801130021">
You can access them by using basic jQuery selectors : $('.user_801130021')
HTML5 Data Attributes
Another option is using them as HTML5 data attributes which is so much better in my opinion. Their format is data-*.
<span data-user="user_801130021">
You can get data-user value by $('span').data('user') and change it by $('span').data('user', value)
For example, if you changed id to data-user, you must change var id = this.id; to var id = this.data('user');. Then everything will be work as it must.
i found the trick.
use looping number to create unique id.
here my code.
$np = 0;
while ($value = $query->fetch()) {
<div class="content"><span id="user<?php echo np++ ?>_801130021">text1</span></div>
}
I have an ajax autocomplete where it returns the full name of the user. However, when there are instances where some names or values are the same, it doesn't return the correct value. Rather, it returns the first value in the dropdown. Even if it has 4 same occurences, it still returns the first value.
When I click Stannis Arryn Baratheon, it returns Stannis Targaryen Baratheon.
Here is my php code (sql/php code; ad.php):
<?php
include('config.php');
if($_POST)
{
if($_POST['search_keyword'])
{
$similar = mysql_real_escape_string($_POST['search_keyword']);
$result=mysqli_query($conn, "SELECT * FROM person WHERE (firstName like '" . $_POST["search_keyword"] . "%' OR lastName like '" . $_POST["search_keyword"] . "%') AND residentOrNot = 'Yes' ");
if (mysqli_num_rows($result) > 0) {
while($row=mysqli_fetch_array($result))
{
//$name = $row['fullname'];
//$copiedname = $row['fullname'];
//$b_name= '<strong>'.$similar.'</strong>';
//$final_name = str_ireplace($similar, $b_name, $name);
?>
<div class="show" align="left">
<span class="returnName"><?php echo $row["firstName"].' '.$row["middleName"].' '.$row["lastName"]; ?></span>
<span class="returnID" style="display:none"><?php echo $row['idPerson'];?></span>
</div>
<?php
}
}
else {
?>
<div class="show" align="left">
<span class="returnMessage">No matching records found.</span>
</div>
<?php
}
}
mysqli_close($conn);
}
?>
HTML input form:
<form method="post" action="try.php" name="try">
<div class='web'>
<input type="text" class="search_keyword" id="search_keyword_id" placeholder="Search" />
<input type="hidden" name="resID" id="resID"/>
<div id="result"></div>
<input type="submit" name="try" value="Submit">
</div>
AJAX/JS/JQUERY CODE (i think this is where the problem occurs):
<script type="text/javascript">
$(function(){
$(".search_keyword").keyup(function()
{
var search_keyword_value = $(this).val();
var dataString = 'search_keyword='+ search_keyword_value;
if(search_keyword_value!='')
{
$.ajax({
type: "POST",
url: "ad.php",
data: dataString,
cache: false,
success: function(html)
{
$("#result").html(html).show();
}
});
}
return false;
});
jQuery("#result").on("click", function(e)
{
/*var $clicked = $(e.target);
var $name = $clicked.find('.returnName').html();
var decoded = $("<div/>").html($name).text();
$('#search_keyword_id').val(decoded);
var $clicked = $(e.target);
var $id = $clicked.find('.returnID').html();
var id = $("<div/>").html($id).text();
$('#resID').val(id);
*/
$name = $('span.returnName',this).html();
$name = $("<div/>").html($name).text().toString();
$('#search_keyword_id').val($name);
$id = $('span.returnID',this).html();
$id = $("<div/>").html($id).text().toString();
$('#resID').val($id);
});
jQuery(document).on("click", function(e) {
var $clicked = $(e.target);
if (! $clicked.hasClass("search_keyword")){
jQuery("#result").hide();
}
});
});
</script>
It really returns the first value even if I click the second or third or fourth value. Where did I go wrong in my code? Please help me. Thank you so much!
Your code is currently collecting all elements with class returnName in #result, and by calling .html() on that collection jQuery will only return the html of the first element found. The same goes for the your returnID search. This is why you are only getting the first returned entry.
Modify your #result click handler to only trigger for elements with class show, since that is the element that will contain your data.
jQuery("#result").on("click", ".show", function(e){
Then all you have to do is search for the elements with class returnName and returnID and call .text().
var showName = $('.returnName',this).text();
var showId = $('.returnID',this).text();
$('#search_keyword_id').val(showName);
$('#resID').val(showId);
So all together
jQuery("#result").on("click", ".show", function(e){
var showName = $('.returnName',this).text();
var showId = $('.returnID',this).text();
$('#search_keyword_id').val(showName);
$('#resID').val(showId);
});
Though note there are probably better ways of returning your data, and utilizing it rather than transporting it in html elements. For example use data-* attributes instead of using a separate span element to contain your id.
Another option is to use jQuery-UI's autocomplete that does most of the client side work for you and just return the raw data in JSON format from your php script.
In your php code, change this:
<div class="show" align="left">
<span class="returnName"><?php echo $row["firstName"].' '.$row["middleName"].' '.$row["lastName"]; ?></span>
<span class="returnID" style="display:none"><?php echo $row['idPerson'];?></span>
</div>
With this:
<div class="show" align="left">
<span class="returnName" data-id="<?php echo $row['idPerson'];?>"><?php echo $row["firstName"].' '.$row["middleName"].' '.$row["lastName"]; ?></span>
</div>
And your new jquery function:
jQuery("#result").on("click","'.returnName" function(e)
{
var choosenName = $(this).html();
var choosenId = $(this).data('id');
$('#search_keyword_id').val(choosenName );
$('#resID').val(choosenId );
});
I want to get the parent div id (the div class is called "col-sm-2") when selecting each option in HTML "select" tag in each div. But it always gives only the div id of latest added product at "id" alert. For example if the id of my last added product is "7", it always gives "7" as the alert.
Here is my PHP code for getting the product id.
$jsql_ae7 = mysql_query("select request_list.product_id from request_list where request_list.product_id='{$jrowa2['id']}' and request_list.email='$visit_email'") or die(mysql_error());
$jfeta7 = mysql_fetch_assoc($jsql_ae7);
Here is my HTML code.
<div class="col-sm-2" id="<?php echo $jfeta7['product_id']; ?>">
<select id="formats_id" name="aformats" onchange="showFormat(this);">
<option value="<?php echo $jrowa2['formats']; ?>"><?php echo $jrowa2['formats']; ?></option>
<?php foreach($formats3 as $v3){ ?>
<?php if($v3 !== $jrowa2['formats']) { ?>
<option value="<?php echo $v3; ?>"><?php echo $v3; ?></option>
<?php } ?>
<?php } ?>
</select>
</div>
Here is my javaScript code.
var showFormat = function(dd) {
var format_value = dd.options[dd.selectedIndex].value;
var scriptTags = document.getElementsByTagName('select');
var id = scriptTags[scriptTags.length - 1].parentNode.id;
alert(id);
};
Try to use each:
$('select').each(function() {
alert($(this).parent().attr('id'));
});
You coild get the id property of the immediate container div using closest() :
$('select').on('change',function() {
alert($(this).closest('div').prop('id'));
});
use this code
var showFormat = function(dd) {
var format_value = dd.options[dd.selectedIndex].value;
var scriptTags = document.getElementsByTagName('select');
var parent = scriptTags[scriptTags.length - 1].parentNode;
alert(parent.getAttribute('id'));
};
Try this:
Fiddle
$('#formats_id').change(function(){
alert($(this).parent().attr('id'));
});
First we will start with making the selection:
$('select').each(function() {
var selectField = $(this); // this will point to select element
});
There are two ways:
This will take direct parent of select
selectField.parent().attr('id');
This will select first ancestor that is a div with class 'my-class':
selectField.closest('div.my-class').attr('id');
Both work, but differ in deep of search:)
Im making a like system and am encorporating ajax to make it smooth. Everything works okay except it always defaults to the last post in for loop. My thinking is there is no way for the javascript to know which element of id "like" to post to.
main.js:
$(".like>a").click(function() {
$.post(base_url + "index.php/userprofile/like_post/", { post : post }, function(data) {
alert('liked');
}, "json");
return false;
});
Im passing through the post variable from the view file. I grab the postID of each post.
userprofile_view.php:
<?php foreach ($posts as $post)
{ ?>
<?php $postID = $this->model_posts->getPostData('id', $post->post); ?>
<script type="text/javascript">
var post = "<?php echo $postID; ?>";
var base_url = "<?php echo base_url(); ?>";
</script>
model_posts.php:
function likePost($post) {
$data['user_ID'] = $this->session->userdata('id');
$data['post_liked'] = $post;
$insert = $this->db->insert('user_post_likes', $data);
return $insert;
}
userprofile.php(controller):
public function like_post() {
$this->load->model('model_posts');
$post = $this->input->post('post');
$this->model_posts->likePost($post);
}
If someone couldhelp me out that would be great!
The problem is your usage of a global variable in a loop, so the variable will have only the last value of the loop.
You can use a data-* attribute like
<script type="text/javascript">
var base_url = "<?php echo base_url(); ?>";
</script>
<?php foreach ($posts as $post)
{ ?>
<?php $postID = $this->model_posts->getPostData('id', $post->post); ?>
<div class='posts'>
<div class='posts_img'>
<img src="<?php echo base_url() . 'img/profilepictures/thumbs/' . $profilepicture?>">
</div>
<div class='posts_user'>
<strong><?php echo $prefname; ?></strong>
</div>
<div class='posts_date'>
<?php echo $this->model_posts->getPostTime($post->post); ?>
</div>
<div class='post'>
<p><?php echo $post->post ?></p>
</div>
<?php if($this->model_posts->doesUserLike($me, $postID)) { ?>
<div class='unlike'>
<?php echo anchor('userprofile/unlike_post/' . $me . '/' . $postID, 'unlike'); ?>
</div>
<?php } else { ?>
<div class='like' data-post="<?php echo $postID; ?>">
<?php echo anchor('#', 'like', array('id' => 'like')); ?>
</div>
<?php } ?>
then
$(".like>a").click(function () {
var post = $(this).parent().attr('data-post');
$.post(base_url + "index.php/userprofile/like_post/", {
post: post
}, function (data) {
alert('liked');
}, "json");
return false;
});
if you're sending same ID field with different values stop, send unique IDs with selected values OR send ID with values as post array, PHP can deal with it
<script type="text/javascript">
var post = "<?php echo $postID; ?>";
var base_url = "<?php echo base_url(); ?>";
</script>
This is your problem. You're declaring these variables in global scope. So every time your PHP foreach loop iterates, you're redefining the variable in global scope, overwriting the previous value.
Instead, set an id attribute on each <a> tag to be the $postID, and get that ID in your click handler, like so:
$(".like>a").click(function() {
var post = this.id;
$.post(base_url + "index.php/userprofile/like_post/", { post : post }, function(data) {
alert('liked');
}, "json");
return false;
});
You would have to modify the code that creates the <a> tags to include the id attribute with the $postID value assigned to it...I don't see that part included in your code samples.
I am a newbie in Jquery. I have a table in my webpage which shows the contents of a user table from the database.I have also created an edit button and Delete button for each row of data.I need the id of each edit and delete button for writing code for editing and deleting the records in the database as well as implementing this changes in the table in the webpage also.
$query = mysqli_query($con,"SELECT * FROM user_details");
while($row = mysqli_fetch_array($query))
{
echo "<tr>";
echo "<td>".$row['fname']."</td>";
echo "<td>".$row['mname']."</td>";
echo "<td>".$row['childname']."</td>";
echo "<td><input type='button' id = 'edit".$row['Id']."' value='Edit'></td>";
echo "<td><input type='button' id = 'delete".$row['Id']."' value='Delete'></td>";
echo "</tr>";
}
If I am using Jquery,how to get the IDof each button?Or If I write a onclick event using javascript for each button and passes the ID's as arguments,can I access via Jquery.Please help me
$("button").each(function(index, item) {
var itemId = $(item).attr('id');
});
But I would set the $row['id'] into a data-id attribute and then use:
$("button").each(function(index, item) {
var itemId = $(item).data('id');
});
Add common class name and use that as a selector to get id of the buttons like below
Try like this
$(document).on('click','.edit_btn',function(){
alert($(this).attr('id'));
});
$(document).on('click','.del_btn',function(){
alert($(this).attr('id'));
});
HTML
<input type='button' id ='edit' class="edit_btn" value='Edit'>
<input type='button' id ='delete' class="del_btn" value='Delete'>
DEMO
First of all, you need to escape your variables in HTML context using htmlspecialchars(). Second, you can use data attributes to easily identify the record that needs be edited or deleted.
?>
<tr>
<td><?= htmlspecialchars($row['fname'], ENT_QUOTES, 'UTF-8') ?></td>
<td><?= htmlspecialchars($row['mname'], ENT_QUOTES, 'UTF-8') ?></td>
<td><?= htmlspecialchars($row['childname'], ENT_QUOTES, 'UTF-8') ?></td>
<td><input type="button" class="edit" data-id="<?= $row['Id'] ?>" value="Edit"></td>
<td><input type="button" class="delete" data-id="<?= $row['Id'] ?>" value="Delete"></td>
</tr>
<?php
Then, you can use classes to identify the buttons instead:
$('.edit').on('click', function() {
var id = $(this).data('id');
// edit stuff
});
$('.delete').on('click', function() {
var id = $(this).data('id');
// delete stuff
});
You can use a data-* attribute to specify the ID and use a common class to call the click handler
echo "<td><input type='button' id = 'edit".$row['Id']."' data-id='".$row['Id']."' value='Edit' class='edit-record'></td>";
then in jQuery
jQuery(function ($) {
$(document).on('click', '.edit-record', function () {
//this is called when the edit button is clicked
var $this = $(this),
id = $this.data('id');
//now id has the value of current record's id
})
})
Use Attribute starts with selector, and Event Delegation
$(document).on("click" , "[id^='edit']" ,function() {
console.log(this.id);
});
$(document).on("click" , "[id^='delete']" , function() {
console.log(this.id);
});