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>
Related
I have a php script that creates a table and each id in the table has an edit button. The edit button looks like this.
<button data-siteid="'.$row->site_sn_id.'" class="btn btn-link p-0 m-0" style="font-size:.7rem" id="editBtn" type="button" >Edit</button>
The number of buttons varies but I am trying to get the data-siteid passed to an ajax call like this.
$("#editBtn").on("click", function(){
var siteID = $(this).data('siteid');
$.ajax({
method: "POST",
url: "edit-modal.php",
data: {siteID: siteID}
})
.done(function( msg ) {
$('#editModal').modal('show');
$("#bodyContent").html(msg);
});
});
Its working on the first edit button of the table but it does nothing after that first button. It wont even open the modal.
The reason is because ID should be unique across your HTML page and it looks like you're defining multiple elements with the same ID.
So, instead, try adding and using a class selector:
<button class="... editBtn" ...
$(".editBtn").on("click", function() {
...
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 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.
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
?>
I'm working on a planner using bootstrap, php and jquery and i'd like to use a datetimepicker (http://www.eyecon.ro/bootstrap-datepicker/) to go to a different date on the planner and view the tasks of that day.
I want to use a normal button to trigger the datepicker. Then, whenever the user picked a date, use GET to create a link like index.php?page=planner&date=2013-08-03. I'm trying not to use an input field, but whenever a date is clicked to create a GET link immediately if possible..
Example image:
How to create a button working like this?
I'm using the following HTML:
<a id="diff-date" class="btn btn-large btn-primary" href="#">Date <i class="icon-calendar icon-white"></i></a>
An the following JQuery:
$(function() {
$('#diff-date').datetimepicker({
pickTime: false
});
});
Without succes so far.. I hope someone can help!
EDIT
Normally I use this HTML:
<label>Datum:</label>
<div id="datum" class="input-append">
<input data-format="dd-MM-yyyy" type="text" name="datum" placeholder="Kies een datum..." /><span class="add-on"><i data-date-icon="icon-calendar"></i></span>
</div>
And this JQuery:
$(function() {
$('#datum').datetimepicker({
pickTime: false
});
});
To achieve this:
You're confusing:
http://tarruda.github.io/bootstrap-datetimepicker/
With this:
http://www.eyecon.ro/bootstrap-datepicker/
They're not the same.
Try this :
$(document).ready(function() {
$('#diff_date').datepicker().on('changeDate', function(ev){
var choosenDate = ev.date;
//Add a specific treatment for the date here...
$('#diff-date').datepicker('hide');
});
$('#diff_date').click(function() {
$('#diff-date').datepicker('show');
});
}
And change the html of your link like :
<a id="diff-date" class="btn btn-large btn-primary" href="#" data-date-format="yyyy-mm-dd" data-date="2012-02-20">Date <i class="icon-calendar icon-white"></i></a>
Just for information, this is the code used in the site to make a link with a calendar :
var startDate = new Date(2012,1,20);
var endDate = new Date(2012,1,25);
$('#dp4').datepicker()
.on('changeDate', function(ev){
if (ev.date.valueOf() > endDate.valueOf()){
$('#alert').show().find('strong').text('The start date can not be greater then the end date');
} else {
$('#alert').hide();
startDate = new Date(ev.date);
$('#startDate').text($('#dp4').data('date'));
}
$('#dp4').datepicker('hide');
});
And the Html for that
Start dateChange