I have a below javascript function which updates the display values when I move the slider. However, now I am planning to update the values only on the button click. This is the javascript function.
.on("slider:ready slider:changed", function (event, data) {
var $output =$(this).nextAll(".output:first");
$output.html(data.value.toFixed(2));
masterData[$output.attr("id").replace(/output/,"")] = data.value;
$("#kwBody > tr").each(function() {
var $cells = $(this).children("td");
var found=false,count=0,currentCell;
for (var i=0;i<masterData.length;i++) {
currentCell=$cells.eq(i+1);
found = parseInt(currentCell.text(),10) >=masterData[i];
currentCell.toggleClass("found",found); //add or remove class to highlight
count+=found;
}
window.console && console.log(masterData,count);
$(this).toggle(count==masterData.length); // show if all cells >
});
});
});
I designed a button as below.
<button onclick="myFunction()">Display!</button>
I included the above javascript function inside myfunction(). However, the update is not happening on the button click. A working example can be found here.
EDIT:
<h2>Keyword Scores</h2>
<?php
$i = 0;
while (++$i <= $_SESSION['totalcolumns']-1) {
isset($_GET["slider$i"]) ? $rangevalue=$_GET["slider$i"] : $rangevalue="";
$range = $_SESSION["min-column-$i"] . ',' . $_SESSION["max-column-$i"];?>
<br><?php echo "Keyword" ?>
<?php echo $i ?>
<br><input type="text" data-slider="true" id="slider<?php echo $i; ?>" data-slider-range="<?php echo $range ?>" autocomplete="off" value="<?php echo $rangevalue; ?>" data-slider-step="1">
<meta http-equiv="refresh">
<?php } ?>
<script>
Add an 'id' attribute to the button. Say it is 'myButton'. Now,
I'm assuming that the var masterData is global
Change the slider listener to
.on("slider:ready slider:changed", function (event, data) {
var $output =$(this).nextAll(".output:first");
$output.html(data.value.toFixed(2));
masterData[$output.attr("id").replace(/output/,"")] = data.value;
});
Create a click listener for the button
$("#myButton").click(function (){
$("#kwBody > tr").each(function() {
var $cells = $(this).children("td");
var found=false,count=0,currentCell;
for (var i=0;i<masterData.length;i++) {
currentCell=$cells.eq(i+1);
found = parseInt(currentCell.text(),10) >=masterData[i];
currentCell.toggleClass("found",found); //add or remove class to highlight
count+=found;
}
window.console && console.log(masterData,count);
$(this).toggle(count==masterData.length); // show if all cells >
});
});
Simulate button click on each page load.
$(document).ready(function(){
$("#myButton").click();
});
I haven't tried it, but hopefully, it works.
Related
I'm trying to delete data from database but when I click on delete button then its delete the first row not where I'm clicking.
my PHP Code:
<?php
$connect = mysqli_connect("localhost","root","","abu");
if($connect){
$showdata = mysqli_query($connect,"SELECT * FROM dealers");
if(mysqli_num_rows($showdata)>0){
$i = 1;
while($rows = mysqli_fetch_assoc($showdata)){
echo "<tr>";
echo "<td>".$i."</td>";
echo "<td>".$rows["dealer_name"]."</td>";
echo "<td><button onclick='deleteproduct()' class='delete'>Delete</button><input type='hidden' id='productid' vlaue='".$rows["id"]."'></td>";
echo "</tr>";
$i++;
}
}else {
echo "<center><i>No Dealers to show</i></center>";
}
}
?>
And this is my ajax code:
function deleteproduct(){
if(window.XMLHttpRequest){
http = new XMLHttpRequest();
}else {
http = new ActiveXObject("Microsoft.XMLHTTP");
}
http.onreadystatechange = function(){
if(http.readyState == 4 && http.status == 200){
document.getElementById("alerts").innerHTML = http.responseText;
}
}
var delid = document.getElementById("productid").value;
var file = "assets/php/addproduct_deletedata.php";
var senddata = "productid="+delid;
http.open("POST",file,true);
http.setRequestHeader("content-type","application/x-www-form-urlencoded");
http.send(senddata);
}
I want that when I click on delete button then it delete the row where I clicked not others.
FIRST OF ALL YOU CANNOT ASSIGN THE SAME ID TO MORE THAN ONE ELEMENTS ON A PAGE.
The browser won't mind it but It makes the HTML invalid. You can use class attribute for this purpose.
You can validate your HTML online here
echo "<td><button onclick='deleteproduct()' class='delete'>Delete</button><input type='hidden' id='productid' vlaue='".$rows["id"]."'></td>";
For your requirement, you can use anchor tag instead of using a form with a hidden input field to reduce the DOM size and call the function on click and pass the function the productId as a parameter.
Here's the code:
<?php
$connect = mysqli_connect("localhost","root","","abu");
if($connect){
$showdata = mysqli_query($connect,"SELECT * FROM dealers");
if(mysqli_num_rows($showdata)>0){
$i = 1;
while($rows = mysqli_fetch_assoc($showdata)){
echo "<tr id='row-".$rows["id"]."'>";
echo "<td>".$i."</td>";
echo "<td>".$rows["dealer_name"]."</td>";
echo "<td><a href='#' onclick='return deleteproduct(".$rows["id"].")'>Delete</a></td>";
echo "</tr>";
$i++;
}
}else {
echo "<center><i>No Dealers to show</i></center>";
}
}
?>
JavaScript:
function deleteproduct( delId ){
var tableRowId = 'row-'+delId;
// you got delId and tableRowId to remove the table row
// do ajax stuff here...
return false;
}
Let me know how it went.
because its "value" and not "vlaue" ;)
input type='hidden' id='productid' vlaue='".$rows["id"]."'
2.
you're iterating over your resultset and printing out an input-field with the id "productid".
In your code, EVERY column has the SAME id. Thats the reason your javascript isn't working as expected. An ID needs to be unique.
You need to send the value (product id) as the function parameters. Do it like this:
<input type="hidden" onclick="deleteproduct(this.value)" value="$yourRowId"/>
or
<input type="hidden" onclick="deleteproduct($yourRowId)" />
and this is how you can retrieve the value in JS:
<script type="text/javascript">
function deleteproduct(id)
{
alert(id); // your product ID
}
</script>
I am building a comment system in which there is features like: delete main post, delete comment, delete reply, edit main post, edit comment, edit reply, Read more/Read less for post that is >250 character. So i am now at the stage of making the edit for reply post to a comment, everything else is working perfectly except this one, when i click i need to see reply post with Read More/Read Less feature, so to make this happen after ajax response i needed to paste the javascript codes for this feature in the php script which edit the reply, so when i make .html(data) i see the javascript codes inside the span which i want the response to be shown ! please help ! i made the same script for comment and same way placing javascript code in the php page that edited the comment but i do not see the javascript lines ! below are pictures that shows what is happening and my script next :
// THIS TAKES CARE OF THE EDIT FEATURE OF THE REPLY ON BOARD_COMMENT PAGE
$(document).on("click", ".board_reply_edit_button", function() {
// this will select the form in which is contained the edit button
var editBoardButtonAttribute = $(this).attr("id");
var editBoardButtonIdArray = editBoardButtonAttribute.split("-");
var editBoardButtonId = editBoardButtonIdArray[0];
$("#"+editBoardButtonId+"-formBoardReplyEdit").toggle();
$("#"+editBoardButtonId+"-spanBoardReplyEdit").toggle();
// if the cancel button is clicked, this happens
$(document).on("click", ".board_cancel_button", function() {
// this will select the form in which is contained the edit button
var cancelBoardAttribute = $(this).attr("id");
var cancelBoardButtonIdArray = cancelBoardAttribute.split("-");
var cancelBoardButtonId = cancelBoardButtonIdArray[0];
$("#"+cancelBoardButtonId+"-formBoardReplyEdit").hide();
$("#"+cancelBoardButtonId+"-spanBoardReplyEdit").show();
});
// if the edit button is clicked we send this ajax call
$(document).on("click", ".board_edit_save_button", function(e) {
e.preventDefault();
// this will select the form in which is contained the edit button
var saveBoardAttribute = $(this).attr("id");
var saveBoardButtonIdArray = saveBoardAttribute.split("-");
var saveBoardButtonId = saveBoardButtonIdArray[0];
var editBoardTextareaVal = $("#"+saveBoardButtonId+"-textareaBoardReplyEdit").val();
url = "widgets/edit_board_comment_reply.php";
if (editBoardTextareaVal === "") {
CustomSending("This post can't be left blank")
setTimeout(function () {
$("#sending_box").fadeOut("Slow");
$("#dialogoverlay").fadeOut("Slow");
}, 2000);
// this makes the scroll feature comes back
setTimeout(function(){
$("body").css("overflow", "auto");
}, 2001);
} else {
$.ajax({
url: url,
method: "POST",
data: {
reply_id: saveBoardButtonId,
board_reply_textarea: editBoardTextareaVal
},
beforeSend: function() {
CustomSending("Sending...");
},
success: function(data){
$("#sending_box").fadeOut("Slow");
$("#dialogoverlay").fadeOut("Slow");
// this makes the scroll feature comes back
$("body").css("overflow", "auto");
$("#"+saveBoardButtonId+"-spanBoardReplyEdit").html(data); //// THIS IS THE KEY LINE
$("#"+saveBoardButtonId+"-formBoardReplyEdit").hide();
$("#"+saveBoardButtonId+"-spanBoardReplyEdit").show();
}
});
}
});
});
this is the edit_board_comment_reply.php file :
<?php
require_once '../includes/session.php';
require_once '../includes/functions.php';
require_once '../includes/validation_functions.php';
if(isset($_POST['reply_id'], $_POST['board_reply_textarea'])) {
$reply_id = (int)$_POST['reply_id'];
$board_reply_textarea = mysql_prep($_POST['board_reply_textarea']);
// INSERT into table
$query = "UPDATE board_comment_reply_table ";
$query .= "SET reply = '$board_reply_textarea' ";
$query .= "WHERE reply_id = $reply_id";
$result = mysqli_query($connection, $query);
// now we select the updated board post
$query2 = "SELECT * FROM board_comment_reply_table ";
$query2 .= "WHERE reply_id = $reply_id ";
$result2 = mysqli_query($connection, $query2);
confirm_query($result2);
$result_array = mysqli_fetch_assoc($result2);
}
echo nl2br($result_array['reply']);
?>
<script>
// This takes care of the board comment Continue Reading feature ---------------------------------------------------------
$(".reply_content_span").each(function(){
var boardReplyPostThis = $(this);
var boardPostText = $(this).text();
var boardPostLength = boardPostText.length;
var boardIdAttribute1 = $(this).attr("id");
var boardIdAttributeArray1 = boardIdAttribute1.split("-");
var boardPostId = boardIdAttributeArray1[0];
var boardPostUserId = boardIdAttributeArray1[1];
if(boardPostLength > 250) {
var boardPostTextCut = boardPostText.substr(0, 250);
boardReplyPostThis.text(boardPostTextCut+"...");
boardReplyPostThis.append('<a class="board_read_more_link board_reply_read_more" id="'+boardPostId+'-readMoreComment">Read More</a>');
} else {
boardReplyPostThis.text(boardPostText);
}
$("body").on("click", ".board_reply_read_more", function(e){
e.preventDefault();
boardReplyPostThis.text(boardPostText);
boardReplyPostThis.append('<a class="board_read_more_link board_reply_read_less">Read Less</a>');
});
$("body").on("click", ".board_reply_read_less", function(e){
e.preventDefault();
boardReplyPostThis.text(boardPostTextCut+"...");
boardReplyPostThis.append('<a class="board_read_more_link board_reply_read_more">Read More</a>');
});
});
</script>
This is the html code :
<span class="comment_content_span" id="<?php echo $board_comment_id_number;?>-spanBoardCommentEdit"><?php echo nl2br($board_comment_text);?></span>
<form action="" method="post" class="board_comment_edit_form" id="<?php echo $board_comment_id_number;?>-formBoardCommentEdit">
<textarea rows="2" name="board_comment_edit_textarea" class="board_comment_edit_textarea" id="<?php echo $board_comment_id_number;?>-textareaBoardEdit"><?php echo $board_comment_text;?></textarea>
<input type="submit" value="Edit" class="board_edit_save_button" id="<?php echo $board_comment_id_number;?>-saveBoardCommentEdit"/>
<input type="button" value="Cancel" class="board_cancel_button" id="<?php echo $board_comment_id_number;?>-cancelBoardCommentEdit"/>
</form>
Solution found !
instead of the javascript between the script tags, I added this line in the edit_board_comment_reply.php
<script src="js/board.js"></script>
It seems that the appended javascript exitsts in "data" which is send back from your php script. First of all you should try to define the "dataType" property of your ajax-post because the output is preprocessed by jquery depending on that property.
After that you can try to grab just the content-division from your resonse-html and append that instead of the whole result.
For example like this $(body).append($(data).find('#contentID')).
I want to make one javascript function, but I cannot call my function name right when i click on it(show_more_in_month_0/1/2).
this is my code
$i = 0;
foreach ($data as $row){
echo '<td><span class="glyphicon-plus show_more_in_mont_'.$i.'"></span><span class="glyphicon-minus_'.$i.'"></span></td>';
echo '<td>';
echo $row[0];
echo '</td><td>;
echo $row[1];
echo '</td><td>';
echo $row[2];
echo '</td><tr>';
$i ++;
}
And this is my script, i just want alert my class name after i call right function name
$(document).ready(function() {
$(".show_more_in_mont_'.$i.'.").click(function(){
alert(show_more_in_mont_'.$i.');
});
});
You are doing it wrong -- $i i suppose its your PHP variable ? well you shouldnt have those in your JS..
Just add as javascript one global class such "show-more-container" and use it to show whatever you want to show
$( document ).ready(function() {
$(".show-more-container").click( function() {
var elementId = $(this).data('id');
alert ('show_more_in_mont_'+elementId);
});
});
Now your html should look like
<div data-id="<?= $i ?>" class="show-more-container">
</div>
Hope this make sense to you :)
EDIT:
If you want to go far -- and call that as a function then do as follow:
window['my_fn_name_as_string'+appendId]()
for this to work the function should be on a Global scope -- on Body or Head and not inside Jquery! if you want to add it to jQuery then make sure you use:
$.function() {
window.my_fn_name_as_string_div = function() { }
}
EXAMPLE:
http://jsfiddle.net/7d23y99b/1/
I have three select boxes on a page and when someone selects an option from the 1st box, I want to update the options via ajax for the 2nd box. When someone updates the 2nd box then the 3rd box gets new options via ajax.
The problem I'm having seems to be that when the user updates the first box, I check the DB for the options I need and then in php create the new select box and replace the original one. The problem is, even though the code for the select box is the same, and the id's the same the original javascript which was watching for a change on this 2nd box no longer works.
here's the cakephp/html all the cake stuff is doing is creating select boxes.
<table>
<tr>
<td class="threeCol"><?php echo $this->Form->input('industry', array('type'=>'select', 'options'=>$industries, 'empty'=>'Industry', 'id'=>'industry', 'class'=>'formInputSelect'));?></td>
<td class="threeCol" id="cateWrap"><?php echo $this->Form->input('category', array('type'=>'select', 'options'=>$categories, 'empty'=>'Category', 'id'=>'category', 'class'=>'formInputSelect'));?></td>
<td class="threeCol" id="courseWrap"><?php echo $this->Form->input('course', array('type'=>'select', 'options'=>$courses, 'empty'=>'Course', 'id'=>'course', 'class'=>'formInputSelect'));?></td>
</tr>
</table>
And the javascript I use:
<script type="text/javascript">
$(document).ready(function() {
//Update categories dropdown when inustry selected
$("#industry").change(function() {
if( this.value != "Industry" ) {
$.post("<?php echo $this->webroot;?>categories/selectoptionsupdate", {id:this.value})
.done(function (data) {
$("#cateWrap").html(data);
});
}
});
//Update course dropdown when category selected
$("#category").change(function() {
if( this.value != "Category" ) {
$.post("<?php echo $this->webroot;?>courses/selectoptionsupdate", {id:this.value})
.done(function (data) {
$("#courseWrap").html(data);
});
}
});
});
And finally the php which creates the new box.
//UPdate the options for the dropdown on post new job page
function selectoptionsupdate() {
if ($this->request->is('ajax')) {
$this->layout = 'ajax';
$id = $this->request->data['id'];
$options = $this->Course->find('list', array('conditions'=>array('Course.category_id'=>$id)));
$result = '';
$result .= '<select name="data[Job][course]" id="course" class="formInputSelect">';
$result .= '<option value="">Course</option>';
foreach($options as $k=>$v) {
$result .= '<option value="'.$k.'">'.$v.'</option>';
}
$result .= '</select>';
echo 'hey';
}
}
Whats the best way round this problem?
change the lines
$("#industry").change(function() {
$("#category").change(function() {
for:
$(document).on("change", "#industry", function() {
$(document).on("change", "#category", function() {
http://api.jquery.com/on/
I have the following code which when div clicked converts the div into a dropdown - works perfectly, however, I have "on change" set to submit the form and it passes all data apart from the option selected in the dropdown/select element, any ideas?
This is the js
<script type="text/javascript">
$(document).ready(function(){
var choices = "<select class='choices_dropdown' name='list_name' onchange=\"this.form.submit();\">"+"<option value='My list'>My list</option>"
<?php
// this loads the select element
$wishes4 = mysql_query("select event_id from user_events where user_id = '$userfromcookie'",$db);
while ($databack444 = mysql_fetch_array($wishes4)) { // cc
$wishes5 = mysql_query("select event from events_master where event_id = '$databack444[event_id]'",$db);
$databack555 = mysql_fetch_array($wishes5);
echo "+\"<option value='".$databack555[event]."'>".$databack555[event]."</option>\"";
} // close CC
?>
+"</select>";
$(".update").click(function() {
var $this = $(this),
currentChoice;
// don't continue if there's already a select in this cell
if ($this.find("select").length != 0)
return;
currentChoice = $this.html();
var $choices = $(choices);
$this.empty().append($choices);
$choices.val(currentChoice);
});
$(document).on("change", ".choices_dropdown", function() {
var $this = $(this);
$this.parent().html($this.val());
$('#event_update').submit(); /* this submits the form */
return false;
});
});
</script>
and the html which displays the div is:
echo '<td class="update">
<form action=/list2.html method=post id=event_update>'
.$databack33[list_name].
'<input type="hidden" name="wishlist_id" value='
.$databack33[list_id].
'>
<input type="hidden" name="action" value="update_list">
</form></td>';