using keypress event in javascript - php

i want to delete php session variable using a key press. so i used these codes,
<script type="text/javascript">
function textsizer(e){
var evtobj=window.event? event : e
var unicode=evtobj.charCode? evtobj.charCode : evtobj.keyCode
var actualkey=String.fromCharCode(unicode)
if(actualkey=="x"){
location.href="biling.php?cmd="+actualkey;}
}
document.onkeypress=textsizer
</script>
<?php if(isset($_GET['cmd'])){
unset($_SESSION["bill_array"]);
header('location:biling.php');
}
?> }
but the problem is, this code also clearing the session when i'm typing "x" in a text box. so i just want to stop that and clear the session only when i press "x" out side of a text box

I think you can edit your existing function as such:
function textsizer(e) {
var evtobj=window.event? event : e;
var element = evtobj.target ? evtobj.target : evtobj.srcElement;
if (element.tagName.toLowerCase() == "body") {
var unicode=evtobj.charCode? evtobj.charCode : evtobj.keyCode;
var actualkey=String.fromCharCode(unicode)
if(actualkey=="x"){
location.href="biling.php?cmd="+actualkey;
}
}
}

You can check the e.target property to identify which element trigger the keypress event.
//Does not work on IE
window.addEventListener('keypress', function(e){ console.log(e.target) }, false)
Taking action when e.target.tagName == 'BODY' is a good choice.
Update
For more info about Event, check:
Firefox & Webkit, https://developer.mozilla.org/en/DOM/event
IE, http://msdn.microsoft.com/en-us/library/ie/ms535863(v=vs.85).aspx

$("input[type='text']").keypress(function(){
});

Related

how to call php function from jqgrid button

I'm trying when i submit a value to jqgrid box on multiple selected rows to Update the data of specific columns.My code is this but when i click OK in jqgrid nothing happens and function is not called :
jQuery(document).ready(function(){
jQuery('#list1').jqGrid('navButtonAdd', '#list1_pager',
{
'caption' : 'Resubmit',
'buttonicon' : 'ui-icon-pencil',
'onClickButton': function()
{
var str = prompt("Please enter data of Column")
var selr = jQuery('#list1').jqGrid('getGridParam','selarrrow');
$(selector).load('Updatestatus.php', {'string': str,'box[]' : selr })
},
'position': 'last'
});
});
The function that updates the column of the table:
function update_data($data)
{
// If bulk operation is requested, (default otherwise)
if ($data["params"]["bulk"] == "set-status")
{
$selected_ids = $data["cont_id"];
$str = $data["params"]["data"];
mysql_query("UPDATE out_$cmpname SET cont_status = '$str' WHERE cont_id IN ($selected_ids)");
die;
}
}
I'm new to jqgrid and Jquery.What can i do to call and execute this function when i click ok?
Thanks in advance!
You'll need a Ajax-call for this. I see you're using jQuery, have a look at http://api.jquery.com/load/
With this function, you can load PHP or HTML with jQuery to a certain element.

prevent user from submitting form

I have my website in which I have email pdf functionality
Procedure is :
when user enters email and then he has to click on submit button
after clicking submit button , form will not submit and form will hide and
there is another hidden div contains thank you message which appears with Ok button.
When User Click on OK button then form will submit.
But Now the Problem is :
When User enter email and if he press ENTER accidentally then form gets submitted without showing thank you message.
I want to Disable ENTER when user Press Enter key.
Check which key was pressed ant if was the enter key return false. Using jQuery this is easy.
var field = $('.classname');
field.keydown(function(e){
if(e.which==13){
return false;
}
});
you can try this to disable the submit on keypress
$(function() {
$("form").on("keypress", function(e) {
if (e.keyCode == 13) return false;
});
});
Use this code, will surely work for you:
var class = $('.classname');
function stopRKey(evt) {
var evt = (evt) ? evt : ((event) ? event : null);
var node = (evt.target) ? evt.target : ((evt.srcElement) ? evt.srcElement : null);
if ((evt.keyCode == 13) && (node.type=="text")) {return false;}
}
class.onkeypress = stopRKey;
Use a regular html button instead of a submit button. In the onclick event of the button write some Javascript to show/hide the DIV. The button on the Thank You DIV make that a submit button.
Place this in the script:
<script language="JavaScript">
function TriggeredKey(e)
{
var keycode;
if (window.event) keycode = window.event.keyCode;
if (window.event.keyCode == 13 ) return false;
}
</script>

how to remember scroll position of page

