Automatic scrolling when clicking my submit button - javascript

So on my custom module that I've created, there's a submit button (form defined in php) but it already acquires an action where it calls a callback function to trigger the display of some information regarding a certain barcode right below it.
All I want to do is add some code that will allow my submit button to also trigger an automatic scroll down without a link/anchor (because I want the SUBMIT BUTTON to acquire that action, not another link) so that the user doesn't have to scroll down to view the information.
The reason I'm avoiding the link/anchor option is because I just dont want to have a separate entity that needs to be clicked in order to scroll down. I want the scroll to happen right when i click my submit button. Unless a link can be combined with a button? Thanks!
My PHP submit button form:
//submit button that uses ajax (to display whats in callback)
$form['submit_button'] = array(
'#type'=> 'submit',
'#value'=> t('Submit'),
'#ajax' => array( //no need to refresh the page bc ajax
'callback' => '_ibbr_inv_after_callback', //callback
),
'#suffix' => "<div id='after_div'><br></div>
<div id='after_status'></div>",
);
return $form;
My PHP callback function:
//function for submit button callback
function _ibbr_inv_after_callback($form, $form_state) {
$selector = '#after_div';
$commands = array();
$query = new EntityFieldQuery();
$entities = $query->entityCondition('entity_type', 'node')
->propertyCondition('type', 'eq')
->propertyCondition('title', $form_state['input']['barcode'])
->propertyCondition('status', 1)
->range(0,1)
->execute();
//If this barcode is found in database
if (!empty($entities['node'])) {
$node = node_load(array_shift(array_keys($entities['node'])));
//Load fields from returned equipment item
$room = taxonomy_term_load($node->field_eq_room['und'][0]['tid']);
$desc = $node->field_eq_description['und'][0]['value'];
$manu = $node->field_eq_mfr['und'][0]['value'];
$model = $node->field_eq_modelno['und'][0]['value'];
$serial = $node->field_eq_serial['und'][0]['value'];
//displaying all the components of the specific barcode
$info = "<div id='after_div'><b>Title</b>: $node->title<br>
<b>Description</b>: $desc<br>
<b>Manufacturer</b>: $manu<br>
<b>Room</b>: $room->name<br>
<b>Model Number:</b> $model<br>
<b>Serial Number:</b> $serial<br></div>";
//Displaying the Confirm and Flag buttons
$commands[] = ajax_command_replace($selector, $info);
$commands[] = ajax_command_replace("#after_status", "<div id='after_status'> <button id = 'confirm' type = 'submit' name = 'Confirm' value = 'Confirm'> Confirm</button><button id = 'Flag' type = 'submit' name = 'flag' value = 'flag'>Flag </button> </div>");
//$commands[] = ajax_command_invoke("#after_div", 'animate', array("{scrollTop: top}",1000));
//If this barcode is not found in the database
}else {
//Displaying the Add button and "Item not found" ONLY IF this entity is empty (meaning barcode was not found in database)
$commands[] = ajax_command_replace($selector, "<div id = 'after_div'>Item not found.</div>");
$commands[] = ajax_command_replace("#after_status", "<div id='after_status'><button id = 'add' type = 'submit' name = 'Add' value = 'Add'>Add new item</button></div>");
}
return array('#type' => 'ajax', '#commands' => $commands);
}//end _ibbr_inv_after_callback

