Changing JQuery function from keyup to submit - javascript

I'm not overly familiar with jquery and I'm trying to adapt someone else's code for what I need. Currently, the code submits the contents of a form with a textarea (called "sendie") and other information when the user presses the enter key. I'd like to change that so that the information is submitted when a button is pressed. It seems like it should be simple, but it has me completely stumped. I'm an amateur, this is for a personal project for some friends and I. Any help would be appreciated.
Relevant Code (I think):
// 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, time, filename,);
$(this).val("");
} else {
$(this).val(text.substring(0, maxLength));
}
}
});
<form id="send-message-area">
<textarea id="sendie" maxlength='5000'></textarea>
<br>
<input id="post" type="submit" value="Post" /> //I added this line for the button.
</form>

With jQuery I think you can just do:
$("#post").click(function() {
var text = $("#sendie").val();
var maxLength = $("#sendie").attr("maxlength");
//rest of the code in the if block from the original, replacing $(this) with $("#sendie")
});
This adds a click handler to the button you added with id="post". You might not want it to be a submit type though and rather do button type, but I'm not 100% on that and/or your exact use-case.

Related

How to detect if a specific string (email domain) is entered into an input to add/remove attribute/class from a button

So I know how to do the remove/add class/attribute from a submit button, but I need to be able to apply this to a button based off of entry into an input.
The scenario is this, user enters their email address, but if it's at a specific domain, ex: xxxx#troopers.gov I then want to be able to apply/remove the class, and attribute from the submit button, since this is a domain they are not supposed to enter for a registration.
I have done some similar validation in the past, and tried a few different methods in jQuery .val(), indexOf, etc. But still can't seem to get it working.
I tried something like
var badDomain = 'troopers.gov';
and then
if (!$('#input').val() === badDomain) {
doStuff();
}
but it didn't seem to get me anywhere.
I thought I may be able to do this without using a RegEx (I don't have much experience with that)
Would be nice to be able to account for case as well... and I don't mind if the solution is jQuery, or pure JS... for learning purposes, it would be great to see how I could do it both ways...
So this does what you want, by turning anything typed into the field in lower case and then comparing against a given array of bad strings. Any time the input field blurs, it checks and turns the submit on or off.
Take a look in the code to see some bad addresses for sample use.
var badDomains = [
"troppers.com",
"fooBarBaz.org",
"myReallyUselessDomainName.com",
"a.net"
]
$(function(){
$("#email").on("blur", function(){
var addressBad = false;
var thisEmail = $(this).val().toLowerCase();
for (var i=0; i<badDomains.length; i++){
if (thisEmail.includes(badDomains[i])){
addressBad = true;
}
}
if (addressBad) {
console.log("bad address!")
$(".disabledButton").attr('disabled', "disabled");
} else {
console.log("not a bad address!");
$(".disabledButton").removeAttr("disabled");
}
})
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form>
<label for="email">Email:</label>
<input type="text" name="email" id="email" />
<input class="disabledButton" type="submit" disabled />
</form>
simple workaround :
var email = document.getElementById('email');
var checkEmail = document.getElementById('checkEmail');
checkEmail.onclick = function() {
if ((email.value).includes('#troopers.gov')) alert('This email address cannot be used!');
}
<input id="email">
<button id="checkEmail">Check Email</button>
there are multiple ways around though.
You can use a regex for this purpose.
HTML:
<input type="text" id="InputTest" />
<button id="TestBtn" type="button">
Validate
</button>
<p>
Valid
</p>
CSS:
.valid{
background-color:green;
}
.invalid{
background-color: red;
}
JS:
$("#TestBtn").on("click",function() {
var pattern = /\S+#troopers\.com/gi;
var str = $("#InputTest").val();
var arr = str.match(pattern);
alert(arr); // just to see the value
if(arr !== null){
$("p").addClass("invalid");
}
else{
$("p").addClass("valid");
}
});
Here is a JSFiddle. Basically, if what the user typed in the textbox matches the expression.. then the background color turns red, but if it doesn't match, then the background color turns green.
Let me know if this helps.
You can use the following Regex for the Email property of the related Model in order to accept mails having 'abc.com' suffix:
[RegularExpression("^[a-zA-Z0-9_#./#&+-]+(\\.[a-zA-Z0-9_#./#&+-]+)*#abc.com$",
ErrorMessage = "Please enter an email with 'abc.com' suffix")]

Javascript run onChange not onLoad

I have a very simple piece of Javascript that works perfectly onLoad, but I need it to work onChange.
My script;
<form action="" method="post" name="product_search">
<p><strong>Existing Part Number:</strong>
<input name="v_prodref" type="text" id="v_prodref" size="25" maxlength="25" onChange="searchValue()">
<input type="text" name="prodref" id="prodref">
<input type="submit" name="search_Submit" id="search_Submit" value="Submit">
</p>
<div>
<%=(rs_ProductCheck.Fields.Item("prodref").Value)%>
// <%=(rs_ProductCheck.Fields.Item("proddesc").Value)%></div>
<script>
function searchValue() {
var add = "NW";
var c_ProdRef = document.getElementById('v_prodref');
if(c_ProdRef.search(/GST/i) == -1) {
n_ProdRef = c_ProdRef.concat(add) }
else {
n_ProdRef = c_ProdRef.replace(/GST/i,"NWGST") }
document.getElementById("prodref").value = n_ProdRef;
}
</script>
</form>
So, I enter a part number in the first text box, and I want my javascript to run and enter the new value in the second text box, but it doesn't seem to work.
What am I missing?
search does not exist on an HTMLInputElement. You need to use c_ProdRef.value.search.
(Actually, since you're using it in many places as a string, and never as an input, you probably intended to define c_ProdRef as var document.getElementById('v_prodref').value)
You would've seen this error on load as well.
you want onkeyup if it works perfectly onLoad, and you want to start typing in something in textbox 1 and the javascript to run, you dont want onchange
onchange triggers after blur of focused element
onkeyup triggers after you release a keyboard input
Thanks to everyone for their help. After a little tweaking I have managed to get my code working.
function myFunction() {
var add = "NW";
var c_ProdRef = document.getElementById('v_prodref').value;
if (c_ProdRef.search(/GST/i) == -1) {
n_ProdRef = c_ProdRef.concat(add)
} else {
n_ProdRef = c_ProdRef.replace(/GST/i, "NWGST")
}
document.getElementById("prodref").value = n_ProdRef;
}
Along with #indubitablee suggestion of onKeyup and specifying the .value of my first text field it all works.

Send message from input field into database by pressing enter

i've done a web chat which the codes are:
<div id="namebox">Name: <input type="text" id="name" autofocus autocomplete="on" ></div>
<div id="msgbox" >Message: <input type="text" id="message"></div>
<div id="submitbox"><button onClick="postMessageToDB(); return false;" id="submit">Submit</button></div>
So, the message goes into the database fine by clicking the button submit, however i was wondering to ad a code to jut press enter and it will be sent, so there will be 2 options.
I am using onClick and onKeypress which it is not working.
<div id="submitbox"><button onClick="postMessageToDB(); return false;" id="submit" onkeypress="postMessageToDB(this, event); return false;">Submit</button></div>
Where the javascript is:
<script type="text/javascript">
function postMessageToDB(inputElement, event) {
if (event.keyCode == 13) {
inputElement.div.submit();
}
}
</script>
Im not using form because it was asked to be div, not form.
Really appreciate for any help.
Thank you very much
Your code provided will only work when postMessageToDB() is called... it's not listening for a keypress.
Using jQuery:
$(window).keyup(function(e) {
if( e.keyCode==13 ) {
postMessageToDB([...]);
}
}
You need to call the function, you can do this by adding an EventListener to document and then check if it's enter that was pressed.
var keyevent = (/Firefox/i.test(navigator.userAgent)) ? "keypress" : "keydown"; // fit browser
document.addEventListener(keyevent, function(e) {
if (event.keyCode == 13) {
var a = document.getElementById('name').value; //get field values
var b = document.getElementById('message').value; //get field values
postMessageToDB(inputElement, event); // as I said, not sure what this will do, but you need to get the data you want to pass first within this function.
}
});
Then, just remove the keypress checkup from you function and you should check this line, I can't see that this is going to work:
inputElement.div.submit();

Accessing input fields not working

i have 8 text fields and two textareas in my form.i am trying to access all of them and check whether they are empty or not.But somehow the javascript i wrote is not working.here is the code:
javascript:
function textboxes(formobj)
{
var ip = formobj.getElementsByTagName('input');
for(var i=0; i<ip.length; i++)
{
if(ip[i].value == "")
{
alert("empty field");
ip[i].focus();
return false;
}
}
}
The id of the form is 'genform' and this is passed as an arguement to the above javascript code while the button is clikced :
HTML:
<input type="submit" name="submit" value="Generate Questions"
onclick="return textboxes('genform'); return false;" />
This would be a lot easier with jQuery. Thats for another day :)
The onclick event handler passes the text 'genform' to your function. You have to grab the DOM element from this.
var ip = document.getElementById(formobj).getElementsByTagName('input');

javascript - why doesnt this work?

<form method="post" action="sendmail.php" name="Email_form">
Message ID <input type="text" name="message_id" /><br/><br/>
Aggressive conduct <input type="radio" name="conduct" value="aggressive contact" /><br/><br/>
Offensive conduct <input type="radio" name="conduct" value="offensive conduct" /><br/><br/>
Rasical conduct <input type="radio" name="conduct" value="Rasical conduct" /><br/><br/>
Intimidating conduct <input type="radio" name="conduct" value="intimidating conduct" /><br/><br/>
<input type="submit" name="submit" value="Send Mail" onclick=validate() />
</form>
window.onload = init;
function init()
{
document.forms["Email_form"].onsubmit = function()
{
validate();
return false;
};
}
function validate()
{
var form = document.forms["Email_form"]; //Try avoiding space in form name.
if(form.elements["message_id"].value == "") { //No value in the "message_id"
box
{
alert("Enter Message Id");
//Alert is not a very good idea.
//You may want to add a span per element for the error message
//An div/span at the form level to populate the error message is also ok
//Populate this div or span with the error message
//document.getElementById("errorDivId").innerHTML = "No message id";
return false; //There is an error. Don't proceed with form submission.
}
}
}
</script>
Am i missing something or am i just being stupid?
edit***
sorry i should add! the problem is that i want the javascript to stop users going to 'sendmail.php' if they have not entered a message id and clicked a radio button... at the moment this does not do this and sends blank emails if nothing is inputted
You are using
validate();
return false;
...which means that the submit event handler always returns false, and always fails to submit. You need to use this instead:
return validate();
Also, where you use document.forms["Email form"] the space should be an underscore.
Here's a completely rewritten example that uses modern, standards-compliant, organised code, and works:
http://jsbin.com/eqozah/3
Note that a successful submission of the form will take you to 'sendmail.php', which doesn't actually exist on the jsbin.com server, and you'll get an error, but you know what I mean.
Here is an updated version that dumbs down the methods used so that it works with Internet Explorer, as well as includes radio button validation:
http://jsbin.com/eqozah/5
You forgot the underscore when identifying the form:
document.forms["Email_form"].onsubmit = ...
EDIT:
document.forms["Email_form"].onsubmit = function() {
return validate();
};
function validate() {
var form = document.forms["Email_form"];
if (form.elements["message_id"].value == "") {
alert("Enter Message Id");
return false;
}
var conduct = form.elements['conduct']; //Grab radio buttons
var conductValue; //Store the selected value
for (var i = 0; i<conduct.length; i++) { //Loop through the list and find selected value
if(conduct[i].checked) { conductValue = conduct[i].value } //Store it
}
if (conductValue == undefined) { //Check to make sure we have a value, otherwise fail and alert the user
alert("Enter Conduct");
return false;
}
return true;
}
return the value of validate. Validate should return true if your validation succeeds, and false otherwise. If the onsubmit function returns false, the page won't change.
EDIT: Added code to check the radio button. You should consider using a javascript framework to make your life easier. Also, you should remove the onclick attribute from your submit input button as validation should be handled in the submit even, not the button's click
Most obvious error, your form has name attribute 'Email_form', but in your Javascript you reference document.forms["Email form"]. The ironic thing is, you even have a comment in there not to use spaces in your form names :)

Categories

Resources