send data on click - jquery ajax chat - javascript

I have a jquery chat with script
var name = "Guest";
name = name.replace(/(<([^>]+)>)/ig,"");
var chat = new Chat();
$(function() {
chat.getState();
$("#sendie").keydown(function(event) {
var key = event.which;
if (key >= 33) {
var maxLength = $(this).attr("maxlength");
var length = this.value.length;
if (length >= maxLength) {
event.preventDefault();
}
}
});
$('#sendie').keyup(function(e) {
if (e.keyCode == 13) {
var text = $(this).val();
var maxLength = $(this).attr("maxlength");
var length = text.length;
if (length <= maxLength + 1) {
chat.send("testtext", name);
$(this).val("");
} else {
$(this).val(text.substring(0, maxLength));
}
}
});
});
the html structure is;
<body onload="setInterval('chat.update()', 1000)">
<div id="page-wrap">
<h2>jQuery/PHP Chat</h2>
<p id="name-area"></p>
<div id="chat-wrap"><div id="chat-area"></div></div>
<form id="send-message-area">
<p>Your message: </p>
<textarea id="sendie" maxlength = '100' ></textarea>
<button id="submit">submit</button>
</form>
</div>
</body>
This send (or save to file) message when i hit ENTER key after my message. I have replaced text area data with testtext. I want to send data when i click the submit button.
How can i do this??
I am trying to modify this example.. If anybody got a solution, please let me know.. I am trying to add a button instead of default enter key hit.
Thanks in advance...:)
blasteralfred

Use jQuery's ajax() or post(). For example:
$('#submit').click(function() {
$.ajax({
url: myUrl,
cache: false,
dataType: "json",
data: { 'message' : $('#sendie').val() },
success: function(data){
//...
},
error: function(e, xhr){
//...
}
});
});

Just take the code from $('#sendie').keyup(), create a function and call it from $('#sendie').keyup() and $('#send-message-area').submit()
something like this
var name = "Guest";
name = name.replace(/(<([^>]+)>)/ig,"");
var chat = new Chat();
$(function() {
chat.getState();
$("#sendie").keydown(function(event) {
var key = event.which;
if (key >= 33) {
var maxLength = $(this).attr("maxlength");
var length = this.value.length;
if (length >= maxLength) {
event.preventDefault();
}
}
});
$('#sendie').keyup(function(e) {
if (e.keyCode == 13) {
doSend();
return (false);
}
});
$('#send-message-area').submit(function(e) {
doSend();
return (false);
});
});
function doSend(){
var text = $('#sendie').val();
var maxLength = $('#sendie').attr("maxlength");
var length = text.length;
if (length <= maxLength + 1) {
chat.send("testtext", name);
$('#sendie').val("");
} else {
$('#sendie').val(text.substring(0, maxLength));
}
}

You could try to fire event when submiting a form:
$('#sendie').keyup(function(e, extra) {
if (e.keyCode == 13 || extra.keyCode == 13) {
var text = $(this).val();
var maxLength = $(this).attr("maxlength");
var length = text.length;
if (length <= maxLength + 1) {
chat.send("testtext", name);
$(this).val("");
} else {
$(this).val(text.substring(0, maxLength));
}
}
});
...
$("#send-message-area").submit(){
$('#sendie').trigger('keyup', [{keyCode: 13}]);
return false;
}
the line return false is needed to prevent from reloading Your page.
After update Added a new parameter to keyup function named extra, which will hold the keyCode for event fired "manually".

I solved it by removing chat send from main group and included it in trigger click function as below;
$('#trigger').click(function() {
chat.send("testtext", name);
$(this).val("");
});
Thanks to #Kon, #Piotr Salaciak and #Dutchie432 for their support... :)

Related

My page wont redirect to url using a function

