jQuery keydown function not working - php

I need some help with making the following code work properly:
$('#entry').keydown(function(e) {
alert(e.keyCode);
});
With this textarea field:
<textarea id="entry" placeholder="Type message here"></textarea>
I have checked with adding alerts outside of the brackets, and the document is loaded and works fine. I even extract a series of entries from a database right after this, with no errors.
What I'm looking to cook here is a textfield that when pressing Enter simply sends the .val() of the field to another function responsible for the AJAX request. But obviously I can't get there when I cannot enter the function.

$(function() {
$('#entry').on('keyup', function(e) {
if (e.which == 13) someotherFunction(this.value);
});
});
FIDDLE

Try:
$('#entry').live('keydown',function(e) {
alert(e.keyCode);
});

Related

In PHP how can I detect when a user is deleting text from an input text field

<form action="" method="POST">
<input type="text" name="phonenumber" value="" />
<form>
If there is something written in the input text field and the user start to delete the string meaning the last letter of the string I want to do something.
So something like this:
if(user deletes last letter of isset($_POST['phonenumber'])){
//do something
}
I tried to use strlen() with -1 but did not seem to work. Anyone have any ideas?
Thank you!
You should use javascript to do something when user is deleting char.
One way is to listen to 'keyup' event of the text input. E.g.:
<script>
$(":text[name=phonenumber]").on('keyup', function(event){
if (event.keyCode == 8){ // means BACKSPACE pressed
// do something
}
});
</script>
you can get it by using javascript. on every keyup you have to count the textbox value by id if it is decreasing from the max count means user is deleting some text..
you should use javascript with event keyup ,
jQuery(function($) {
$('input[name=phonenumber]').on('keyup', function(e) {
if(e.keyCode == 46)
{
$.ajax({
type: 'POST',
url : 'url',
data :{'phonenumber': $('input[name=phonenumber]').val()},});
}
});
});

Prevent JQuery Timepicker from displaying using beforeShow

