Using submit button to send insted of Enter key - javascript

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

Related

Removing < > symbols while typing in javascript

I have developed following code. But while typing i need to remove < > these two charectres. Its removing but it removing entire string when we type in middle. I donr want to remove entire string i want remove only < > while typing.
Enter your name:
<input type="text" id="UserC" onkeyup="rem()">
function rem() {
var spclChars = "<>"; // specify special characters
var content = document.getElementById("UserC").value;
for (var i = 0; i < content.length; i++) {
if (spclChars.indexOf(content.charAt(i)) != -1) {
document.getElementById("UserC").value = "";
return false;
}
}
}
You can use regex for that:
var str = 'hello<name>'
function rem(string) {
return string.replace(/<|>/g, '')
}
console.log(rem(str))
this will output helloname.
Use the below code it's working perfectly...
$(document).on('keypress', "#inputid", function(e) {
var check_val = $("#inputid").val();
if ((e.which == 60 || e.which == 62)) { // &lt ascii value is 60 and &gt ascii value is 62
console.log(check_val);
// $(this).attr("placeholder", "digits only");
// $(this).addClass("alert-danger");
$(this).val(check_val);
return false;
} else {
$(this).removeClass("alert-danger");
}
});

JavaScript validation using inputs as array

Hi I am trying to validate my inputs using JavaScript, I have the inputs in an array and I am trying to use them to extract information like .value and set values such as .className. This is not working as I would like it to. What I want the code to do is if I define input[1] = document.forms["register"]["username"]; then use input[1].value it interprets this as if I have written document.forms["register"]["username"].value
Here is my original code:
function validateForm() {
var inputs = [];
inputs[0] = document.forms["register"]["firstname"];
inputs[1] = document.forms["register"]["lastname"];
inputs[2] = document.forms["register"]["username"];
inputs[3] = document.forms["register"]["email"];
inputs[4] = document.forms["register"]["password"];
inputs[5] = document.forms["register"]["confirmpassword"];
for (i = 0; i < inputs.length; i++) {
if (inputs[i].value == null || inputs[i].value == "") {
alert("Highlighted fields must be filled out");
inputs[i].className += " invalid";
return false;
}
}
return true;
}
Here is my updated code, I am unsure of whether this is good practice:
function validateForm() {
var error = false;
var inputs = [];
inputs[0] = document.forms["register"]["firstname"];
inputs[1] = document.forms["register"]["lastname"];
inputs[2] = document.forms["register"]["username"];
inputs[3] = document.forms["register"]["email"];
inputs[4] = document.forms["register"]["password"];
inputs[5] = document.forms["register"]["confirmpassword"];
console.log(inputs.length);
for (i = 0; i < (inputs.length); i++) {
if (inputs[i].value == null || inputs[i].value == "") {
error = true;
inputs[i].className += " invalid";
if (inputs[i] == (inputs.length - 1)) {
alert("Highlighted fields must be filled out");
return false;
}
}
}
if (error == false) {
return true;
}
alert("Highlighted fields must be filled out");
return false;
}
The class invalid adds a red border to the field.
Thanks.
i changed your function a bit to read input elements as in the plnkr link below
https://plnkr.co/edit/zHhM6lmz3XA2u4CYr9h0?p=preview
function validate() {
var inputs = [];
var elements = document.forms["register"].elements;
for (var i = 0; i < elements.length; i++) {
var element = elements[i];
if (element.type === "text" || element.type === "email" || element.type === "password") {
inputs.push(element)
}
}
for (i = 0; i < inputs.length; i++) {
if (inputs[i].value == null || inputs[i].value == "") {
alert("Highlighted fields must be filled out");
inputs[i].className += " invalid";
return false;
}
}
return true;
}
I have handled three input types
text
email
password
You can add more later if needed
Edit: Possible cause of error can be DOM element not available inside the form (please share HTML if possible). First loop will read all available DOM element from the form.
function validateForm() {
var inputs = [];
inputs[0] = document.forms["register"]["firstname"];
inputs[1] = document.forms["register"]["lastname"];
inputs[2] = document.forms["register"]["username"];
inputs[3] = document.forms["register"]["email"];
inputs[4] = document.forms["register"]["password"];
inputs[5] = document.forms["register"]["confirmpassword"];
for (i = 0; i < inputs.length; i++) {
if (inputs[i].value == null || inputs[i].value == "") {
alert("Highlighted fields must be filled out");
inputs[i].className += " invalid";
return false;
}
}
return true;
}

javascript form validation radio buttons

I trying to do some validation on a form with radio buttons in it. I can get the text elements to work fine but the radio buttons don't seem to like me.
function validateAll(theForm)
{
var err=0;
var fields;
for (var i=0; i<theForm.elements.length; i++)
{
fields =theForm.elements[i];
if(fields.type == "text" || fields.type == "textarea")
{
if(fields.value == "" || fields.value == null){
err++;
validateText(fields.id);
}
}
else if(fields.type == "radio"){
validateRadio(fields)
}
}
if(err > 0){return;}else{document.myform.submit();}
}
function validateText(id)
{
var x=document.forms["myForm"][id].value;
if (x==null || x=="")
{
var text = id+"Text";
document.getElementById(text).style.visibility ="visible";
return;
}else {
var text = id+"Text";
document.getElementById(text).style.visibility="hidden";
return;
}
}
function validateRadio(radios)
{
var id = radios.id;
var text;
for (i = -1; i < radios.length; ++i)
{
if (radios[i].checked) {
text = id+"Text";
document.getElementById(text).style.visibility="hidden";
return true
}}
text = id+"Text";
alert(text);
document.getElementById(text).style.visibility ="visible";
return false;
}
I am just calling it with a input button. Any ideas on why its not working? It turns the text on find but dose not turn it off.

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";

send data on click - jquery ajax chat

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... :)

Categories