So I have a project, which needs to have a sample login page, using this it was working but now it is not opening the url in the If statement
function validate() {
var usern = document.getElementById("userIn").value;
var passw = document.getElementById("passIn").value;
var position = -1;
var usernArray = ["User1", "User2"];
var passwArray = ["Pass1", "Pass2"];
for (var i=0; i <usernArray.length; i++) {
if ((usern == usernArray[i]) && (passw == passwArray[i])) {
position = i;
break;
}
}
if (position != -1)
{
alert("Login Was Successful!, You are being redirected to the homepage");
window.location.href = 'home.html';
}
else
{
alert("Invalid Username and/or Password! Please try again.")
}
}
You can solve this by adding to the button on your form the attribute: type="button"
<button type="button" onclick="validate()">Login</button>
and your code will work perfectly, but notice that you need to consider the form being submitted also (by pressing Enter button on keyboard). Maybe try changing your code to this:
<script>
$('#form').on('submit', function(e) {
var usern = document.getElementById("userIn").value;
var passw = document.getElementById("passIn").value;
var position = -1;
var usernArray = ["User1", "User2"];
var passwArray = ["Pass1", "Pass2"];
for (var i=0; i <usernArray.length; i++) {
if ((usern == usernArray[i]) && (passw == passwArray[i])) {
position = i;
break;
}
}
if (position != -1)
{
alert("Login Was Successful!, You are being redirected to the homepage");
window.location.href = 'home.html';
}
else
{
alert("Invalid Username and/or Password! Please try again.")
}
e.preventDefault();
return false;
});
</script>
and set the type attribute to your button to submit
Could you try this window.location.href=/home.html so it is relative to the current domain. Or you could try the window.location.replace instead of href.

How to make an if argument on several inputs together?

