specifying div id with jquery - php

I have buttons and divs and in each part I have them with the same ID I want to get the ID of button and use it for refreshing the div html.how should I write the * section?
$(function() {
$(".button").click(function(){
var id=$(this).attr('id');
var dataString = 'id='+ id ;
$.ajax({
type: "POST",
url: "download_number.php",
data: dataString,
cache: false,
success: function(html)
{
*********I HAVE PROBLEM HERE**************
$('how to get the id of the div from var id of button above?').html(html);
}
});
});
});
Div:
Downloaded:<div id="<?php echo $id; ?>" ><?php echo $downloadcount;?></div>
Button:
<input type = "button" value="Download" class="button" id="<?php echo $id; ?>" name="dl">
If I get class It will update the whole divs I want to update just the div realted to the button

You cannot have the same id on both the button and the div, id values must be unique in a document.
What I'd probably do is put the div's id on the button as a data-divid attribute (all attributes with the prefix data- are valid on all elements as of HTML5, and harmless in earlier versions of HTML), like this:
<input type="button" value="Download" class="button" data-divid="<?php echo $id; ?>" name="dl">
Then change
var id=$(this).attr('id');
to
var id=$(this).attr('data-divid');
...and then use that id var in your success callback (as the callback is a closure created within the context where id is defined, and so the callback has access to id).
Here's a simple example: Live copy | source
HTML:
<div id="div1">This is div1</div>
<div id="div2">This is div2</div>
<div>
<input type="button" data-divid="div1" value="Update div1">
<input type="button" data-divid="div2" value="Update div2">
</div>
JavaScript:
jQuery(function($) {
$("input[type=button]").click(function() {
var id = $(this).attr("data-divid");
// I'll use setTimeout to emulate doing an ajax call
setTimeout(function() {
// This is your 'success' function
$("#" + id).html("Updated at " + new Date());
}, 10);
return false;
});
});

Use the id but prefix them then build the name up...
<div id="div_<?php echo $id; ?>" ><?php echo $downloadcount;?></div>
button:
<input type = "button" value="Download" class="button" id="<?php echo $id; ?>" name="dl">
Then in you're code you have the id used in the buttons already (and also it will be div_), so you can then in you're 'success' just do:
$("#div_"+id).html(html);

change your html to this:
Downloaded:<div id="<?php echo $id; ?>" class="downloaded" ><?php echo $downloadcount;?></div>
then do something like:
var element_id = $(".downloaded").prop("id");
if(element_id = this.id){
$("#"+element_id).html(/* ... */);
}

$(function() {
$(".button").click(function(){
var id=$(this).attr('id');
var dataString = 'id='+ id ;
$.ajax({
type: "POST",
url: "download_number.php",
data: dataString,
cache: false,
success: function(html)
{
$('.count-' + id).html(html); // for class
}
});
});
});
<div class="count-<?php echo $id; ?>" ><?php echo $downloadcount;?></div>

First of all avoid using same IDS.
Then you can use CSS selectors:
$('div.class') //div
$('input[type="button"].youridclass')

You cannot use the id attribute for that purpose, the id cannot be a number (valid html) and thereby id's needs to be unique. Use the data attrib instead.

Try something like:
$('.button').attr('id');
to get the id of the button, then to change it:
$('.button').attr('id',''); //delete previous id if existing
$('.button').attr('id','yourNewId'); //set new id
then to use the new id:
$("#yourNewId").doSomething();

First and foremost, ids should be unique, you'll run into problems, particularly when using jQuery, if you have elements with the same id.
Without seeing your markup it's hard to give you a working example. But you can get the id of the div which corresponds to the clicked button by traversing the DOM.
Example markup:
<div id="example-div">
<input type="button" value="Example" />
</div>
jquery
$('input[type="button"]').click(function() {
console.log($(this).parent('div').prop('id'));
});
// outputs 'example-div'

for your reference check the below link for the various ways that you can use to select the dom elements given the parent element.
jsperf.com/jquery-selectors-context/2

Related

how to grab each value from input with jquery ajax when inputs are in a foreach loop

Input fields and delete buttons are produced by a php foreach loop!
To grab the value of an input and send it to php i use code below:
Html:
<input type="hidden" name="file_id" id="<?php echo $file_id; ?>" value="<?php echo $file_id; ?>" />
<button class="btn btn-sm btn-danger delete" type="submit" name="delete_file">Delete</button>
jquery:
$(document).on('click' , '.delete' , function() {
var file_id = $('#<?php echo $file_id; ?>').val();
$.ajax({
url: "admin.php",
method: "POST",
data: {
file_id : file_id
},
success: function(data) {
$('.result').html(data);
}
});
});
php:
if(isset($_POST["file_id"])) {
echo $_POST["file_id"];
}
Problem: When i submit (delete),it grabs always the value from the first input field.
How can i make this work, so when i choose the second delete, that it grabs the value from the second input field?
Instead of
var file_id = $('#<?php echo $file_id; ?>').val();
use
var file_id = $(this).prev().val(); // according to provided markup
This will select previous element to the <button> (which is the hidden <input>), and takes its value.