I am submitting some data to my database then reloading the same page as the user was just on, I was wondering if there is a way to remember the scroll position the user was just on?
I realized that I had missed the important part of submitting, so, I decided to tweak the code to store the cookie on click event instead of the original way of storing it while scrolling.
Here's a jquery way of doing it:
jsfiddle ( Just add /show at the end of the url if you want to view it outside the frames )
Very importantly, you'll need the jquery cookie plugin.
jQuery:
// When document is ready...
$(document).ready(function() {
// If cookie is set, scroll to the position saved in the cookie.
if ( $.cookie("scroll") !== null ) {
$(document).scrollTop( $.cookie("scroll") );
}
// When a button is clicked...
$('#submit').on("click", function() {
// Set a cookie that holds the scroll position.
$.cookie("scroll", $(document).scrollTop() );
});
});
Here's still the code from the original answer:
jsfiddle
jQuery:
// When document is ready...
$(document).ready(function() {
// If cookie is set, scroll to the position saved in the cookie.
if ( $.cookie("scroll") !== null ) {
$(document).scrollTop( $.cookie("scroll") );
}
// When scrolling happens....
$(window).on("scroll", function() {
// Set a cookie that holds the scroll position.
$.cookie("scroll", $(document).scrollTop() );
});
});
#Cody's answer reminded me of something important.
I only made it to check and scroll to the position vertically.
(1) Solution 1:
First, get the scroll position by JavaScript when clicking the submit button.
Second, include this scroll position value in the data submitted to PHP page.
Third, PHP code should write back this value into generated HTML as a JS variable:
<script>
var Scroll_Pos = <?php echo $Scroll_Pos; ?>;
</script>
Fourth, use JS to scroll to position specified by the JS variable 'Scroll_Pos'
(2) Solution 2:
Save the position in cookie, then use JS to scroll to the saved position when page reloaded.
Store the position in an hidden field.
<form id="myform">
<!--Bunch of inputs-->
</form>
than with jQuery store the scrollTop and scrollLeft
$("form#myform").submit(function(){
$(this).append("<input type='hidden' name='scrollTop' value='"+$(document).scrollTop()+"'>");
$(this).append("<input type='hidden' name='scrollLeft' value='"+$(document).scrollLeft()+"'>");
});
Than on next reload do a redirect or print them with PHP
$(document).ready(function(){
<?php
if(isset($_REQUEST["scrollTop"]) && isset($_REQUEST["scrollLeft"]))
echo "window.scrollTo(".$_REQUEST["scrollLeft"].",".$_REQUEST["scrollTop"].")";
?>
});
Well, if you use _targets in your code you can save that.
Or, you can do an ajax request to get the window.height.
document.body.offsetHeight;
Then drop them back, give the variable to javascript and move the page for them.
To Remember Scroll all pages Use this code
$(document).ready(function (e) {
let UrlsObj = localStorage.getItem('rememberScroll');
let ParseUrlsObj = JSON.parse(UrlsObj);
let windowUrl = window.location.href;
if (ParseUrlsObj == null) {
return false;
}
ParseUrlsObj.forEach(function (el) {
if (el.url === windowUrl) {
let getPos = el.scroll;
$(window).scrollTop(getPos);
}
});
});
function RememberScrollPage(scrollPos) {
let UrlsObj = localStorage.getItem('rememberScroll');
let urlsArr = JSON.parse(UrlsObj);
if (urlsArr == null) {
urlsArr = [];
}
if (urlsArr.length == 0) {
urlsArr = [];
}
let urlWindow = window.location.href;
let urlScroll = scrollPos;
let urlObj = {url: urlWindow, scroll: scrollPos};
let matchedUrl = false;
let matchedIndex = 0;
if (urlsArr.length != 0) {
urlsArr.forEach(function (el, index) {
if (el.url === urlWindow) {
matchedUrl = true;
matchedIndex = index;
}
});
if (matchedUrl === true) {
urlsArr[matchedIndex].scroll = urlScroll;
} else {
urlsArr.push(urlObj);
}
} else {
urlsArr.push(urlObj);
}
localStorage.setItem('rememberScroll', JSON.stringify(urlsArr));
}
$(window).scroll(function (event) {
let topScroll = $(window).scrollTop();
console.log('Scrolling', topScroll);
RememberScrollPage(topScroll);
});
I had major problems with cookie javascript libraries, most cookie libraries could not load fast enough before i needed to scroll in the onload event. so I went for the modern html5 browser way of handling this. it stores the last scroll position in the client web browser itself, and then on reload of the page reads the setting from the browser back to the last scroll position.
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function () {
if (localStorage.getItem("my_app_name_here-quote-scroll") != null) {
$(window).scrollTop(localStorage.getItem("my_app_name_here-quote-scroll"));
}
$(window).on("scroll", function() {
localStorage.setItem("my_app_name_here-quote-scroll", $(window).scrollTop());
});
});
</script>
I tackle this via using window.pageYOffset . I saved value using event listener or you can directly call window.pageYOffset. In my case I required listener so it is something like this:
window.addEventListener('scroll', function() {
document.getElementById('showScroll').innerHTML = window.pageYOffset + 'px';
})
And I save latest scroll position in localstorage. So when next time user comes I just check if any scroll value available via localstorage if yes then scroll via window.scrollTo(0,myScrollPos)
sessionStorage.setItem("VScroll", $(document).scrollTop());
var scroll_y = sessionStorage.getItem("VScroll");
setTimeout(function() {
$(document).scrollTop(scroll_y);
}, 300);

Close pop up by clicking on body

