Jquery - Get Button Value Dynamically - php

I have a JS that output the button dynamically:
<button class='btn btn-mini btn-primary likebtn' name='likebtn' value='1' type='button'>value1text</button>
<button class='btn btn-mini btn-primary likebtn' name='likebtn' value='2' type='button'>value2text</button>
$('button=[name=likebtn]').click(function (){
alert($(this).val());
});
I would like to get the value of the button click! But it doesn't seem to get the name of button clicked. Why? Find it strange...
Code is here...
$('#div').append("<button class='btn btn-mini btn-primary likebtn' name='likebtn' type='button' value='"+obj.value+"'>"+"LIKE"+"</button>");

If you are outputting the buttons via javascript you need to use on instead of click to bind your events.
$('body').on("click", "button[name=likebtn]", function (){
alert($(this).attr("value"));
});

you can just use
$(this).val()
to get value
use
$(this).text()
to get the text
if u want to append value to asd use
alert('asd'+$(this).val());
and use the selector as $('button[name=likebtn]').click(....

In script, you should write :
$('button[name="likebtn"]').click(function(){
alert($(this).val());//if you are trying to get value of 'value' attribute
alert($(this).text());//if you are trying to get text between the tag
});
You can look at this to check the example.

I believe you are trying to get the text of the button, if so:
$(this).text()
And remove the 'asd':
alert($(this).val());
And fix your selector:
$('button[name=likebtn]')

You can use this directly and remove unwanted doublequotes.
$('button[name=likebtn]').click(function (){
alert($(this).val());
});
Check this JSFiddle
You need to correct the append method
$('div').append('<button class=btn btn-mini btn-primary likebtn name=likebtn value='+ obj.value + '>LIKE</button>');
check this

You can try this one,if the button is dynamic and brought using ajax:
$(document).ready(function(){
$(".details").click(function(){
var value=$(this).attr('id');
$.post("product-viewbills-1.php",
{
value1:value
},
function(data){
//alert(data);
$('#shadow').html(data);
});
});
});
Now the above code is the j query (ajax) we are using. $.post is used instead of $.ajax
Now we will see the button used dynamically. this one is a php code
<?php
$con=mysqli_connect("localhost","root","root","amazing"); //connecting to database
$result=mysqli_query($con,"SELECT * FROM productmaster"); //taking values from table
while($row=mysqli_fetch_array($result)) //fetching the array which contains the column
{
?>
<input type="button" class="details" id="<?php echo $row['pmid'];?>" value="details">
<?php
}
?>
Now we have made so many buttons having unique ids and same class pmid is the column of the table we have taken.
Now each button contains different ids and can be used separately.
<div id="shadow"></div>
<?php
mysqli_close($con); //closing the database
?>

Related

jQuery add class to specific ID based on MYSQL fetch

I try to solve this problem:
I have a from MYSQL fetched element in PHP:
<button class="like-btn" id="idLike-'.$row['id'].'">Button text</button>
Currently, there are 3 fetched elements and every fetched element has its own id automatically e.g. idLike-1, idLike-2, idLike-3 etc.
I added a Jquery script:
$(document).ready(function(){
$("#idLike-2").click(function(){
$("#idLike-2").addClass("btn-first");
});
});
This works fine with the idLike-2 element of course, but I cannot find an ultimate solution for this script to work every id separately e.g. if I click on the idLike-1, only this element has a new class.
Thank you for your help!
Update:
If I try to save the current state of the element into the localStorage, the state of all elements will be saved. My full code:
$(document).ready(function(){
$(document).ready(function() {
if(localStorage.getItem('isCliked')){
$(".like-btn").addClass('liked-btn');
$(".like-btn").removeClass('like-btn');
}
$('.like-btn').on('click',function() {
$(this).addClass('liked-btn');
$(this).removeClass('like-btn');
// set the value upon clicking
localStorage.setItem('isCliked', true)
});
});```
You could solve that by using a more general "class" selector like so:
PHP fetched HTML:
<button class="like-btn">Button text</button>
Javascript:
$(document).ready(function() {
$(".like-btn").click(function() {
$(this).addClass("btn-first");
});
});
You can target the jQuery element triggering the event using the $(this) selector.
References:
https://api.jquery.com/class-selector/
https://api.jquery.com/jquery/#jQuery-element
1 alternative option is using wildcard on id.
$('button[id*="idLike-"]').click(function() {
$('button').removeClass("btn-first");
$(this).addClass("btn-first");
});
.btn-first {
background: red
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<button class="like-btn" id="idLike-1">Button text</button>
<button class="like-btn" id="idLike-2">Button text</button>
<button class="like-btn" id="idLike-3">Button text</button>

PHP / MySQL / AJAX - Update multiple data

How to update multiple data using AJAX ?
Example :
TableA
id : 1, 2
name : Jack, John
It's only working with id 1, when I am trying to edit name for id 2 it's not working.
I have try with this code but failed.
HTML/PHP :
...
while($row=mysqli_fetch_array($query)){
echo'
<form class="btn-group">
<input type="text" class="form-control" name="id_user" id="id_user" data-user="'.$row['id'].'" value="'.$row['id'].'">
<input type="text" class="form-control" name="id_status" id="id_status" data-status="'.$row['id'].'" value="'.$row['id'].'">
<button type="submit" id="likestatus" class="btn btn-primary btn-outline btn-xs"><i class="fas fa-thumbs-up"></i></button>
</form>
';
}
AJAX :
$(document).ready(function(){
$("#likestatus").click(function(){
var id_user=$("#id_user").data("user");
var id_status=$("#id_status").data("status");
$.ajax({
url:'status/like-status.php',
method:'POST',
data:{
id_user:id_user,
id_status:id_status
},
success:function(response){
alert(response);
}
});
});
});
The problem with your code is that ids should be unique, but in the loop you create elements with same id.
Use this in the event handler to find the siblings of the button that has been clicked - closest returns the parent of type form.
$(document).ready(function(){
$(".btn-primary").click(function(){
var $form = $(this).closest('form');
var id_user=$form.find('[name="id_user"]').data("user");
var id_status=$form.find('[name="id_status"]').data("status");
$.ajax({
url:'status/like-status.php',
method:'POST',
data:{
id_user:id_user,
id_status:id_status
},
success:function(response){
alert(response);
}
});
});
});
You might want to use your own class instead of .btn-primary because this affects all buttons on the page.
Judging from the incomplete PHP, it appears as if you're not assigning to $ruser within your loop. This would mean you're always posting the same id to like-status.php.
PS: Would've posted as comment, but I can't.
Make your ID unique so make them dynamic
<?php
$counter = 0;
while($row=mysqli_fetch_array($query)){
$counter++;
echo'
<form class="btn-group">
<input type="text" class="form-control" id="userid_$counter" data-user="'.$ruser['id'].'" value="'.$ruser['id'].'">
<input type="text" class="form-control" name="id_status" id="status_$counter" data-status="'.$rtimeline['id'].'" value="'.$rtimeline['id'].'">
<button type="submit" id="likestatus_$counter" class="btn btn-primary btn-outline btn-xs"><i class="fas fa-thumbs-up"></i></button>
</form>
';
}
?>
Then
<script type="text/javascript">
$(document).ready(function(){
$('[id^="likestatus_"]').on('click',function(){
var index = $(this).attr('id').split("_")[1];
var id_user=$("#user_"+index).data("user");
var id_status=$("#status_"+index).data("status");
$.ajax({
url:'status/like-status.php',
method:'POST',
data:{
id_user:id_user,
id_status:id_status
},
success:function(response){
alert(response);
}
});
});
});
You're using the id's multiple times. Thus your query for var id_user=$("#id_user").data("user"); always finds the first input field on the page. You should avoid using the same id multiple times on one page (see this Question).
You may subscribe to the jQuery submit event of the form and then search for the input fields within that form, to properly extract the id_user and status_user values. For that you have to add an appropriate event listener to the <form> element. To find the form I would recommend adding a css-class like like-status-form.
$(document).ready(function(){
// We're attaching a submit-event listener to every element with the css class "like-status-form"
$(".like-status-form").submit(function(event){
// Form get's submitted
// Prevent that the Browser reloads the page
event.preventDefault();
// Extract the user id and status from the form element (=== $(this))
var id_user = $(this).find('[name="id_user"]').data('user');
var id_status = $(this).find('[name="id_status"]').data('status');
// TODO Perform AJAX Call here
});
});
To detect the form elements one can use the jQuery Attribute Equals Selector.
Find a working example at https://jsfiddle.net/07yzf8k1/

I am unable to use id in codeigniter for jquery

I have a submit button in codeigniter which is as follow:
<?php
form_open('admin/delete_article'),
form_hidden('article_id', $article->id),
form_submit(['name'=>'submit', 'id'=>'btnDelete', 'value'=>'Delete', 'class'=>'btn btn-danger']),
form_close();
?>
Actually this is a delete button and I want to add a fuctionality to confirm before delete, so I am using jquery by using #btnDelete, but that is not working. Source code is showing the input correctly, like:
<input type="submit" name="submit" value="Delete" id="btnDelete" class="btn btn-danger" />
Jquery is loading correctly in the bottom of the page, but id and class of the input type is not working in jquery. My jquery code is as follow:
$(document).ready(function() {
$("#btnDelete").click(function() {
bootbox.confirm("Are you sure want to delete?", function(result) {
alert("Confirm result: " + result);
});
});
});
But id and class is not working even I am alerting something. Why is this so?
Update: This piece of code works:
$(document).ready(function(){
$('div').click(function(){
alert("Umar");
});
});
I am unable to understand why any of the selectors of the input type is not working only, rest is working fine?
You can use this:
$('body').on('click', '#btnDelete', function() {
//code
});
Your code not working because it didn't load at the time, so can't catch the trigger.

How to pass php variable (id) using button going to other form

Sorry for kinda idiot, I just want to ask if possible to pass a php variable using button.
for example I have a list of records with update, contact, delete buttons at the end of row. when I click the update it will go to update page where i can get the id that passes through the button.
foreach($director->results() as $director){
$id = $director->id;
echo "<tr>
<td>$director->director</td>
<td>$director->agent_name</td>
<td>$director->apz_account</td>
<td>$director->api_account</td>
<td>$director->wupos_tid</td>
<td>$director->translink_tid</td>
<td>$director->island_name</td>
<td>$director->region</td>
<td>$director->province</td>
<td>$director->city</td>
<td>$director->address</td>
<td>$director->landmark</td>
<td width='200'>
<button class='btn btn-mini btn-info' value='$director->apz_account'>Update</button>
<button class='btn btn-mini btn-info'>Contact</button>
<button class='btn btn-mini btn-info'>delete</button>"; //end the echo command
}
you have to work with <form> and passing the id of director with an hidden <input> to the page in which you want to do the update
try this way:
<form method="POST" action="yourPage.php">
<input type="hidden" name="id_director" value="<?= $id ?>" />
<input type="submit" value="Update" />
</form>
then in yourPage.php
$id_director = $_POST['id_director'];
//do your query
"UPDATE director set foo = 'foo' where id = $id_director";
hope this helps
When the user clicks the submit button, trigger an event in jquery
then get the id of that row using the attr property and pass it as a query string to that php page and from that php page you can get the value of that id and you can do any manipulations
For ex:
$("#button").click(function(){
var id=$(this).attr("id");
//Use jquery's ajax method here to
$.ajax(
{
// The link we are accessing.
url: "your url?id="+id,
// The type of request.
type: "get",
// The type of data that is getting returned.
dataType: "html",
error: function(){
ShowStatus( "AJAX - error()" );
// Load the content in to the page.
jContent.html( "<p>Page Not Found!!</p>" );
},
beforeSend: function(){
ShowStatus( "AJAX - beforeSend()" );
},
complete: function(){
ShowStatus( "AJAX - complete()" );
},
success: function( strData ){
ShowStatus( "AJAX - success()" );
// Load the content in to the page.
jContent.html( strData );
}
}
);
});
try this make a function and then do like this
<button onclick="updateme('<?php echo $director->apz_account ?>')" class='btn btn-mini btn-info' value='$director->apz_account'>Update</button>
now the function is
function updateme(id){
//alert(id); just to get the id
window.location.href = 'your_page_url.php?id='+id;
}
make your code like this when you go to our_page_url.php use header there to load your current page
do your code likes this and then you get alert...
once you get alert page reload with given href and do your query
to complete the update...!!..
NOTE:-here no need to use value attr. because you get value in function
echo "<button onclick=\"updateme('".$director->id ."')\" class='btn btn-mini btn-info' value=".$director->id ." >Update</button>";

remove clicked button div on button click

i m getting data from databse, number of div depend on the number of records but i m getting wanted result if i click 4th button the first div is removed but i want it to remove 4th div not first, my code is here
<button class="mws-button red" type="button" id="red_remove_<?php echo $i;?>"onclick="rem(id,id);">Remove</button>
i have called this function on button click
var count=0;
function rem(key,l){
$('#remove_more_opertaion'+count).remove();
$('#label'+count).remove();
count++;
}
Cleaner way to do it using jQuery:
HTML:
<button class="mws-button red remove-btn"
type="button"
data-id="<?php echo $i; ?>" // <-- will use this id to remove corresponding div
id="red_remove_<?php echo $i;?>">Remove</button>
JS:
$('.remove-btn').click(function() {
var id = $(this).data('id');
$('#remove_more_opertaion' + id).remove();
$('#label' + id).remove();
});
Alos no need to use onclick="..." since you have jQuery.
use the split function and match the number and deleted clicked button div

Categories