jQuery How do I call current/correct value after popup

Basically I have a list of files composed from a foreach loop that all have the same code except for the name, which carries the file_id for each file. My problem is that when I added an on-click pop-up event I lose the ability to fetch the current $(".flag") attribute name. Is there a way that I can pass it along the way so I can use it in the end?
PHP: (the user sees the link which they can click...remember there are several of these as a result from the foreach loop. I'm showing one for example)
echo "<td><a href='#' class='flag' name='$files[id]' >Click Here</a> ( $files[nums] )</td>";
jQuery: (on-click this will happen)
$(".flag").live('click', function() {
$(".pop").show("slow");
return false;
});
HTML: this div will popup
<div class="pop">
<form method="post" id="new_folder" >
<p><label for="folder">Reason for Reporting?</label><textarea id="report_reason" name="report_reason" maxlenght="100" style="resize:none" cols="30" rows="5">Please limit your response to 100 characters.</textarea></p>
<p><input type="submit" value="Submit" id="message_submit"/> or <a class="close" href="/">Cancel</a></p>
</form>
</div>
jQuery: on submit I need to send the current $files['id'] and textarea value via ajax. The textarea sends the correct data, but the $(".flag") instead of being the id of the selected link it is the id of the first fetched id from the foreach loop
$("#message_submit").on("click", function(e){
var fileID = $(".flag").attr("name");
var text = $("#report_reason").val();
$(".pop").hide("slow");
$.ajax({
url: '<?php echo base_url().'home/report_file';?>',
type: 'POST',
data: { val: fileID, val2: text },
dataType: 'json',
success: function(output_string){
$(".success").text("You have flagged this file!!").show().css({"color" : "green", "margin-top" : "10px"});
$(".success").fadeOut(10000);
}
});
return false;
});
You can save the .flag link being clicked and later use it.
var flagClicked;
$(".flag").live('click', function() {
$(".pop").show("slow");
flagClicked = $(this);
return false;
});
$("#message_submit").on("click", function(e){
var fileID = flagClicked.attr("name");
....

select the closest textarea to a button

I am having a table td which contains a textarea and a button and I want to send the value of textarea on button click via AJAX however there is a problem selecting the closest textarea to the button.
JavaScript
$(document).ready(function () {
$(document).on("click", ".addR", function () {
paperID = $(this).attr("paperID");
commentID = $(this).attr("commentID");
text = $(this).closest("textarea").val();
$.ajax({
data: {
paperID: paperID,
commentID: commentID,
text: text
},
type: 'POST',
url: 'add_rebuttal.php',
success: function (response) {
alert(response);
window.location.href = window.location.href;
}
});
});
});
PHP:
while ($row = mysql_fetch_assoc($comments)) {
echo "<tr><td>{$row['text']}</td>";
?>
<td><br /><textarea class="reText" rows='5' name='reText' id='reText' style='width:98%;' type='text'></textarea>
<button commentID="<?php echo $row['comment_id'] ?>" paperID="<?php echo $paper_id ?>" class="addR" type="button" name="addR" id="addR">send rebuttal</button></td></tr> <?
}
The problem is $(this).closest("textarea").val(); return undefined, so how I can solve this problem?
closest() returns the closest ancestor. Your textarea is not an ancestor of your button, it's a previous sibling. Instead, try:
text = $("textarea", $(this).parent()).val();
To get the text of a textarea you have to use text() instead of val(). As pointed out by Scotty, the textarea you want is not an ancestor so don't use closest().

get text value from dynamic created object

I'm still searching solution for getting values from dynamic created object.
Follwing code generates dynamic object from zip2.php
$(document).ready(function() {
$("#submit").click(function(e) {
e.preventDefault();
var q = $("#k").val();
$.ajax({
type: "POST",
url: "zips.php",
data: "q="+ q,
dataType: "html",
success: function(res) {
$("#result").html(res); $('#result').trigger('create');
},
});
});
});
<div data-role="content">
<div id="result"></div>
</div>
It created object like this format.(contents of zips.php)
<? echo " <div><ul id='zips' data-role='listview' data-inset='true' data-theme='c'>";
while($row = mysql_fetch_array($result)) {
$out .= "
<li>
<a name='submit_button' href='#mainPage'><span class='zip1'>$zip1</span>-
<span class='zip2'>$zip2</span><br />
<span class='address'>$row[zp_sido] $row[zp_gugun] $row[zp_dong] $row[zp_bunji] </span></a>
</li> \n";
}
echo $out."</ul>";
?>
And this script get the text() value from dynamic object and insert it to form.
<script>
$(document).ready(function() {
$('a[name=submit_button]').click(function(){
var inputVal1 = $('.zip1, this).text();
var inputVal2 = $('.zip2', this).text();
var inputVal3 = $('.address', this).text();
$('div input[name=zip_code1]').val(inputVal1);
$('div input[name=zip_code2]').val(inputVal2);
$('div input[name=address1]').val(inputVal3);
</script>
<div>
<form>
<input type="text" id='zip_code1' name="zip_code1" > - <input type="text" id='zip_code2 name="zip_code2"><br />
<input type="text" id='address1' name="address1">
</form
</div>
The problem is that "var inputVal1 = $('.zip1, this).text();" gets null from dynamic objects class name "zip1".
Instead of
$('a[name=submit_button]').click(function(){..
use this:
$('#result').on('click', 'a[name=submit_button]', function(){..
As you a[name=submit_button] append to DOM after page load, dynamically via ajax request, so you need delegate event handler to that, ordinary event binding will not work here.
Read more about .on()
Note
For general binding syntax of .on() is like:
$(target).on(eventName, handlerFunction)
but for delegate event systax is
$(container).on(eventName, target, handlerFunction)
Here container is the Static-element that belongs to DOM at page load and contains target and both container and target are valid jQuery selector.

Jquery not considering new div that is added by Jquery + php + jquery

I have a php page where I add and delete items from database using Jquery + PHP + AJAX.
Now I am able to delete and add when that page loads for the first time.
Now if I first add an element; which in turn adds record to the DB and then updates the div that contains all the listing of divs.
Example:
<div id="all_items">
<div id= "item_1">
<a id="delete_link">...</a>
</div>
<div id= "item_2">
<a id="delete_link">...</a>
</div>
.... Upto Item n
</div>
Now I replace the div with id all_items.
Now I have jQuery at the bottom of the page which calls ajax on a tag of delete_link.
Situtation is:
When page is loaded I can delete any item from the list.
But if I page load i add new item first. (which will update all_items div) after that if I try to click on delete link. Jquery on click selector event is not fired and which in turn doesn't do delete ajax operation.
I couldn't figure out why this is happening.
Looking for some help here.
EDITED:
Sorry for not writing code earliar.
Following is the jQuery I am talking about.
<script type="text/javascript" >
var jQ = jQuery.noConflict();
jQ(function() {
jQ("#submit_store").click(function() {
var store_name = jQ("#store_name").val();
var dataString = 'store_name='+ store_name;
dataString += '&mode=insert';
if(store_name =='')
{
alert("Please Enter store Name");
}
else {
jQ.ajax({
type: "POST",
url: "<?php echo $mycom_url; ?>/store_insert.php",
data: dataString,
cache: false,
success: function(html){
jQ("#dvstoreslists").html(html);
document.getElementById('store_name').value='';
document.getElementById('store_name').focus();
}
});
}
return false;
});
jQ(".store_delete").click(function() {
var store_id = jQ(this).attr('id');
var id = store_id.split("_");
var dataString = 'store_id='+ id[2];
dataString += '&mode=delete';
var to_delete = "#store_list_" + id[2]
jQ.ajax({
type: "POST",
url: "<?php echo $mycom_url; ?>/store_insert.php",
data: dataString,
cache: false,
success: function(html){
jQ(to_delete).hide("slow");
}
});
return false;
});
});
</script>
So If on page load, I delete then delete on click jquery event is fired. But after adding new store and replacing div of stores with new div. then jQuery on click event is not fired.
My HTML is as below.
<div class="sbBox stores">
<form id="add_storefrm" name="add_storefrm" method="post" action="" >
<div class="dvAddStore">
<div class="dvName" id="store_list">
<input type="text" id="store_name" name="store_name">
<input type="hidden" value="addstore" id="mode" name="mode">
</div>
<div class="btnAddStore">
<input type="submit" name="submit_store" value="Add Store" id="submit_store">
</div>
</div>
<div id="dvstoreslists">
<?php
$query = "SELECT * FROM #__shoppingstore order by store_id desc;";
$db->setQuery($query);
$rows = $db->loadObjectList();
foreach($rows as $row)
{
echo "<div class=dvlist id=store_list_".$row->store_id ."><div class=dvStoreListLeft>";
echo "<div class='slname'><h3>" . $row->store_name . "</h3></div>";
?>
<div class="slDelBtn">
<p id = "p_store_<?php echo $row->store_id ; ?>">
<a id="store_delete_<?php echo $row->store_id ; ?>" class="store_delete" alt="Delete" onclick="DeleteStore(<?php echo $row->store_id ; ?>);" >
</a>
</p>
</div>
</div>
</div>
<?php } ?>
</div>
</form>
</div>
Sorry folks for not posting the code earliar.
the ID should always be unique so use class instead
in your case : <a id="delete_link">...</a> to <a class="delete_link">...</a>
When you replace the contents of #all_items any event handlers that were bound to any descendants will no longer exist. You can use event delegation, using the on method, to solve this:
$("#all_items").on("click", ".delete_link", function() {
//Do stuff
});
Notice that I'm using a class selector (.delete_link) instead of an ID selector for the links. It's invalid to have duplicate IDs in the same document.
Also note that the above will only work if you are using jQuery 1.7 or above. For older versions, use delegate instead:
$("#all_items").on(".delete_link", "click", function() {
//Do stuff
});
This works because DOM events bubble up the tree from their target. So a click on a link which is a descendant of #all_items will bubble up through all of its ancestors and can be captured when it reached #all_items.
use live() instead of .bind()
It seems you are trying to delete dynamically added delete_link so i think you should use
$('id or class').on(click,function(){});

Categories