I'm trying to find out the solution of this one but I am not able to find anything yet.There is beforeShow properties for timepicker. What I want to achieve is, before showing up the timepicker I want to do some validation. If the validation is passed, then the timepicker will come up, but if it is fail, then the timepicker will not pop up. How can I achieve this? I tried to put
beforeShow: function(){return false},
but nothing happens
EDIT:
I came across a solution said that remove that field and replace with a new one. Tt works, the timepicker is not showing up anymore. But, if the validation is passed, that field must can be used again. Now i can't. It seems like the text field is not replace with the correct one. Because when I alert the parentNode, it is getting the <td> node, not the <form> node. I put that form in the table. My JS code:
$('input[id^=timepicker]').timepicker({beforeShow: function(instant){
if(!validation){ //validation fail
var element = document.getElementById(instant.id);
var clonedElement = element.cloneNode(true);
var parentElement = element.parentNode;
parentElement.replaceChild(clonedElement, element);
else{
$("#"+instant.id).timepicker();
}
}
});
My HTML is like
<form>
<table>
<tr><td><input type="text" id="timepicker1" name="tp" readonly="true"/></td></tr>
</table>
</form>
Trt this ;
$('.timepicker').timepicker({
beforeShow: function(){
var validation = true;
if(validation){
$.timepicker.hide();
//this one should not be display since there is an error
}
}
});

2Cannot press return to submit form and run JS action

This has got to be easier than I'm making it. I ahve a form that has an onclick action, it runs js that submits the form value to another page. How do I allow users to press return to perform the same action? I've tried some onkeypress stuff, but nothing has worked. Below is the form, and the js being run.
Thanks!
**updated code to reflect more of what I am trying to do..
<script type="text/javascript">
function getQueryValue(name) {
var match = (new RegExp('[?&;]' + name + '=([^&;#]*)')).exec(document.URL);
return match ? unescape(match[1]) : null;
}
var ext = "&ext="+getQueryValue('ext');
</script>
<script src="prototype.js"></script>
<script type="text/javascript">
function checkSubmit(e)
{
if(e && e.keyCode == 13) // if key is enter
{
doSubmit(); // call your submit function
}
}
</script>
</head>
<body>
<div id="dialNumber_form">
<form id="dialer" style="margin-bottom:0;">
<input id="numberBox" name="outnumber" onKeyUp="checkSubmit(event)" type="text">
<input id="submitButton" onsubmit="dosubmit()" type="button"/>
</form>
<div class="clear"></div>
</div>
<div id="success">
</div>
<script type="text/javascript">
function dosubmit( ) {
var par = $('dialer').serialize();
var url = par + ext;
new Ajax.Updater('success', 'dial.php', { method: 'post' , parameters: url , evalScripts: true } );
$('dialer').reset();
}
</script>
</body>
dial.php is taking the number you enter in the field, checking that it's valid, and sending it to our PBX to be dialed. This works, assuming you click the submit button. If you press return (even with the updated code, as recommended below), the page refreshes, and the contents of the outnumber box are posted as GET URL variable, rather than being sent to the dosubmit action. When the form works, you see it stay as it was originally built (dialout.htm?ext={extension number})
Thanks for all the responses. Let me try some of your suggestions, and I'll get back to you.
Not sure I'm clear in what I need to accomplish. This entire thing is being run in an iframe that is passed URL variables. I have no control over that piece, so I need to work with what I've got. When a user opens it, the URL would look something like .../dialout.htm?ext=1234. The extension is used, along with the number entered into the outnumber box, to place a call (system dials extension first, then outnumber). They should be passed to dial.php for processing, and if everything is good, a success response is sent back with the results (and the call is made). This works great if the dial button is clicked. The page does not refresh, and after a short delay, the success box pops up and a call is placed. If enter is pressed, the form refreshes, and the URL changes to .../dialout.htm?outnumber=<number>. I want enter to do what clicking the dial button does. Nothing i've tried here really works for that (unless I'm just really slow..). Any ideas?
You should make your submit button <input type="submit" id="submitButton" etc> then attach an onsubmit handler. jQuery:
$("#dialer").submit(function() {
var result = doMyStuff();
if (result > 10) {
return false; // prevent the submit
}
else {
return true; // allow the submit to happen
}
});
See the jQuery .submit() docs.
Returning false prevents the submit from occurring, true allows it. (I normally wouldn't put a "return false else return true" (return (result<=10);) but wanted to make the true/false sumbit control explicit)
When using AJAX to do the submit you'd want to return false so the normal submit is suppressed.
Update:
Returning false to stop default event processing is, these days, mostly deprecated. Using preventDefault() is generally preferred. This would change my example to be:
$("#dialer").submit(function(event) {
var result = doMyStuff();
if (result > 10) {
event.preventDefault(); // prevent the form submit
}
});
The keyDown / keyUp listener should be on the input not the submit button
<input id="numberBox" name="outnumber" onKeyUp="checkSubmit(event)" type="text">
function checkSubmit(e)
{
if(e && e.keyCode == 13) // if key is enter
{
doSubmit(); // call your submit function
}
}
Working example : http://jsfiddle.net/sVnMy/
This will listen to key presses on the input field and when the enter key is pressed it will submit the form

Collect checkbox values in jQuery and POST them on submit

I've referred to this post:
Post array of multiple checkbox values
And this jQuery forum post:
http://forum.jquery.com/topic/checkbox-names-aggregate-as-array-in-a-hidden-input-value
I am trying to collect an array (or concatenated string with commas, whatever) of checkbox values in a hidden input field using jQuery. Here's the script code I'm using:
<script type="text/javascript">
$("#advancedSearchForm").submit(function() {
var form = this;
$(form).find("input[name=specialty]").val(function() {
return $("input:checkbox",form).map(function() {
return $(this).attr("name");
}).get().join();
});
});
</script>
A snippet of the relevant HTML:
<form id="advancedSearchForm" name="advancedSearchForm" method="post" action="<?php echo site_url('/magcm/advancedSearch#results'); ?>">
<input type="checkbox" name="FCM" id="FCM" class="chk" value="FCM" <?php echo set_checkbox('FCM', 'FCM'); ?>/>
<input type="hidden" name="specialty" id="specialty" value="" />
<input class="button" name="submit3" id="submit3" type="submit" value="Search" />
I've tried changing "submit" to "submit3" in the jQuery, which breaks (obviously). When I print_r($_POST), the checkboxes POST correctly but the condensed hidden variable does not. (It posts, but a blank value.) The checkboxes persist correctly using CI's hacked set_value() function (Derek needs to implement this in the main trunk... but that's another story)
I'm sure I'm doing something that is wrong and easy to point out. I've just been banging my head against the wall for the past 2 hours on it, trying various functions and changing a ton of things and analyzing it in Chrome dev tools (which don't show any errors).
Help is appreciated. :)
Let's say you applied an class, maybe "tehAwesomeCheckboxen" to every checkbox. Then
<script>
$("#advancedSearchForm").submit(function() {
var chkbxValues = $(".tehAwesomeCheckboxen").val();
$("#specialty").val( chkbxValues.join(",") );
});
</script>
EDIT:
I don't think the $_POST array is getting populated, since the submit is being handled locally by the JavaScript engine. SO... let's try this:
<script>
var chkbxValues = new Array();
$(".tehAwesomeCheckboxen").live("change", function(e){
var val = $(this).val();
if( $(this).is(":checked") ) {
if( chkbxValues.length == 0 || chkbxValues.indexOf(val) == -1){
// Add the value
chkbxValues.push(val);
}
}
else {
// remove the value
chkbxValues.splice( chkbxValues.indexOf(val), 1 );
}
$("#specialty").val( chkbxValues.join(",") );
});
</script>
This adds an event handler the checkboxes themselves, such that checking/unchecking the box alters the hidden element. Then your form handles its submission as normal.
Is this more in line with what you're trying to do?
P.S. Those who upvoted this, please note I have modified my answer. Please verify whether you still find it useful and adjust your vote accordingly.
I ended up solving it using PHP arrays rather than jQuery:
<input type="checkbox" name="chk[]" id="RET" class="chk" value="RET" <?php echo set_checkbox('chk', 'RET'); ?>/>
I changed the name to an array and POSTed it to my script, where I looped through the array and handled it there. Still not sure what the problem was with the jQuery-based solutions, but I figured I'd post this for everyone to refer to in the future.
You've got lots of nested functions() in your JavaScript, makes it hard to follow what you're doing.
However, it seems that you're just passing a function to .val() rather than an actual value. Try this instead:
<script type="text/javascript">
$("#advancedSearchForm").submit(function() {
var form = this;
$(form).find("input[name=specialty]").val((function() {
return $("input:checkbox",form).map(function() {
return $(this).attr("name");
}).get().join();
})());
});
</script>
Or even better, calculate the value first:
<script type="text/javascript">
$("#advancedSearchForm").submit(function() {
var form = this;
var value = $("input:checkbox",form).map(function() {
return $(this).attr("name");
}).get().join();
$(form).find("input[name=specialty]").val(value);
});
</script>