With javascript you can make your submit button to jump to any HTML element on the page, without link/anchor. Next example has two buttons, when clicked, buttons will scroll down to different points of the page :
<html>
<head>
<script type="text/javascript">
function godown ()
{ document.getElementById("down").scrollIntoView(); // JUMP TO DIV "DOWN".
}
function gobottom ()
{ document.getElementById("bottom").scrollIntoView(); // JUMP TO DIV "BOTTOM".
}
</script>
</head>
<body>
<button onclick="godown()">Click to go down</button>
<button onclick="gobottom()">Click to go bottom</button>
<br/>1<br/>2<br/>3<br/>4<br/>5<br/>6<br/>7<br/>8<br/>9<br/>0<br/>
<br/>1<br/>2<br/>3<br/>4<br/>5<br/>6<br/>7<br/>8<br/>9<br/>0<br/>
<br/>1<br/>2<br/>3<br/>4<br/>5<br/>6<br/>7<br/>8<br/>9<br/>0<br/>
<br/>1<br/>2<br/>3<br/>4<br/>5<br/>6<br/>7<br/>8<br/>9<br/>0<br/>
<br/>1<br/>2<br/>3<br/>4<br/>5<br/>6<br/>7<br/>8<br/>9<br/>0<br/>
<br/>1<br/>2<br/>3<br/>4<br/>5<br/>6<br/>7<br/>8<br/>9<br/>0<br/>
<br/>1<br/>2<br/>3<br/>4<br/>5<br/>6<br/>7<br/>8<br/>9<br/>0<br/>
<br/>1<br/>2<br/>3<br/>4<br/>5<br/>6<br/>7<br/>8<br/>9<br/>0<br/>
<br/>1<br/>2<br/>3<br/>4<br/>5<br/>6<br/>7<br/>8<br/>9<br/>0<br/>
<div id="down">You are down!</div>
<br/>a<br/>b<br/>c<br/>d<br/>e<br/>f<br/>g<br/>h<br/>i<br/>j<br/>
<br/>a<br/>b<br/>c<br/>d<br/>e<br/>f<br/>g<br/>h<br/>i<br/>j<br/>
<br/>a<br/>b<br/>c<br/>d<br/>e<br/>f<br/>g<br/>h<br/>i<br/>j<br/>
<br/>a<br/>b<br/>c<br/>d<br/>e<br/>f<br/>g<br/>h<br/>i<br/>j<br/>
<br/>a<br/>b<br/>c<br/>d<br/>e<br/>f<br/>g<br/>h<br/>i<br/>j<br/>
<br/>a<br/>b<br/>c<br/>d<br/>e<br/>f<br/>g<br/>h<br/>i<br/>j<br/>
<br/>a<br/>b<br/>c<br/>d<br/>e<br/>f<br/>g<br/>h<br/>i<br/>j<br/>
<br/>a<br/>b<br/>c<br/>d<br/>e<br/>f<br/>g<br/>h<br/>i<br/>j<br/>
<br/>a<br/>b<br/>c<br/>d<br/>e<br/>f<br/>g<br/>h<br/>i<br/>j<br/>
<div id="bottom">You are at the bottom!</div>
</body>
</html>
You just insert your information inside a <div> (or a table, or anything you want), give it an "id", and you will be able to scroll down to it with javascript method ".scrollIntoView()".
Copy/paste previous code in a file and save it as HTML, then open it in your browser.
Edit #1 : add some javascript code with PHP right after you fill "after_div" :
$info = "<div id='after_div'><b>Title</b>: $node->title<br>
<b>Description</b>: $desc<br>
<b>Manufacturer</b>: $manu<br>
<b>Room</b>: $room->name<br>
<b>Model Number:</b> $model<br>
<b>Serial Number:</b> $serial<br></div>" .
"<script type='text/javascript'>" .
"document.getElementById('after_div').scrollIntoView();" .
"</script>";
Edit #2 : replace this line :
$commands[] = ajax_command_replace($selector, "<div id = 'after_div'>Item not found.</div>");
by this next one :
$body = "<div id = 'after_div'>Item not found.</div>" .
"<script type='text/javascript'>" .
"document.getElementById('after_div').scrollIntoView();" .
"</script>";
$commands[] = ajax_command_replace($selector, $body);

Related

$(this).attr("data-id") returning undefined