I have been trying to make an if argument that will check if several inputs(that have the same class) have a value of negative number on several.
If one of them have, I want to have an error message.
I have been trying to do so, and I got the error message that I wanted but it continues to the next step eventhough I wrote return and event.preventDefault.
My Fiddle
My code below:
$("#inventoryForm").submit(function (event) {
$(".inventoryInput").each(function(){
if($(this).val() < 0) {
event.preventDefault();
$("#inventoryError").slideDown().text("blablabla");
;
return;
}
});
});
Your problem comes from the rest of your code. event.preventDefault() will not return out of the submit handler, it will just prevent the default form submit behavior.
Here's what you can do:
$("#inventoryForm").submit(function (event) {
var error = false;
//You seem to always want to prevent the default behavior
event.preventDefault();
$(".inventoryInput").each(function(){
if($(this).val() < 0) {
error = true; //Indicate there was an error
$("#inventoryError").slideDown().text("blablabla");
return false; //This stops the iteration
}
});
//Stop processing if there was an error
if (error) return;
$("#inventorySubmit").hide();
$("#inventoryChange").show();
$("#withdraw").show();
$(".inventoryInput").attr('disabled','disabled');
sum = 0;
/* var money = table.find("td:nth-child(2)");
for (var i = 0; i<money.length; i++) {
}
*/
});
Btw the code is even more consise without jQuery:
var inputs = [].slice.call(document.querySelectorAll('.inventoryInput'));
if (inputs.some(haveValueUnderZero)) {
//error
}
function haveValueUnderZero(input) { return input.value < 0; }
Try this:
<script>
$(".inventoryInput").each(function(){
var el = $(this)
$("#inventoryForm").on("submit", function (event) {
if(el.val() < 0) {
$("#inventoryError").slideDown().text("blablabla");
return false;
}
})
});
try a hidden verify function:
window.verify = function() {
var valid = true;
$('input').each(function() {
if ($(this).val() == "" || $(this).val() < 0) {
valid = false;
}
});
if (valid) {
$('#submit').click();
} else {
alert("Please complete all fields.");
}
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form id="inventoryForm">
<input type="text" placeholder="Product Id" name="prod_id" id="prod_id" />
<input type="number" placeholder="Quantity" name="quantity" id="quantity" />
<button type="button" onclick="verify()">Submit</button>
<button id="submit" type="submit" style="display:none"></button>
</form>
You can use a filter function to return only elements that do not match your condition.
var hasErrorElements = $('.inventoryInput').filter(function() {
return parseInt($(this).val()) < 0;
}).length > 0;
if (hasErrorElements) {
alert('Error!');
event.preventDefault();
return false;
}
Try this:
$("#inventoryForm").submit(function (event) {
event.preventDefault();
$(".inventoryInput").each(function () {
if ($(this).val() < 0) {
$("#inventoryError").slideDown().text("blablabla");
return false;
} else {
$("#inventorySubmit").hide();
$("#withdraw").show();
return true;
}
});
});
Also, you need to insert other functions like $("#withdraw").show(); inside the else statement.
JSFiddle Demo

Stop saving when some fields and table data are empty

On this code, it does not allow to save if any of table cell is empty, however, I want it now to save even the last table cell is null.
How can i add here for last input of table row where type is not
hidden?
$('#myTable tr input[value != add]:text').filter(function () {});
see my FIDDLE
This is my javascript code :
$("#btnSave").click(function (event) {
var flag = false;
var emptyBoxes;
var $rows = $('#myTable tr:not(:hidden)');
$rows.each( function () {
emptyBoxes = $('#myTable tr input[value != add]:text').filter(function () {
return this.value == "";
});
if (emptyBoxes.length != 0) {
flag = true;
}
});
if (flag) {
alert("this cannot be empty");
emptyBoxes.eq(0).focus();
} else
alert("done");
});
Try the following code:
var fields = $('input[type=text]'); /* All fields */
/* This function will find empty fields */
var findEmptyFields = function() {
var n = fields.length - 1;
/* Go throw all inputs with type=text and if someone is empty return index of this element */
for (var i = 0; i < n; i++) {
if (fields.eq(i).val() === '') {
return i;
}
};
/* Else return false that means that we didn't find any empty fields*/
return false;
}
$("#btnSave").on('click', function() {
var empty = findEmptyFields();
if (empty === false) {
alert('Done');
}
else {
alert('Some field is empty');
fields.eq(empty).focus();
}
});

Using submit button to send insted of Enter key

I have this piece of code
// watch textarea for release of key press
$('#sendie').keyup(function(e) {
if (e.keyCode == 13) {
var text = $(this).val();
var maxLength = $(this).attr("maxlength");
var length = text.length;
// send
if (length <= maxLength + 1) {
chat.send(text, name);
$(this).val("");
} else {
$(this).val(text.substring(0, maxLength));
}
}
});
What it does it that it sends a message typed in a textarea to a certain email address once someone hits the enter button. How can i change this to use a submit button as in the code below?
< div id="page-wrap">
< form id="send-message-area">
< p>Your message: </p>
< textarea id="sendie" maxlength = '100' placeholder ="Send Your Message"> < /textarea>
< input type="submit">
< /form>
< /div>
So attach the code to the submission of the form
$("#send-message-area").on("submit", function (e) {
var elem = $("#sendie");
var text = elem.val();
var maxLength = parseInt(elem.attr("maxlength"),10);
var length = text.length;
// send
if (length <= maxLength + 1) {
chat.send(text, name);
elem.val("");
} else {
elem.val(text.substring(0, maxLength));
}
e.preventDefault();
});
$("#send-message-area").on("submit", function (e) {
var text = $("#sendie").val();
var maxLength = $("#sendie").attr("maxlength");
var length = text.length;
// send
if (length <= maxLength + 1) {
chat.send(text, name);
alert(text);
$("#sendie").val("");
} else {
$("#sendie").val(text.substring(0, maxLength));
}
e.preventDefault();
});
check sample here

Switch between two textareas only when pressing Tab button

Normally when a user is visiting a web page and pressing TAB button on a keyboard, the selection moves from one element to another starting from the begining of the page.
I am looking for a solution to switch between two particular text areas by pressing TAB button on a keyboard with an initial focus on the first one when web page is loaded? All other elements on the page have to be ignored for this TAB key press event.
How can I achive this?
Thanx for your help!
= Update =
I have managed to make it work under Firefox 12.0 . IE and Chrome do not work properly. Asuming the text area IDs are #ICCID and #MSISDN, the Jquery looks like this:
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
<script type="text/javascript">
$(function() {
$(document).ready(function() {
$("#ICCID").focus();
});
var $inp = $('.cls');
$inp.bind('keydown', function(e) {
var key = e.which;
if (key == 9) {
e.preventDefault();
var nxtIdx = $inp.index(this) + 1;
$(".cls:eq(" + nxtIdx + ")").focus();
//Simulate Enter after TAB
var textInput = $("#MSISDN").val();
var lines = textInput .split(/\r|\r\n|\n/);
if (lines > 1) {
$("#MSISDN").on("keypress", function(e) {
if (e.keyCode == 9) {
var input = $(this);
var inputVal = input.val();
setTimeout(function() {
input.val(inputVal.substring(0,inputVal.length) + "\n");
}, 1);
}
});
}
}
if (key == 9) {
e.preventDefault();
var nxtIdx = $inp.index(this) - 1;
$(".cls:eq(" + nxtIdx + ")").focus();
//Simulate Enter after TAB
$("#ICCID").on("keypress", function(e) {
if (e.keyCode == 9) {
var input = $(this);
var inputVal = input.val();
setTimeout(function() {
input.val(inputVal.substring(0,inputVal.length) + "\n");
}, 1);
}
});
}
});
});
</script>
Catch the keydown action using jQuery, determine which textarea has focus, and then use the focus() method to set the focus to the other textarea.
Supposing that your textareas have id="textarea1" and id="textarea2". First you can set focus to the first textarea when the page loads by doing : $('#textarea1').focus();
$("body").keypress(function(e) {
var code = (e.keyCode ? e.keyCode : e.which);
switch(code)
{
case 9:
if($("#textarea1").focus()){
//First one has focus, change to second one
$("#textarea2").focus();
}
else if($("#textarea2").focus()) {
//Second one has focus, change to first one
$("#textarea1").focus();
}
}
});
Ok I have found the solution for for my task! It also includes the simulation of ENTER key just after the TAB key event, so user do not need to hit ENTER to go to the new line. Tested with IE9, FF12, Chrome 18.0.x
Here it is:
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
<!-- Switching between ICCIDs and MSISDNs textareas + simulating ENTER key pressing after the TAB key event - START -->
<script type="text/javascript">
$(function() {
$(document).ready(function() {
$("#ICCID").focus();
});
var $inp = $('.cls');
$inp.bind('keydown', function(e) {
var key = e.which;
if (key == 9) {
e.preventDefault();
var nxtIdx = $inp.index(this) + 1;
$(".cls:eq(" + nxtIdx + ")").focus();
//Simulate Enter after TAB
var textInput = $("#MSISDN").val();
var lines = textInput .split(/\r|\r\n|\n/);
if (lines > 1) {
$("#MSISDN").on("keyup", function(e) {
if (e.keyCode == 9 || e.which == 9) {
var input = $(this);
var inputVal = input.val();
setTimeout(function() {
input.val(inputVal.substring(0,inputVal.length) + "\r\n");
}, 1);
}
});
}
}
if (key == 9) {
e.preventDefault();
var nxtIdx = $inp.index(this) - 1;
$(".cls:eq(" + nxtIdx + ")").focus();
//Simulate Enter after TAB
$("#ICCID").on("keyup", function(e) {
if (e.keyCode == 9 || e.which == 9) {
var input = $(this);
var inputVal = input.val();
setTimeout(function() {
input.val(inputVal.substring(0,inputVal.length) + "\r\n");
}, 1);
}
});
}
});
});
</script>
<!-- Switching between ICCIDs and MSISDNs textareas + simulating ENTER key pressing after the TAB key event - END -->
What about this.... Im to bored at work i think..
http://jsbin.com/uqalej/3/
HTML:
<input/>
<textarea id="t1"></textarea>
<textarea id="t2"></textarea>
<input/>
<button onClick='window.toggleBetween=true;'>Init</button>
<button onClick='window.toggleBetween=false;'>Destroy</button>
JS:
var d = document,
t1 = d.getElementById("t1"),
t2 = d.getElementById("t2"),
nodeType, nodeTypes = [],
i, iLen,
y, yLen;
nodeTypes.push( d.getElementsByTagName("textarea") );
nodeTypes.push( d.getElementsByTagName("input") );
nodeTypes.push( d.getElementsByTagName("select") );
i = 0;
iLen = nodeTypes.length;
for ( ; i < iLen; i++ ) {
nodeType = nodeTypes[i];
y = 0;
yLen = nodeType.length;
for ( ; y < yLen; y++ ) {
if ( nodeType[y] != t1 && nodeType[y] != t2 ) {
nodeType[y].onfocus = function() {
if ( window.toggleBetween )
t1.focus();
};
}
}
}
Using javascript on page load:
document.getElementById("textarea1").focus();
document.getElementById('textarea1').tabIndex="1";
document.getElementById('textarea2').tabIndex="2";

Categories