Form won't call javascript function when I press enter - javascript

<form id="search" onSubmit="go()">
<input autofocus autocomplete="off" type="text" class="searchbar" id="searchbar" placeholder="Search Keywords: search, navigate, weather" required>
<input type="button" value="Go" class="go" id="go" onclick="go()">
</form>
I have the function in an external javascript document that I have sourced at the bottom of my webpage, the function works when I click the submit button, just not when I hit enter.
My go function:
function go() {
var input = document.getElementById('searchbar').value;
var words = input.split(" ");
var wordsLength = words.length;
var searchWords = '';
if(words[0] == 'search' || words[0] == 'Search') {
for(var x = 1; x < wordsLength; x++) {
searchWords += words[x];
if(x == wordsLength-1) {
} else {
searchWords += '+';
}
}
window.location.replace("http://www.google.com/#q=" + searchWords);
} else if(words[0] == 'navigate' || words[0] == 'Navigate') {
for(var x = 1; x < wordsLength; x++) {
searchWords += words[x];
if(x == wordsLength-1) {
} else {
searchWords += '+';
}
}
window.location.replace("http://www.google.com/maps/place/" + searchWords);
}
}

You need to change
<input type="button" value="Go" class="go" id="go" onclick="go()">
to
<input type="submit">

<form id="search" onsubmit="go()">
<input autofocus autocomplete="off" type="text" class="searchbar" id="searchbar" placeholder="Search Keywords: search, navigate, weather" required>
<input type="submit">
</form>

Your id of the button and the function name is same change one of those.
<form id="search" onSubmit="go()">
<input autofocus autocomplete="off" type="text" class="searchbar" id="searchbar" placeholder="Search Keywords: search, navigate, weather" required>
<input type="button" value="Go" class="go" id="_go" onclick="go()">
</form>

Try this, it is working.
HTML
<form id="search" onSubmit="return false">
<input autofocus autocomplete="off" type="text" class="searchbar" id="searchbar" placeholder="Search Keywords: search, navigate, weather" required>
<input type="button" value="Go" class="go" id="go">
</form>
JavaScript
$('form').keypress(function (e) {
if (e.which == 13) {
go($('#searchbar').val());
$('form#search_form').submit();
return false;
}
});
function go(keyword){
alert('Your search keyword is [' + keyword + ']');
}
Live Example

Try using jQuery solution.
<form id="search">
<input autofocus autocomplete="off" type="text" class="searchbar" id="searchbar" placeholder="Search Keywords: search, navigate, weather" required>
<input type="submit" value="Submit">
</form>
On Form Submit call go().
$(document).ready(function() {
$('#search').submit(function() {
//Add code from go() or just call go()
});
});
UPDATE :
<form id="search" onSubmit="go()">
<input autofocus autocomplete="off" type="text" class="searchbar" id="searchbar" placeholder="Search Keywords: search, navigate, weather" required>
<input type="submit" value="Submit">
</form>
Jquery Part.
$(document).ready(function() {
$('#searchbar').live("keypress", function(e) {
var code = (e.keyCode ? e.keyCode : e.which);
if (code == 13) {
e.preventDefault();
e.stopPropagation();
$(this).closest('form').submit();
}
});
});

Related

Form submit to specific url according to data inserted