I have put javascript and css pop up in my magento application. I can close the pop up by clicking on close button on pop up, but if user clicks elsewhere(out of pop up window) on the page pop up should be closed.
See this question:
Use jQuery to hide a DIV when the user clicks outside of it
var mouse_is_inside = false;
$(document).ready(function()
{
$('.form_content').hover(function(){
mouse_is_inside=true;
}, function(){
mouse_is_inside=false;
});
$("body").mouseup(function(){
if(! mouse_is_inside) $('.form_wrapper').hide();
});
});
So you check if the mouse is inside your popup div, and when it is not, you will close it onclick. If you provide some more code we can help you get that set up
maybe this helps you. I would recommend jQuery but as far as you can't use it maybe thats the solution for you.
<script type="text/javascript">
document.onclick=check;
function check(e){
var target = (e && e.target) || (event && event.srcElement);
var obj = document.getElementById('body');
if(target!=obj){obj.style.display='none'}
}
</script>
And if you have to "toggle" it maybe this helps you:
<script type="text/javascript">
document.onclick=check;
function check(e){
var target = (e && e.target) || (event && event.srcElement);
var obj = document.getElementById('mydiv');
var obj2 = document.getElementById('sho');
if(target!=obj&&target!=obj2){
obj.style.display='none'
}
else if(target==obj2){
obj.style.display='block'
}
}
</script>

Use Jquery to update a PHP session variable when a link is clicked

I have several divs that a user can Minimize or Expand using the jquery toggle mothod. However, when the page is refreshed the Divs go back to their default state. Is their a way to have browser remember the last state of the div?
For example, if I expand a div with an ID of "my_div", then click on something else on the page, then come back to the original page, I want "my_div" to remain expanded.
I was thinking it would be possible to use session variables for this, perhaps when the user clicks on the expand/minimize button a AJAX request can be sent and toggle a session variable...IDK..any ideas?
There's no need for an ajax request, just store the information in a cookie or in the localstorage.
Here's a library which should help you out: http://www.jstorage.info/
Some sample code (untested):
// stores the toggled position
$('#my_div').click(function() {
$('#my_div').toggle();
$.jStorage.set('my_div', $('#my_div:visible').length);
});
// on page load restores all elements to old position
$(function() {
var elems = $.jStorage.index();
for (var i = 0, l = elems.length; i < l; i++) {
$.jStorage.get(i) ? $('#' + i).show() : hide();
}
});
If you don't need to support old browsers, you can use html5 web storage.
You can do things like this (example taken from w3schools):
The following example counts the number of times a user has visited a
page, in the current session:
<script type="text/javascript">
if (sessionStorage.pagecount) {
sessionStorage.pagecount=Number(sessionStorage.pagecount) +1;
}
else {
sessionStorage.pagecount=1;
}
document.write("Visits "+sessionStorage.pagecount+" time(s) this session.");
</script>
Others have already given valid answers related to cookies and the local storage API, but based on your comment on the question, here's how you would attach a click event handler to a link:
$("#someLinkId").click(function() {
$.post("somewhere.php", function() {
//Done!
});
});
The event handler function will run whenever the element it is attached to is clicked. Inside the event handler, you can run whatever code you like. In this example, a POST request is fired to somewhere.php.
I had something like this and I used cookies based on which user logged in
if you want only the main div don't use the
$('#'+div_id).next().css('display','none');
use
$('#'+div_id).css('display','none');
*Here is the code *
//this is the div
<div id = "<?php echo $user; ?>1" onclick="setCookie(this.id)" ><div>My Content this will hide/show</div></div>
function setCookie(div_id)
{
var value = '';
var x = document.getElementById(div_id);
var x = $('#'+div_id).next().css('display');
if(x == 'none')
{
value = 'block';
}
else
{
value = 'none';
}
console.log(div_id+"="+value+"; expires=15/02/2012 00:00:00;path=/")
//alert(x);
document.cookie = div_id+"="+value+"; expires=15/02/2012 00:00:00;path=/";
}
function getCookie(div_id)
{
console.log( div_id );
var i,x,y,ARRcookies=document.cookie.split(";");
for (i=0;i<ARRcookies.length;i++)
{
x=ARRcookies[i].substr(0,ARRcookies[i].indexOf("="));
y=ARRcookies[i].substr(ARRcookies[i].indexOf("=")+1);
x=x.replace(/^\s+|\s+$/g,"");
if (x==div_id)
{
return unescape(y);
}
}
}
function set_status()
{
var div_id = '';
for(var i = 1; i <= 9 ; i++)
{
div_id = '<?php echo $user; ?>'+i;
if(getCookie(div_id) == 'none')
{
$('#'+div_id).next().css('display','none');
}
else if(getCookie(div_id) == 'block')
{
$('#'+div_id).next().slideDown();
}
}
}
$(document).ready(function(){
get_status();
});
Look about the JavaScript Cookie Method, you can save the current states of the divs, and restore it if the User comes back on the Site.
There is a nice jQuery Plugin for handling Cookies (http://plugins.jquery.com/project/Cookie)
Hope it helps
Ended up using this. Great Tutorial.
http://www.shopdev.co.uk/blog/cookies-with-jquery-designing-collapsible-layouts/

Categories