If checkbox changes, use jquery to call php

I have a simple checkbox on a page that allows a user to say if they'd like to receive email notifications. I am using jquery for this to call some php code when the checkbox changes. However, I am not having much luck even calling the jquery function (clicking the checkbox does nothing) let alone test the backend functionality.
Any help in pointing out the error would be great. Thanks.
The checkbox HTML:
<input id="notify_checkbox" type="checkbox" value="y" name="notify">
The jquery:
$('#notify_checkbox').change(function(){
if($('#notify_checkbox').attr('checked'))
{
$.post("/update_notify", { checked: "y", email: "<?php echo $this->session->userdata('email');?>" });
$( "#notifyresult" ).html( "<p>Awesome, we'll send you an email!</p>" );
}
else
{
$.post("/update_notify", { checked: "n", email: "<?php echo $this->session->userdata('email');?>" });
$( "#notifyresult" ).html( "<p>Okay, we won't email you.</p>" );
}
});
And finally the PHP:
function update_notify()
{
// Passed through AJAX
$notify = $_POST[checked];
$email = $_POST[email];
$this->load->model('musers');
$query = $this->musers->update_user_notify($email, $notify);
}
RESOLUTION: The comments below were helpful but not the ultimate solution. The solution was to add the following around my code.
$(document).ready(function() {
{);
Why not use .click() instead?
JSFIDDLE
Also, as you can see in my JSFiddle example, use .is(':checked') instead of attr('checked').
edit after #Rocket commented on your post:
You should indeed quote your $_POST values in your php! Didn't notice it myself, credits to rocket
What's the name of your controller? You need to put that in the URL.
$.post("/controller/update_notify", ...
The problem is with the redefinition of the attr function in jQuery 1.6, and with the difference between attributes and properties.
With attributes (retrieved with attr), the value of checked="checked" or its absence stays the same, regardless of whether the element is actually checked or not.
With properties (retrieved with prop as of jQuery 1.6), the actual state of the element is found. This is equivalent to checking the checked property of the element (which is preferable because you don't need to do a new jQuery selection). The best soltion would be as follows:
if (this.checked) {
See jsFiddles showing this:
your current solution
using prop
using this.checked

Categories