I will probably sound or look dumb by this but I need to learn. Check out the following part of a code:
$('.buttonclass').click(function(){
var button_id = $(this).attr('id');
$('#'+button_id).click(function(){
var yes = $("input#yes").val();
if (yes == "") {
return false;
}
var id = $("input#id").val();
if (id == "") {
return false;
}
var dataString = 'yes='+ yes + '&id=' + id;
//try insted this //alert (dataString);return false;
$.ajax({ type: "POST", dataType:'HTML',
//or the appropiate type of data you are getting back
url: "http://www.edshaer.com/EdinburgCISD/Gorena/Gorena.php", data: dataString,
//in the php file do $email = $_POST['email'];
//not a good practice but you can try with it and without it
success: function(data) {
$("#div").hide(data).fadeOut();
$("#div").html(data);
$("#div").show(data).fadeIn();
// Change the content of the message element
// Fade the element back in
} });
//ajax ends
return false; });
//click ends
});//document ready ends
My button ID that is being submitted in my html page is sending random numbers. For example
It can be:
$("#383").click(function() {
or it can be:
$("#521").click(function() {
My question is, how do I do it to auto increment the ID of the button clicked so that no matter what ID number is clicked it will still run the run the code smoothly... Right now I have this:
$('.buttonclass').click(function(){
var button_id = $(this).attr('id');
$('#'+button_id).click(function(){
Hopefully someone can help me... let me know if you need more info... Thank you in advanced...
Here is part of my HTML code... Hopefully it will be a little more understandable...
<?php
$data3 = mysql_query("SELECT * FROM `EdinburgCISDGorenamessage`
ORDER BY `ID` DESC LIMIT 0, 100")
or die(mysql_error());
echo "<div id=\"div\"> <table align=\"center\" width=\"570\">";
while($info3 = mysql_fetch_array( $data3 ))
{
$id = $info3['ID'];
}
?>
<form name="contact" id="post" method="post" action="">
<input id="id" value="<?php echo $id?>"/>
<input type="submit" class="buttonclass" id="<?php echo $id?>" name="<?php echo $id?>" value="Yes" />
<input type="submit" id="no<?php echo $id ?>" name="no<?php echo $id ?>" value=" No " /> </form>
I don' want to provide the whole code because its too messy and it doesn't go with the question... Let me know if you need anything else.
Use a class instead. Add a class to the button, and an incremental id you give it while printing it out in your html (I suppose you echo buttons in a loop?), and then just use one snippet:
$('.buttonclass').click(function(){
var button_id = $(this).attr('id');
$('#'+button_id).click(function(){
// your function here
alert(button_id); // just to see if ID is retrieved
)};
});
So, if you have
<button id="325" class="buttonclass" type="button">BUTTON 325</button>
<button id="150" class="buttonclass" type="button">BUTTON 150</button>
The ID of the button you click is retrieved only when you press it
Related
I have a form where there are select option and a textbox. All I want to do is when I select specific option, it will pass the id to query the same table to get another column's value based on ID of selected option and then display the value in a textbox before insert/update the table.
This code will works if both field in my form using select field. So in my opinion, maybe my script for storing value in input text field is totally wrong. Please correct me if I do wrong.
My form code :
<form name="inserform" method="POST">
<label>Existing Customer Name : </label>
<select name="existCustName" id="existCustName">
<option value="">None</option>
<?php
$custName = $conn->query("SELECT * FROM customers");
while ($row = $custName->fetch_assoc())
{
?><option id="<?php echo $row['customerID']; ?>" value="<?php echo $row['customerID']; ?>"><?php echo $row['customerName']; ?></option><?php
}
?>
</select>br>
<label>Current Bottle Balance : </label>
<input type="int" id="currentBal" name="currentBal"></input><br>
<input name="insert" type="submit" value="INSERT"></input>
</form>
My script code :
<script type="text/javascript">
$(document).on("change", 'select#existCustName', function(e) {
var existCustID = $(this).children(":selected").attr("id");
$.ajax({
type: "POST",
data: {existCustID: existCustID},
url: 'existingcustomerlist.php',
dataType: 'json',
success: function(json) {
var $el = $("input#currentBal");
$el.empty();
$.each(json, function(k, v) {
$el.append("'input[value='" + v.currentBal + "']").val();
});
}
});
});
</script>
existingcustomerlist.php code:
<?php
include 'config/config.php';
$result = $conn->query("SELECT * FROM customers WHERE customerID = '" .$_POST['existCustID'] . "'");
$results = [];
while ($row = $result->fetch_assoc()) {
$results[] = $row;
}
header('Content-Type: application/json');
echo json_encode($results);
?>
I need help to solve this.
I assume you are trying to show the results as input text element next to the #currentBal element. Try by changing the script tag inside the success callback as shown below.
$.each(json, function (k, v) {
$el.after("<input type='text' class="currentBalTemp" value='" + v.currentBal + "' />");
});
Make sure to remove the .currentBalTemp elements on change event of select otherwise duplication will be shown. Add the below code on change event.
$('.currentBalTemp').remove();
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
I have a popup form on which a user provides a key to get access to the site. I validate the user provided key with Jquery. It is working fine on my local system but when I submit the form using ipad it does not work. The form is even nor submitted.
My Form is
<form name="form" method="post">
<div style="width:530px;">
<input style="display:none; height:25px;" id="downloadkey" name="downloadkey" type="text" />
<input style="display:none;" type="submit" id="submit" name="submit" value="<?php echo $variable['QUESTION_BUTTON']['value'] ?>"/>
</div>
<input type="hidden" id ="box_id" value="<?php echo $box_id ?>" />
</form>
JQuery is
$(document).ready(function() {
$('#submit').click(function(e) {
var key = $('#downloadkey').val();
var box_id = $('#box_id').val();
var dataString = {KEY:key, BID:box_id};
$.ajax({
url: "/home/validate_key",
type: 'POST',
data: dataString,
success: function(msg) {
if(msg=="false"){
alert("Your download key is either wrong or missing");
}
else{
$('#popupContact').hide();
$('#backgroundPopup').hide();
}
}
});
e.preventDefault();
});
});
In my controller the validate function is
function validate_key(){
$key = strtolower($this->input->post('KEY'));
$id = $this->input->post('BID');
$query = $this->db->get_where('mc_boxes', array('idmc_boxes' => $id));
$row = $query->row();
$download_key = strtolower($row->downloadkey);
if($download_key == $key){
$_SESSION['download_key'] = $key;
$_SESSION['timeout'] = time();
}
else{
echo 'false';
}
}
Do i need something special to make it working on ipad?
Thanks
jQuery.click() doesn't function properly on iOS.
Try using jQuery.on() or by binding other events like touchstart
.bind("click touch tap", function(){
// code
});
Is what I've seen used when dealing with iPad.
(It's not a CodeIgniter issue for sure.)
I have a comments section on my websites that uses jQuery to animate comments in without reloading the page, as well as deleting comments.
Right now, I have it so when you write a comment, it sends it to a external JS, then to a php file where it processes. If it was successful, it will append the comment into the comment section. My delete action: jQuery deletes my the comment ID in the mysql database.
So my issue is I want to add a delete button via jQuery and somehow call back to the javascript file and tell it the id so the delete button knows the ID to put in the form so the delete file knows what to delete?
Here's my add_comment script:
$(function() {
$(".commentbutton").click(function() {
$.ajax({
type: "POST",
url: "http://myflashpics.com/process_addcomment.php",
data: $("#commentform").serialize(),
success: function() {
var theComment = $("#commentsss").val();
var theUserId = $("#user_id_two").val();
var thePhotoId = $("#photo_id").val();
var theProfilePicture = $("#user_profile_picture").val();
var theUsername = $("#user_username").val();
// Get new HTML data
var html = "<div class='comment_odd'><img src='" + theProfilePicture + "' class='comment_thumbnail'/><div class='comment_username'>" + theUsername + "</div><div class='comment_text'>" + theComment + "</div></div>";
// Append, then fade in
$(html).hide().appendTo(thecommentsdisplay).fadeIn(500);
}
});
return false;
});
});
Thanks in advance!Coulton
EDIT 1:
Here's my comments form (just to clarify):
user_id_two (the user's ID)
commentsss (comments field)
photo_id (the id of the photo being commented on)
user_profile_picture (profile to display on the user's profile picture in the banner)
user_username (username of the user commenting)
Here's also my delete button form:
<form method='post' action='' name='deleteform' id='deleteform'>
<input type='hidden' name='userid' value='<?php echo "$userid_session"; ?>' />
<input type='hidden' name='userpass' value='<?php echo "$password_session"; ?>' />
<input type='hidden' name='pictureid' id='pictureid' value='<?php echo "$picture_id"; ?>' />
<input type='hidden' name='profilepictureid' id='profilepictureid' value='<?php echo "$user_profile_picture_id"; ?>' />
</form>
And lastly my DELETE COMMENT jQuery:
$(function() {
$(".commentdeletebutton").click(function() {
var className = $(this).attr('class');
var theID = className.replace(/delete_button commentdeletebutton delete_(\d+)/, "$1");
commentDone = "#comment_" + theID;
formDone = "#commentdeleteform_" + theID;
$.ajax({
type: "POST",
url: "http://myflashpics.com/process_deletecomment.php",
data: $(formDone).serialize(),
success: function() {
$(commentDone).hide();
}
});
return false;
});
});
If you add an link for deleting, you can insert the complete url for deleting in the href, i.e. http://myflashpics.com/process_removecomment.php?id=xx.
So, you can bind a click event to that link and get the right url using $(this).attr('href') and doing the delete using ajax.
Edited for a more complete sample:
<? [[Loop your recordset]] { ?>
<div class="comment">
Delete
<div class="comment">
[[Comment content...]]
</div>
</div>
<? } ?>
<script>
$(function() {
$(".commentdeletebutton").click(function() {
$this = $(this);
$.ajax({
url: $this.attr('href'),
success: function(data) {
$this.parent().slideUp('fast', function() {
$this.parent().remove();
});
}
});
return false;
});
});
</script>
I want to add a comment system after my article,
php part code
<?php
...
while($result = mysql_fetch_array($resultset))
{
$article_title = $result['article_title'];
...
?>
<form id="postform" class="postform">
<input type="hidden" name="title" id="title" value="<?=$article_title;?>" />
<input type="text" name="content" id="content" />
<input type="button" value="Submit" class="Submit" />
</form>
...
<?php
}
?>
ajax part:
$(function($) {
$(document).ready(function(){
$(".Submit").click(function(){
var id = $(this).attr("id");
var name = $(this).attr("name");
var dataString = 'id='+ id ;
var parent = $(this);
var anyBlank = 0;
if(anyBlank == "0")
{
var title = $("#title").val();
var content = $("#content").val();
$.ajax({
type: "POST",
url: "ajax_post.php",
data: "title="+title+"&content="+content,
success: function(date_added){
if(date_added != 0)
{
structure = '<div class="comment_date_added">'+date_added+'</div><div id="comment_text"><div id="comment_content">'+content+'</div>';
$("#post_comment").prepend(structure);
}
});
});
ajax_post.php
echo $title;
echo $content;//get $title and $content and insert into database.
my question: <form id="postform" class="postform"> is written into a MYSQL_QUERY result circle. how to modify ajax part so that every div.submit can post its own value to ajax_post.php and then return the data into $("#post_comment").prepend(structure); Thanks to all.
You have to give the input fields a class instead of an ID. IDs have to be unique in an HTML document:
<form class="postform">
<input type="hidden" name="title" class="title" value="<?=$article_title;?>" />
<input type="text" name="content" class="content" />
<input type="button" value="Submit" class="Submit" />
</form>
Then you can make the data lookup relative to the clicked element:
var title = $(this).siblings('.title').val();
var content = $(this).siblings('.content').val();
I also suggest to pass an object to the data attribute for automatic URL encoding of the values:
data: {title: title, content: content}
Then, when you create a new entry for the #post_comment section, you have to give these elements also a class instead of an ID (and don't forget to use var!):
var structure = '<div class="comment_date_added">'+date_added+'</div><div class="comment_text"><div class="comment_content">'+content+'</div>';
or more jQuery like:
$('<div />', {class:'comment_data_added'})
.append($('<div />', {class: 'comment_date_added', text: date_added}))
.append($('<div />', {class: 'comment_content', text: content}))
.prependTo('#post_comment');
Further notes:
You have somehow a nested ready() handler:
$(function($) { // <--┐
$(document).ready(function(){ // <--┴- this is the same
//...
});
});
Either do:
jQuery.noConflict();
jQuery(function($) {
$('.Submit')...
)};
or
$(function() {
$('.Submit')...
)};
This part in the click handler:
var id = $(this).attr("id");
var name = $(this).attr("name");
var dataString = 'id='+ id ;
var parent = $(this);
var anyBlank = 0;
does not seem to do anything. Besides that, the submit button has no ID and no name.
Depending on the further structure of your PHP code, you should have a look at the alternative syntax for control structures. It makes easier to mix PHP and HTML without fiddling around with brackets.