I'm building a webshop and on every item there is a button to add that item to the shopping cart.
<?php
$i = 0;
$path = "../images/women/winter/winter1";
$lang = "description_".get_param();
if(!$result = $db->query("SELECT * FROM cloths;")){
die("There was an error running the query [".$db->error."]");
}
while($winter = $result->fetch_assoc()){
echo "<div class = \"boxsale $winter[image]\">
<img src = \"$path.jpg\"/>
<div class = \"test\"> $winter[$lang] </div>
<select>
<option>S</option>
<option>M</option>
<option>L</option>
<option>XL</option>
<option>XXL</option>
</select>
<button class = \"addToCart\" onclick = \"executeJS()\"> <i class = \"fa fa-shopping-cart\" data-id = \"$i\" aria-hidden=\"true\"></i></button>
</div>";
$i++;
}?>
</div>
when you click on the button the executeJS() in the last few lines gets called from a seperate file.
addToCart.js
function executeJS(){
var id = $(this).attr("data-id");
$.ajax( {
type: "GET",
url: "ajax.php?id=" + id + "&action=add"
})
.done(function(){
alert("Product has been added.");
});
}
i wanted to grab the data-id from the button that has been clicked, with
$(this).attr("data-id"); but all i get is a header that has undefined as data-id.
id=undefined&action=add
can anyone please point me in the right direction?
thanks
The problem is because $(this) is not correctly being applied to the element you're trying to access. When using a string based onclick handler (onclick="test()"), this refers to the window, and NOT the element you're trying to access.
function test() {
console.log(this.id);
}
Link
If you want to use the string based onclick notation, pass your element in explicitly, and do $(element).
<button class = \"addToCart\" onclick = \"executeJS(this)\" data-id = \"$i\" />
Javascript:
function executeJS(element){
var id = $(element).data('id');
...
Personally, skip the attr-id all together, and simply pass your id directly:
<button class = \"addToCart\" onclick = \"executeJS($id)\" />
It looks like this may be pointing to the window instead of the button.
You can fix this by manually looking for the button:
var id = $(".addToCart").attr("data-id");
This will only really work if you only have one button. What you should do is use jquery to attach the event to the button.
In your javascript:
$(".addToCart").click(function(e){
var id = $(e.target).attr("data-id");
$.ajax({
type: "GET",
url: "ajax.php?id=" + id + "&action=add"
})
.done(function(){
alert("Product has been added.");
});
})
The e.target refers to the button that is being clicked.
Use regular function (function(){}) instead of arrow function:
$(document).on("click",".deleteBtn",function(){
//Your Code
});
Since you're using jQuery, this is how you should be doing it. First, remove the inline event handler in your PHP (e.g. onclick = \"executeJS()\")
The other issue is that your buttons don't have a data attribute but their <i> children do.
Next, create your jQuery event handler, binding to the button. By doing this you can use $(this).find('i') to get the fontawesone <i> element and its data attribute, .attr("data-id"):
$('button.addToCart').click(function() {
var id = $(this).find('i').attr("data-id");
$.ajax({
type: "GET",
url: "ajax.php?id=" + id + "&action=add"
})
.done(function() {
alert("Product has been added.");
});
})
jsFiddle example

How to hide content after click "more"?

My HTML Code is like this :
...
#foreach($hotel as $key=>$value)
...
<div class="iteration">
<input type='hidden' value='<?php echo $value['HCode'].'#'.$value['HName'].'#'.$value['CheckIn'].'#'.$value['CheckOut'] ?>' id='tes'>
...
...
{{ $value['HotelNo'] }}
{{ $value['HotelName'] }}
...
<button class="save">More</button>
<div class="loading"></div>
... </div>
#endforeach
...
My Javascript Code is like this :
$(function(){
$('.save').click(function () {
var $parent = $(this).closest('div.iteration');
var bla = $parent.find('.tes:first').val();
console.log(bla);
$parent.find('.loading').html('<img src="http://preloaderss.net/preloaders/287/Filling%20broken%20ring.gif"> loading...');
$.ajax({
type: "GET",
url: "hotel-detail",
success: function (response) {
var elem = $parent.find('.loading').empty(); //remove org content
for(var i=0; i<response.SearchAvailResponse.Hotel.length; i++){ //make sure to use var
elem.append("<p>" + response.SearchAvailResponse.Hotel[i].HotelNo + "</p>"); //add the new content
}
}
});
});
});
When click the "more" button, the system displays the content with the loading process. I want when click the "more" button again, the system hide the content. So when click "more" button, the system displays the contents of the loading process. When click "more" button again, the system hide the content. And so on
How hidden the content after click "more" button?
Any solution to solve my problem?
Thank you very much
You need somehow to remember the state of loading and that the content is shown. For instance you can add some class to the parent element $parent.addClass("is_loading") and then check if ($parent.hasClass("is_loading")) {...} else {...} or use data of element $parent.data("loading", true) and check if ($parent.data("loading")) {...} else {...}. One branch show content and make ajax request, another hide the content. And for example success callback later reset the state $parent.data("loading", false) or $parent.removeClass("is_loading").

Codeigniter ajax call does not work properly

For example if I click 'vote up' button it successfully adds vote for the first post and displays the result in span element with class="rate_votes", but it also displays the same result in all the span elements with same class because of the following line:
$(".rate_votes").text(rate); //
How can I avoid that?
If I use
$(this).text(rate); //
it will not work properly because it does not know which span element to select. Could you help me please.
Here is my view:
<div>
<?php
foreach($results as $row){
$id = $row['id'];
$rate = $row['rate'];
?>
<div>
<?php
$data = array(
'name' => $id,
'class' => 'rate',
'content' => 'Vote Up'
);
echo form_button($data);
?>
<span class="rate_votes" >
<?php echo $rate; ?>
</span>
</div>
</div>
Here is my JS file:
$(document).ready(function() {
$(".rate").click(function(){
var self = this;
$(self).attr("disabled", true);
var id_like = $(self).attr("name");
$.post('filter/get_rate', { id_like: id_like }, function (data) {
var my_obj = data;
$.each(my_obj, function (i) {
var rate = my_obj[i].rate;
$(".rate_votes").text(rate); //
$(self).text("Voted!");
});
}, "json");
});
});
This has nothing to do with codeigniter :)
You bind the click event to an ID, #rate but that ID appears multiple times.
$data = array(
'name' => $id,
'id' => 'rate',
'content' => 'Vote Up'
);
echo form_button($data);
use a class instead.
When you select an ID that appears multiple times, only the first one is selected, thus only the first button works.
EDIT
Your comment sounds a bit strange, Given this code for example :
HTML:
<div class="foo">Foo</div>
<div class="foo">Foo</div>
<div class="foo">Foo</div>
<div class="foo">Foo</div>
Javascript/Jquery
$('.foo').click(function() { $(this).remove() });
The above code only removes the specific div being clicked, That is the event is only fired once and for that element only.
Doublecheck your javascript.
You have used:
$("#rate").click(function(){...})
Here "#rate" is an id and an id must be unique, use class like .rate. If you have multiple elements with same id on the page then only the first element of the page will be counted. So the following code is registering the click handler only on the first element with id rate:
$("#rate").click(function(){
//...
});
Give your elements a class instead, for example:
<button class='rate'>Rate</button>
<button class='rate'>Rate</button>
So this code will work on every button click:
$(".rate").click(function(){
var id_like = $(this).attr("name");
$(this).attr("disabled", true); // disables the current button
$('.rate').attr("disabled", true); // disable all the buttons with class rate
//...
});

How To Fade Out Function With No Unique ID/Class

I don't normally post my server side code but I guess I can post abit to solve this issue,I have a staff page that loops through in a database as I am going to use the database to do other things like deleting/demoting the staff if they did anything wrong and to make the site neater. (don't like demoting staff but in a case I need to)
Anyway I am looping it through with a box what I want now is when one of the boxes are clicked I want it to go to a php page (via a ajax request to delete the user from the database) then hide or fade way by using the hide or fade function.
But the only issue is how can I do this when it's looping through? because the div does not have it's own class or id and I don't think jquery can connect to a database to get a unique id (since it's client side)
Here's some of my code to help
while($staff_info = mysqli_fetch_array($select_staff)) {
$account_name = $staff_info['account_name'];
$position = $staff_info['position'];
$description = $staff_info['description'];
echo "
<div id='staff_boxes'> <text style='float:right;'> <a href='#' class='delete_button'> X </a> </text>";
echo"
<h2>$account_name</h2>
$position
<p>$description</p>
</div> ";
}
Hoping to get some help and this I search Google but can't find nothing I might be doing it wrong for this type of system
Thanks!
You can give each box a unique id like this with your code:
while($staff_info = mysqli_fetch_array($select_staff)) {
$id = $staff_info['id']; // assuming you have an id field in your DB
$account_name = $staff_info['account_name'];
$position = $staff_info['position'];
$description = $staff_info['description'];
echo "
<div id='staff_boxes_$id'> <text style='float:right;'> <a href='#' class='delete_button'> X </a> </text>";
echo"
<h2>$account_name</h2>
$position
<p>$description</p>
</div> ";
}
Alternatively, you can give all the divs the same class (e.g. <div class="staff_box"> ... </div> then use jQuery like this:
$('.staff_box').each(function(index) {
var box = $(this);
box.children('.delete_button').click(function(event) {
event.stopPropagation();
box.hide();
})
});

How to update content (show/hide) with renderPartial Yii

How do I can update the content within the block "div" which is currently selected combo box?
I've created an action like this :
public function actionDetail()
{
$sql = "
SELECT
tbl_quotation_order.id_quo
, tbl_quotation_order.no_quo
, tbl_produk.nama_produk
, tbl_detail_quo.qty
, tbl_detail_quo.harga_indo_after
, tbl_detail_quo.harga_dolar_after
, tbl_pemasok.nama_pemasok
FROM
tbl_quotation_order
INNER JOIN tbl_detail_quo
ON (tbl_quotation_order.id_detil_quo = tbl_detail_quo.id_quo_fk)
INNER JOIN tbl_produk
ON (tbl_detail_quo.id_produk = tbl_produk.id_produk)
INNER JOIN tbl_pemasok
ON (tbl_produk.id_pemasok = tbl_pemasok.id_pemasok)
WHERE tbl_quotation_order.id_quo='20'";
$dataProvider=new CSqlDataProvider($sql);
$this->render('_detail',array(
'dataProvider'=>$dataProvider,
));
}
When accessed will result in the display :
I want to display a data table containing the data within :
<div id="detailQuo" style="display:none;">
</div>
My jQuery :
$(document).ready(function(){
$("#SelesOrder_id_quo").change(function() {
//Call controller and show the table
$("#detailQuo").show();
});
});
I need a solution to update a different view inside my div on a click event.
Thanks
HTML -
<div id="detailQuo" style="display:none;">
<?php $this->renderPartial('//<controllername>/_detail',array('pageload'=>true)); ?>
</div>
Controller function ->
public function actionDetail()
{
$sql = "
SELECT
tbl_quotation_order.id_quo
, tbl_quotation_order.no_quo
, tbl_produk.nama_produk
, tbl_detail_quo.qty
, tbl_detail_quo.harga_indo_after
, tbl_detail_quo.harga_dolar_after
, tbl_pemasok.nama_pemasok
FROM
tbl_quotation_order
INNER JOIN tbl_detail_quo
ON (tbl_quotation_order.id_detil_quo = tbl_detail_quo.id_quo_fk)
INNER JOIN tbl_produk
ON (tbl_detail_quo.id_produk = tbl_produk.id_produk)
INNER JOIN tbl_pemasok
ON (tbl_produk.id_pemasok = tbl_pemasok.id_pemasok)
WHERE tbl_quotation_order.id_quo='20'";
$dataProvider=new CSqlDataProvider($sql);
$this->renderPartial('_detail',array(
'dataProvider'=>$dataProvider,
));
}
_detail.php
detect page load on $pageload=true and load nothing - while load the stuff you need via ajax in the else case

Categories