I have a form that is simply a input with a zip code and a submit button.
I need some help on submitting the form according to the data inserted.
For example if someone inserts a number between 1000-000 and 2999-999 it will be forward to landing1.html, if the input is between 3000-000 to 4000-999 it will forward to landing2.html and so on.
This is a draft of my code my code for better understanding
$(document).ready(function() {
$(".postal-code").inputmask("9999-999", {
"placeholder": "0"
});
$(".postal-code").inputmask("9999-999", {
"onincomplete": function() {
alert('Insere um Código Postal válido');
}
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://rawgit.com/RobinHerbots/Inputmask/5.x/dist/jquery.inputmask.min.js"></script>
<div id="form-cp">
<form method="get" action="" onsubmit="" class="needs-validation">
<input type="text" name="cp" value="" size="8" maxlength="8" minlength="8" class="postal-code form-control-lg" aria-invalid="false" placeholder="0000-000" required>
<button type="submit" class="btn btn-primary">Send Data</button>
</form>
</div>
Hope someone can help me.
Many thanks!
Like this
We can make it more complex if you have many sets of post codes
$(function() {
$(".postal-code").inputmask("9999-999", {
"placeholder": "0"
});
$(".postal-code").inputmask("9999-999", {
"onincomplete": function() {
alert('Insere um Código Postal válido');
}
});
$(".needs-validation").on("submit",function() {
const cp = this.cp.value;
if (cp >= "1000-000" && cp <= "2999-999") this.action = "landing1.html";
else if (cp >= "3000-000" && cp <= "4000-999") this.action = "landing2.html";
// else this.action = "outofrange.html";
})
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://rawgit.com/RobinHerbots/Inputmask/5.x/dist/jquery.inputmask.min.js"></script>
<div id="form-cp">
<form method="get" action="" onsubmit="" class="needs-validation">
<input type="text" name="cp" value="" size="8" maxlength="8" minlength="8" class="postal-code form-control-lg" aria-invalid="false" placeholder="0000-000" required>
<button type="submit" class="btn btn-primary">Send Data</button>
</form>
</div>

Enable button functionality

I have this form that the functionality is when all the required fields are completed to enable the submit button.
It was working until i added more interaction for a map gallery.
What could be wrong?
Im open to any suggestion or advice.
Im pretty new
Html
<h1>Contact me</h1>
<form action="" id="ContactForm" onsubmit="sConsole(event)">
<fieldset>
<p><label for="fullname">First Name:</label></p>
<input type="text" id="fullname" name="fullname" required />
<p><label for="lastname">Last Name:</label></p>
<input type="text" id="lastname" name="lastname" >
<p><label for="email">Email:</label></p>
<input type="email"id="email" email="email" required />
<p>Comment</p>
<label>
<textarea name="comments" id="comments" cols="30" rows="30" placeholder="Insert your comments here..." required ></textarea>
</label>
<p>Date of birth</p>
<label for="mydate">Pick a date:</label>
<input type="date" id="date" required />
<input type="submit" id="SubmitButton" disabled = "disabled" value="submit" onClick="sConsole()">
</fieldset>
Javascript
ContactForm.addEventListener("input" , () => {
if (fullname.value.length > 0 &&
lastname.value.length > 0 &&
email.value.length > 0 &&
comments.value.length > 0 &&
date.value.length > 0) {
SubmitButton.removeAttribute("disabled");
} else {
SubmitButton.setAttribute("disabled","disabled");
}
});
The new things that i added
const prevBtn = document.querySelector(".prev");
const nextBtn = document.querySelector(".next");
const mapGallery = document.querySelectorAll(".maps-gallery");
let currentlySelected = 0;
prevBtn.addEventListener("click",function(){
mapGallery[currentlySelected].classList.remove("active");
currentlySelected--;
mapGallery[currentlySelected].classList.add("active");
nextBtn.disabled = false
if (currentlySelected === 0){
prevBtn.disabled = true;
}
});
nextBtn.addEventListener("click",function(){
mapGallery[currentlySelected].classList.remove("active");
currentlySelected++;
mapGallery[currentlySelected].classList.add("active");
prevBtn.disabled = false
if (mapGallery.length === currentlySelected +1 ){
nextBtn.disabled = true;
}
});
You need to use
document.getElementById("ContactForm").addEventListener
in the code. In this case, JavaScript needs to know the ID of the element to access.

check atleast 2 of 5 input fields were not empty

How to check of two out of five inputted fields and get the value? I'm using jQuery, and I'm not sure what is the proper positioning of this code. Maybe you guys can help me.
Here is my code:
$(document).ready(function() {
$("#btnSubmit").on('click', function() {
var val = $(".validate");
var res = "";
for (var i = 0; i < val.length; i++) {
if (val[i].value) {
if (i >= 2) {
res = "Code Execution here";
}
}
}
alert(res);
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" class="validate" id="req1" name="req1">
<input type="text" class="validate" id="req2" name="req2">
<input type="text" class="validate" id="req3" name="req3">
<input type="text" class="validate" id="req4" name="req4">
<input type="text" class="validate" id="req5" name="req5">
<button type="button" class="btn" id="btnSubmit" name="submit">Submit</button>
The result that I get is that it only trigger the res variable if the execution reach into 2 above.
I want to submit the form only when there are at least two fields were inputted.
Thanks!
You're checking if any value other than the first two has value
The correct way to implement your check would be:
$(document).ready(function(){
$("#btnSubmit").on('click', function(){
var val = $(".validate");
var res = "";
var reqCount=0
for(var i = 0; i < val.length; i++){
if(val[i].value){
reqCount++;
}
if(reqCount >= 2){
res = "Code Execution here";
}
}
alert(res);
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" class="validate" id="req1" name="req1">
<input type="text" class="validate" id="req2" name="req2">
<input type="text" class="validate" id="req3" name="req3">
<input type="text" class="validate" id="req4" name="req4">
<input type="text" class="validate" id="req5" name="req5">
<button type="button" class="btn" id="btnSubmit" name="submit">Submit</button>
I don't know why there's a C# tag on this question, if you mean to do this on the server side, that'd be a whole different question
Change you logic to count number of filed having value in for loop
than base don count change alert message
$(document).ready(function() {
$("#btnSubmit").on('click', function() {
var val = $(".validate");
var res = ""; let count=0;
for (var i = 0; i < val.length; i++) {
if (val[i].value) {
count++;
}
}
if (count >= 2) {
res = "Code Execution here";
}
alert(res);
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" class="validate" id="req1" name="req1">
<input type="text" class="validate" id="req2" name="req2">
<input type="text" class="validate" id="req3" name="req3">
<input type="text" class="validate" id="req4" name="req4">
<input type="text" class="validate" id="req5" name="req5">
<button type="button" class="btn" id="btnSubmit" name="submit">Submit</button>
If all you want to do is make sure you have atleast 2 feilds filled before the user submits the form , you can do the below:
function isEmpty(validateElem) {
return (validateElem === "" || typeof validateElem === 'undefined') ? true : false;
}
$(function(){
var InputValidateCount = 0;
$('form').submit(function(){
$('input').each(function(e , i){
if(!isEmpty($(this).val())) {
InputValidateCount++;
}
});
if(InputValidateCount < 2) {
return false; // Stop from from submitting;
}
});
});
You should count the validated fields before submission.
Upvote if this answered you. :P
$(document).ready(function() {
$("#btnSubmit").on('click', function() {
var val = $(".validate");
var minimumNonEmptyFields = 2;
var validatedNonEmptyFieldsCount = 0;
for (var i = 0; i < val.length; i++) {
if (val[i].value) {
validatedNonEmptyFieldsCount++;
}
}
if(validatedNonEmptyFieldsCount >= minimumNonEmptyFields) {
alert( validatedNonEmptyFieldsCount + " fields are non-empty");
} else {
alert("Please fill " + (minimumNonEmptyFields - validatedNonEmptyFieldsCount) + " more fields");
}
});
});
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<title>
Validate any 2 input
</title>
</head>
<body>
<input type="text" class="validate" id="req1" name="req1">
<input type="text" class="validate" id="req2" name="req2">
<input type="text" class="validate" id="req3" name="req3">
<input type="text" class="validate" id="req4" name="req4">
<input type="text" class="validate" id="req5" name="req5">
<input type="text" class="validate" id="req6" name="req6">
<button type="button" class="btn" id="btnSubmit" name="submit">Submit</button>
<script></script>
</body>
</html>
if atleast two input is not empty then return true else return false .
if return's true it submit's the form else it will not.
$(document).ready(function() {
$("#btnSubmit").on('click', function() {
var val = $(".validate");
var res = "";
for (var i = 0; i < val.length; i++) {
if (val[i].value) {
if (i >= 2) {
res = "Code Execution here";
console.log("success");
return true;
}
}
}
console.log("fail");
return false;
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" class="validate" id="req1" name="req1">
<input type="text" class="validate" id="req2" name="req2">
<input type="text" class="validate" id="req3" name="req3">
<input type="text" class="validate" id="req4" name="req4">
<input type="text" class="validate" id="req5" name="req5">
<button type="button" class="btn" id="btnSubmit" name="submit">Submit</button>

Text Input To Sentence Case

I have a form whose is saved to the database and generates a PDF.
I want to have the input text transformed to sentence case. Tried style="text-transform:capitalize" but it still save the input as it was typed into the database. How can I do this, perhaps with JavaScript?
<form class="form-style-9" name="litterregistration" id="LitterReg" method="post">
<li>
<input type="text" name="AKennel" required class="field-style field-split align-left" placeholder="Kennel Name" style="text-transform:capitalize" />
<input type="text" name="BDamMother" required class="field-style field-split align-right" placeholder="Dame (Mother)" style="text-transform:capitalize"/>
</li>
<input type="submit" value="Save as PDF" onClick="Onsubmit1();" />
<input type="button" onclick="ClearFormFields()" value="Clear All Fields">
</form
<script>
function Onsubmit1()
{
document.litterregistration.action = "tcpdf/examples/form-litter-regis.php"
return true;
}
</script>
Please, note this is a NOT scalabe solution, and will only work with this specif code
Hi, a few notes first:
- you call a ClearFormFields() function but it isn't build anywhere;
- the name onSubmit1() for the function is not really good.
- You've missed a /> in the form tag.
With this is mind, this should do the (THIS) trick:
Javascript:
<script type="text/javascript">
function mySubmitAction(myAction) {
with (document.getElementById("LitterReg")) {
AKennel.value = AKennel.value.toUpperCase();
BDamMother.value = BDamMother.value.toUpperCase();
}
document.litterregistration.action = myAction;
return true;
}
</script>
HTML
<form class="form-style-9" name="litterregistration" id="LitterReg" method="post">
<li>
<input type="text" name="AKennel" required class="field-style field-split align-left" placeholder="Kennel Name" style="text-transform:capitalize" />
<input type="text" name="BDamMother" required class="field-style field-split align-right" placeholder="Dame (Mother)" style="text-transform:capitalize"/>
</li>
<input type="submit" value="Save as PDF" onclick="mySubmitAction('tcpdf/examples/form-litter-regis.php');" />
<input type="button" onclick="ClearFormFields()" value="Clear all fields" />
</form>
var $input1 = $( '#input-1' );
$.toSentenceCase = function ( value ) {
var val = value.split( ' ' );
for ( var i = 0, l = val.length; i < l; i++ ) {
val[i] = val[i].charAt(0).toUpperCase() + val[i].substr(1);
}
return val.join( ' ' );
}
$input1.on( 'blur', function ( e ) {
var $this = $( this );
$this.val( $.toSentenceCase( $this.val() ) );
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form>
<input type="text" id="input-1">
</form>

Clear out an error message instead of appending with javascript

In this HTML form that I have I would like to warn the user that he has to enter a level in the inputbox, if he clicks the button again I would like to clear off the error message and print it out again. I would like to also add more error messages but anything that I add as an error message appends to the end of the previous message.
function validateForm () {
var msg = ""
, result = true;
if (document.ExamEntry.name.value === "") {
msg = document.createTextNode("You Must Indicate Your Level");
document.getElementById('name-msg').appendChild(msg);
document.getElementById('name-msg').style.color="red";
}
}
<form name="ExamEntry" method="POST">
<input type="text" id="name" name="name">
<span id="name-msg"></span>
<input type="button" name="submit" value="Submit" onclick="validateForm();">
</form>
here's a jsbin
function validateForm () {
var result = true;
if (document.ExamEntry.name.value === "") {
document.getElementById('name-msg').innerHTML= "You Must Indicate Your Level";
document.getElementById('name-msg').style.color="red";
}
}
<form name="ExamEntry" method="POST">
<input type="text" id="name" name="name">
<span id="name-msg"></span>
<input type="button" name="submit" value="Submit" onclick="validateForm();">
</form>
Is this what are you looking for?
function validateForm(){
var result = true;
var msg = "";
if(document.ExamEntry.name.value===""){
msg = document.createTextNode("You Must Indicate Your Level");
var span = document.getElementById('name-msg');
while( span.firstChild ) {
span.removeChild( span.firstChild );
}
span.appendChild(msg)
document.getElementById('name-msg').style.color="red";
} else {
var span = document.getElementById('name-msg');
while( span.firstChild ) {
span.removeChild( span.firstChild );
}
}
}
<form name="ExamEntry" method="POST">
<input type="text" id="name" name="name" /><span id="name-msg"> </span>
<input type="submit" name="submit" value="Submit" onclick="validateForm();" />
</form>
You can clear the html like
function validateForm() {
var result = true;
var msg = "";
if (document.ExamEntry.name.value === "") {
msg = document.createTextNode("You Must Indicate Your Level");
document.getElementById('name-msg').appendChild(msg);
document.getElementById('name-msg').style.color = "red";
} else {
document.getElementById('name-msg').innerHTML = '';
}
}
<form name="ExamEntry" method="POST">
<input type="text" id="name" name="name" /><span id="name-msg"></span>
<input type="button" name="submit" value="Submit" onclick="validateForm();" />
</form>
You may possibly use innerHTML:
function validateForm() {
var msg = "",
result = true;
if (document.ExamEntry.name.value === "") {
msg = "You Must Indicate Your Level";
}
document.getElementById('name-msg').innerHTML = msg;
}
#name-msg {
color: red;
}
<form name="ExamEntry" method="POST">
<input type="text" id="name" name="name">
<span id="name-msg"></span>
<br/>
<input type="button" name="submit" value="Submit" onclick="validateForm();">
</form>

Categories