I have an Jquery submit textarea, now I want to set textarea submit without button submit. Just using enter key.
<textarea id="ctextarea"></textarea>
Here it's the JS :
$('.comment_button').live("click",function()
{
var ID = $(this).attr("id");
var uid = $("#uid").val();
var comment= $("#ctextarea"+ID).val();
var dataString = 'comment='+ comment + '&msg_id=' + ID + '&uid=' + uid;
if(comment=='')
{
$('#ctextarea').html("").fadeIn('slow');
$("#ctextarea"+ID).focus();
}
else if (!$.trim($("#ctextarea"+ID).val()))
{
$("#ctextarea"+ID).focus();
}
else
{
$.ajax({
type: "POST",
url: "comment_ajax.php",
data: dataString,
cache: false,
success: function(html){
$("#commentload"+ID).append(html);
$("#ctextarea"+ID).val('');
$("#ctextarea"+ID).focus();
}
});
}
return false;
});
I already search the tutorials and found, but I confused where can I put the code in My JS code.
Someone can give the idea ?
Thanks for helps.
$('#ctextarea').on('keyup', function(e){
if(e.which == 13 || e.keyCode == 13){
//enter key pressed..
}
});
You can subscribe to a keydown/keyup event and submit the form inside the event handler:
var KEY_ENTER = 13;
$('#ctextarea').keyup(function (event) {
if (event.keyCode === KEY_ENTER) {
$('form').submit();
// Or perform any necessary ajax calls here
}
});
Related
I want to handle two operations when I click the enter key after entering text in one textbox.
Two operations are
Move the cursor to the next textbox
Establish a serial communication using php code
$(function() {
$('input:text:first').focus();
var $inp = $('input:text');
$inp.bind('keydown', function(e) {
//var key = (e.keyCode ? e.keyCode : e.charCode);
var key = e.which;
if (key == 13) { // Enter key is pressed
e.preventDefault(); // Prevent the default behaviour of enter key
var nxtIdx = $inp.index(this) + 1;
$(":input:text:eq(" + nxtIdx + ")").focus();
// Ajax query to send request to php
var test = $("#command-text").val();
var inputtext = test;
var command = "1";
// var mode = $(".common-input mb-20").val();
$.ajax({
type: "POST",
url: "controller.php",
data: {
inputtext: inputtext,
command: command
},
cache: false,
success: function(html) {
var feedback = "#" + $("#command-text").val() + "#";
$("#feedback").val(feedback);
}
});
}
});
});
When I tried out with the following code,only one operation is executing,either cursor will move to the next textbox or establish communication.
Kindly help me to solve this issue
Code I tried is as below
You are using incorrect syntax your position of brackets is not correct try this:
$(function() {
$('input:text:first').focus();
var $inp = $('input:text');
$inp.bind('keydown', function(e) {
//var key = (e.keyCode ? e.keyCode : e.charCode);
var key = e.which;
if (key == 13) { // Enter key is pressed
e.preventDefault(); // Prevent the default behaviour of enter key
var nxtIdx = $inp.index(this) + 1;
$(":input:text:eq(" + nxtIdx + ")").focus();
// Ajax query to send request to php
var test = $("#command-text").val();
var inputtext = test;
var command = "1";
// var mode = $(".common-input mb-20").val();
$.ajax({
type: "POST",
url: "controller.php",
data: {
inputtext: inputtext,
command: command
},
cache: false,
success: function(html) {
var feedback = "#" + $("#command-text").val() + "#";
$("#feedback").val(feedback);
}
});
}
});
});
I have created a button on my website when it is clicked, I sent data on some php file using ajax and return the results. The code I am using is below,
My Goal :
When that button is clicked for the first time. I want to send the data on some php file using ajax and return the results, and
When it is clicked for the second time, I just want to hide the content, and
When it is clicked for the third time, I just want to show the container without calling the ajax again.
jQuery:
$(function() {
$('#click_me').click(function(){
var container = $('#container').css('display');
var id = $('#id').html();
if(container == 'none'){
$.ajax({
type: 'POST',
data: {id: id},
url: "ajax/get_items.php",
}).done(function(data) {
$('#container').html(data);
}).success(function(){
$('#container').show('fast');
});
}else if(container == 'block'){
$('#container').hide('fast');
}
});
});
Html :
<input type="button" id="click_me" value="Click Me"/>
<div id="container"></div>
The jQuery way would be like this:
$(function() {
$('#click_me').one('click', function() {
$.ajax({
// ... other params ...,
success: function(result) {
$('#container').html(result).show('fast');
$('#click_me').click(function() {
$('#container').toggle('fast');
});
});
});
});
});
http://api.jquery.com/one/
http://api.jquery.com/toggle/
You can use the counter
http://forum.jquery.com/topic/making-a-number-counter
(function () {
var count = 0;
$('table').click(function () {
count += 1;
if (count == 2) {
// come code
}
});
})();
JQuery Mouse Click counter
Working Example of your code :-
http://jsfiddle.net/2aQ2g/68/
Something like this should do the trick...
$("#click_me").click(function(){
var $btn = $(this);
var count = ($btn.data("click_count") || 0) + 1;
$btn.data("click_count", count);
if ( count == 1 ) {
$.ajax({
var container = $('#container').css('display');
var id = $('#id').html();
if(container == 'none'){
$.ajax({
type: 'POST',
data: {id: id},
url: "ajax/get_items.php"
})
}
else if ( count == 2 ) {
$('#container').hide('fast');
}
else {
$('#container').show('fast');
$btn.unbind("click");
}
return false;
});
One way to do it would be to add a class call count using jQuery every time the user clicks on the button (http://api.jquery.com/addClass/) and you can get the count value in the handler and based on that you can handle the click appropriately.
You can do this by defining a simple variable counting the clicks.
$(function() {
var clickCount = 1; //Start with first click
$('#click_me').click(function(){
switch(clickCount) {
case 1: //Code for the first click
// I am just pasting your code, if may have to change this
var container = $('#container').css('display');
var id = $('#id').html();
if(container == 'none'){
$.ajax({
type: 'POST',
data: {id: id},
url: "ajax/get_items.php",
}).done(function(data) {
$('#container').html(data);
}).success(function(){
$('#container').show('fast');
});
}else if(container == 'block'){
$('#container').hide('fast');
}
break;
case 2:
//code for second click
break;
case 3:
//Code for the third click
break;
});
clickCount++; //Add to the click.
});
still looking for a solution but not find yet, I have a function to manage different forms on same/differents pages
function formStantardAction(correctAnswer,addCustomData){
addCustomData = (typeof addCustomData == "undefined")?'':addCustomData;
correctAnswer = (typeof correctAnswer == "undefined")?'Saved.':correctAnswer;
$('form.standard').submit(function(event){
event.preventDefault();
var modalWin = $(this).parent();
var values = $('form.standard').serialize() + addCustomData;
$.ajax({
url: "inc/gateway.php",
data: values,
type: "POST",
success: function(data){
if (data == "OK"){
$(modalWin).html(correctAnswer).delay(500).fadeOut(500);
setTimeout(function() {
mw_close();
}, 1000);
}else{
alert(data);
}
}
});
});
}
after loaded the page and form with an input type="button" named SEND
$('form.standard [name="SEND"]').click(function(){
var str = $('#sortableTo').serializelist();
formStantardAction('New train inserted.',str);
$('form.standard').submit();
});
all the values reach a php page via POST that made all the things (validating, insert in db, update log...) and answer with 'OK' if all OK (so the form in the modal window is substituted with custom message and fade out) or... if there is an error, php answer with some text that js popups with an alert keeping the modal window open with the form.
It's all ok BUT, if php answer with an error, with second click of button SEND the post is sent 2 times.
And if I make another error on second send, and click again the send button, the post values is sent three time... and so on.
What can I do? Where is my error?
thanks.
Try excluding submit block:
function formStantardAction(correctAnswer,addCustomData){
addCustomData = (typeof addCustomData == "undefined")?'':addCustomData;
correctAnswer = (typeof correctAnswer == "undefined")?'Saved.':correctAnswer;
//$('form.standard').submit(function(event){
// event.preventDefault();
//change 'this' to form.standard
var modalWin = $('form.standard').parent();
var values = $('form.standard').serialize() + addCustomData;
$.ajax({
url: "inc/gateway.php",
data: values,
type: "POST",
success: function(data){
if (data == "OK"){
$(modalWin).html(correctAnswer).delay(500).fadeOut(500);
setTimeout(function() {
mw_close();
}, 1000);
}else{
alert(data);
}
}
});
});
// }
and after loaded page:
$('form.standard [name="SEND"]').click(function(){
var str = $('#sortableTo').serializelist();
formStantardAction('New train inserted.',str);
//excluding submit event
// $('form.standard').submit();
});
Because $.ajax {} with type:"Post" is already a submit process and then when script call submit then it re-submit.
Hope this right and help
Is it possbile that somewhere in your code you bind the submit event to the form everytime you get the data back from the ajax-request?
I can't check this in the code you submitted here.
Create a global variable as flag
var flag = 0;
and check this flag while posting and reset it after completed
function formStantardAction(correctAnswer,addCustomData){
**if(flag == 1){
return false;
}
flag = 1;**
addCustomData = (typeof addCustomData == "undefined")?'':addCustomData;
correctAnswer = (typeof correctAnswer == "undefined")?'Saved.':correctAnswer;
$('form.standard').submit(function(event){
event.preventDefault();
var modalWin = $(this).parent();
var values = $('form.standard').serialize() + addCustomData;
$.ajax({
url: "inc/gateway.php",
data: values,
type: "POST",
success: function(data){
**flag = 0;**
if (data == "OK"){
$(modalWin).html(correctAnswer).delay(500).fadeOut(500);
setTimeout(function() {
mw_close();
}, 1000);
}else{
alert(data);
}
}
});
});
}
I put some custom code at the beginning of your submit function - basically if a submit is in progress nothing should be done, but otherwise return an error message as usual.
var submitting = false; //initialise the variable, this needs to be out of the function!
function formStantardAction(correctAnswer,addCustomData){
addCustomData = (typeof addCustomData == "undefined")?'':addCustomData;
correctAnswer = (typeof correctAnswer == "undefined")?'Saved.':correctAnswer;
$('form.standard').submit(function(event){
if (submitting) {
return false; //if a submit is in progress, prevent further clicks from doing anything
} else {
submitting = true; //no submit in progress, but let's make one now
}
event.preventDefault();
var modalWin = $(this).parent();
var values = $('form.standard').serialize() + addCustomData;
$.ajax({
url: "inc/gateway.php",
data: values,
type: "POST",
success: function(data){
if (data == "OK"){
$(modalWin).html(correctAnswer).delay(500).fadeOut(500);
setTimeout(function() {
mw_close();
}, 1000);
}else{
alert(data);
}
}
});
});
}
I am having great difficulty passing a variable from a PHP file to .js files
The code in the PHP file I used is this:
<script>
jQuery(document).ready(function(){
var uid = <?php echo (intval($uid)); ?>;
//var uid = <?php echo(intval($_SESSION['uid'])); ?>.val();
});
</script>
The variable value should be passed into the .js file to refresh just a certain div on the page (not the whole page) after a form submission is performed.
This is the .js file and the corresponding code starts at "// refresh the monitor list div":
$(function() {
$(".button").click(function() {
// validate and process form here
$('.error').hide();
var domain = $("input#domain").val();
if (domain == "") {
$("label#domain_error").show();
$("input#domain").focus();
return false;
}
var com_domain = $("input#com_domain").val();
if (com_domain == "") {
$("label#com_domain_error").show();
$("input#com_domain").focus();
return false;
}
var cemail = $("input#cemail").val();
var port = $("select#port").val();
var active = $("input#active").val();
var uid = $("input#uid").val();
var main = $("select#main").val();
var dataString = 'cemail='+ cemail + '&domain=' + domain + '&com_domain=' + com_domain + '&active=' + active + '&main=' + main + '&port=' + port;
//alert (dataString);return false;
$.ajax({
type: "POST",
url: "user_add.php",
data: dataString,
success: function() {
$('#monitor_form').append("<div id='message'></div>");
$('#monitor_form form')[0].reset();
$('#message').html("<img id='checkmark' src='images/tick.png' /><b> Monitor sucessfully added!</b>")
.hide()
.fadeIn(500, function() {
$('#message').append("");
});
setTimeout("$('#message').hide().remove();", 6000);
var dataString2 = 'ajax=1&uid=' + uid;
$.ajax({
type: "GET",
url: "monpanel.php",
data: dataString2,
success: function(html_data){
$('#list_monitors').html(html_data);
}
});
//document.onkeydown = showDown;
}
});
return false;
});
});
function showDown(evt) {
event = (evt)? evt : ((event)? event : null);
if (evt) {
if (event.keyCode == 8 && (event.srcElement.type!= "text" && event.srcElement.type!= "textarea" && event.srcElement.type!= "password")) {
// When backspace is pressed but not in form element
cancelKey(evt);
}
else if (event.keyCode == 116) {
// When F5 is pressed
cancelKey(evt);
}
else if (event.keyCode == 122) {
// When F11 is pressed
cancelKey(evt);
}
else if (event.ctrlKey && (event.keyCode == 78 || event.keyCode == 82)) {
// When ctrl is pressed with R or N
cancelKey(evt);
}
else if (event.altKey && event.keyCode==37 ) {
// stop Alt left cursor
return false;
}
}
}
function cancelKey(evt) {
if (evt.preventDefault) {
evt.preventDefault();
return false;
}
else {
evt.keyCode = 0;
evt.returnValue = false;
}
}
/*function mycallbackfunc(v,m,f) {
if (v == 'Cancel') {
$.prompt('The action was ' + v + 'ed');
}
else {
$.prompt('Monitor ' + v + 'd successfully');
}
}*/
// ask for validation on monitor delete, pause, resume request
$(document).ready(function(){
$(".error").hide();
alert("Stage 0! -> uid="+uid.toString());
$("#mondelpau").validate({
debug: false,
rules: {
act: "required",
uid: "required",
sid: "required"
},
/*messages: {
name: "Please let us know who you are.",
email: "A valid email will help us get in touch with you.",
},*/
submitHandler: function(form) {
// do other stuff for a valid form
//$.post('delpaures.php', $("#mondelpau").serialize(),
alert("Stage 1! -> uid="+uid.toString());
$.ajax({
async: false,
type: "POST",
url: "delpaures.php",
data: $("#mondelpau").serialize(),
success: function(data) {
$('#monadiv').html(data);
//$('#results').html(data);
//alert (data);return false;
// refresh the monitor list div
//$('#list_monitors').load(dataString8);
//var uid = $("input#uid").val();
//var dataString8 = 'ajax=1&uid=' + $("input#uid").val();
var dataString8 = 'ajax=1&uid=' + uid; // .val()
//var dataString8 = 'ajax=1&uid=19';
alert("Stage 2! -> uid="+uid.toString());
$.ajax({
async: false,
type: "GET",
dataType: "html",
url: "monpanel.php",
data: dataString8,
success: function(html_data){
alert("Stage 3!");
$("#list_monitors").css("background-color","#FF0000");
$("#list_monitors").html(html_data);
}
});
}
});
}
});
});
Needless to say I have tried everything, even renaming .js file to .php and redirecting to them with .htaccess, but that doesn't work either.
The reason you cannot access the variable in your js file is that the variable 'uid' is defined in a different scope than the js file. Its the same thing as:
if(true) {
var a = 1;
}
if(true) {
// b will be undefined since 'a' was defined in another scope
var b = a;
}
// so
jQuery(document).ready(function({
// this is one scope
var a = 1;
});
jQuery(document).ready(function({
// this is another scope and b will be undefined
var b = a;
});
You need to store the uid in a hidden field like:
<intput type="hidden" id="hidUid" value="<?php echo (intval($uid)); ?>"/>
And then inside the scope of your javascript ($(document).ready)
var uid = $("#hidUid").val();
i have these two jquery scripts on my html page, one of them loads more results(like pagination), and the other one replies to users messages, just like twitter!
the replies works(inserts username into textbox), when the page is on default, but when i load more results, the loaded results wnt insert the username into the textbox!! these are the two scripts,
the replies jquery:
function insertParamIntoField(anchor, param, field) {
var query = anchor.search.substring(1, anchor.search.length).split('&');
for(var i = 0, kv; i < query.length; i++) {
kv = query[i].split('=', 2);
if (kv[0] == param) {
field.val(kv[1]);
return;
}
}
}
$(function () {
$("a.reply").click(function (e) {
insertParamIntoField(this,"status_id",$("#status_id"));
insertParamIntoField(this,"reply_name",$("#reply_name"));
insertParamIntoField(this, "replyto", $("#inputField"));
$("#inputField").focus()
$("#inputField").val($("#inputField").val() + ' ');
e.preventDefault();
return false; // prevent default action
});
});
the loadmore jquery script:
$(function() {
//More Button
$('.more').live("click",function()
{
var ID = $(this).attr("id");
if(ID)
{
$("#more"+ID).html('<img src="moreajax.gif" />');
$.ajax({
type: "POST",
url: "ajax_more.php",
data: "lastmsg="+ ID,
cache: false,
success: function(html){
$("ul.statuses").append(html);
$("#more" + ID).remove();
}
});
}
else
{
$(".morebox").html('The End');
}
return false;
});
});
EDIT: when i load more posts, and i click reply the page is refershed, so that ends up with loaded data being hidden again!!
If the reply button is being replaced by the ajax, this might be a workaround.
$(function () {
$("a.reply").live(click, function (e) {
insertParamIntoField(this,"status_id",$("#status_id"));
insertParamIntoField(this,"reply_name",$("#reply_name"));
insertParamIntoField(this, "replyto", $("#inputField"));
$("#inputField").val($("#inputField").val() + ' ').focus();
e.preventDefault();
});
});
Also... If the status_id, reply_name , replyto info is contained within your reply button, make sure these data exists for each reply button after the more button is clicked.