Pass the specific submitted form to a function with jQuery/Javascript - javascript

I want to intercept a form submission, then pass the form as a variable to a Javascript function, then grab form element values within that specific form. In my example, there could be more than one form with class "formtype". I don't think what I have here is quite correct, but maybe close? How do I reference the specific form that has been submitted, in case of multiple "formtype" class forms?
$('.formtype').on('submit', function(e){
var $submittedform=$(this);
e.preventDefault();
processForm($submittedform);
});
function processForm($submittedform){
var email=$($submittedform+' .email').val();
}

You are pretty close, but use find() instead of the string concatenation
$('.formtype').on('submit', function(e) {
var $submittedform = $(this);
e.preventDefault();
processForm($submittedform);
});
function processForm($submittedform) {
console.log($submittedform.find('input.email').val())
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form class="formtype">
<input class="email" value="foo">
<input type="submit">
</form>
<form class="formtype">
<input class="email" value="bar">
<input type="submit">
</form>

Related

JS Measure the word and take action

How to write a script in Javascript, which will measure the number of characters from the input text field on the form and if it is less than 2 will display an alert when you try to send the form, and if it is more than or equal to 2, will send the form with click send?
There are many ways of achieving this, including:
1- Adding a pattern attribute to your input element:
<form>
<input type="text" pattern=".{2,}">
<input type="submit" value="Submit">
</form>
In this case, if the input is invalid, the form will not submit and display the browser's default error message.
The regular expression .{2,} matches all strings with length 2 or more.
2 - Checking the length of the input value via Javascript, and taking action accordingly:
function validate() {
var text = document.getElementById("input").value;
if(text.length < 2) {
//display an alert or whatever
console.log("invalid");
return false; //form will not submit
}
return true; //form will submit
}
<form onsubmit = "return validate();">
<input type="text" id="input">
<input type="submit" value="Submit">
</form>
Using this method, once the form's submit button is clicked, the function validate() will execute. If the function returns true, the form will submit. If it returns false, the form will not submit.
Method 1 is quicker, while method 2 is more customizable/flexible.
In the submit button inside the form, consider doing the following:
<button onclick="checkValidity()">Submit</button>
And within <script> tags inside the body of the html add the following code:
function checkValidity(){
var val = document.getElementById('inputfield').value; //I'm assuming the id of the input text field to be inputfield
if(val.length<2) window.alert('too short');
}
Another simple way :
HTML :
<form id="form1">
<input id="input2" type="text" placeholder="your text here"></input>
<button type="submit">submit</button>
</form>
JS:
$('#form1').submit(function(event){
if($('#input2').val().length < 2){
event.preventDefault();
alert('ur input text will be more than 1 character');
}
});
Don't forget to import jQuery library before the code :
<script type="text/javascript" src="https://code.jquery.com/jquery-3.4.1.slim.min.js"></script>

JS input validation submit disabled for separate instances

I need each instance of input and submit to operate independently. What is the best way to handle multiple instances where each submit is connected to it's own set of inputs?
Since they are unrelated, would data-attributes be the best solution?
$(document).ready(function() {
validate();
$('input').on('keyup', validate);
});
function validate() {
var inputsWithValues = 0;
var myInputs = $("input:not([type='submit'])");
myInputs.each(function(e) {
if ($(this).val()) {
inputsWithValues += 1;
}
});
if (inputsWithValues == myInputs.length) {
$("input[type=submit]").prop("disabled", false);
} else {
$("input[type=submit]").prop("disabled", true);
}
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="item1">
<div><input type="text" name="name" autocomplete="off" required/></div>
<input type="submit" value="Submit 1" />
</div>
<div class="item2">
<div><input type="text" name="name" autocomplete="off" required/></div>
<div><input type="text" name="name" autocomplete="off" required/></div>
<input type="submit" value="Submit 2" />
</div>
I think your intuition about using data attributes works great here.
var allButtons = document.querySelectorAll("input[type=submit]");
allButtons.forEach(button => {
button.addEventListener("click", () => {
var inputSet = button.getAttribute("data-input-set");
var inputs = document.querySelectorAll("input[type='text'][data-input-set='" + inputSet + "']");
});
});
In the following code, when an input button is pressed, it will fetch all the inputs with the corresponding "input-set" tag.
Preferred way
I think best solution would be use form -tag as it is created for just this use case HTML Forms.
<form id="form-1">
<input type="text"/>
<input type="submit>
</form>
<form id="form-2">
<input type="text"/>
<input type="submit>
</form>
You can also bind custom Form on submit event handlers and collect form data this way.
$('#form-1').on('submit', function(event){
event.preventDefault(); // Prevent sending form as defaulted by browser
/* Do something with form */
});
Possible but more bolt on method
Alternative methods to this would be to create your own function's for collecting all relevant data from inputs and merge some resonable data object.
I would most likely do this with giving desired class -attribute all inputs I would like to collect at once eg. <input type="text" class="submit-1" /> and so on. Get all elements with given class, loop through all them and save values into object.
This requires much more work tho and form -tag gives you some nice validation out of the box which you this way have to do yourself.

Auto Submit When Character reaches a Particular Number in a form isn't Working

This Code Works but when i copy and paste into it, it doesn't submit.
<script src="jquery-3.2.1.min.js"></script>
<form id="Form" action="pro_add_invoice.cfm" method="post">
<input id="here"name="htno" type="text" value="" />
<input id="subHere" type="submit" value="Submit" />
</form>
<script>
$('#here').keyup(function(){
if(this.value.length ==10){
$('#Form').submit();
}
});
</script>
I'm assuming you just want to submit the form after ten characters are entered. You can use $().submit() instead and pass in the id of the form.
<form id="Form" action="sell.cfm" method="post">
<input id="here"name="htno" type="text" value="" />
<input id="subHere" type="submit" value="Submit" />
</form>
<script>
//$('#here').keyup(function(){
// if(this.value.length ==10){
// $('#Form').submit();
// }
//});
var input = document.querySelector('#here');
input.addEventListener('keyup', checkLength);
function checkLength(e){
if(e.target.value.length===10){
document.forms["Form"].submit();
}
}
</script>
If you want to submit the form you cannot use click event handler. That's only for click events. you need to call the submit method of the form element to submit the form.
Change your If statement to execute the following:
Vanilla JS:
document.forms.Form.submit();
or
JQuery:
$('#Form').submit();
SO...
<script>
$('#here').keyup(function(){
if(this.value.length ==10){
$('#Form').submit();
}
});
</script>
I think the problem here is this context is not belong to #here, the scope in the anonymous function (probably) belong to window.
I didn't try it yet but maybe this solve the problem, try change this to ('#here')

HTML form run javascript on enter?

I am building a newtab page here:
http://codepen.io/Thisisntme/full/VvgeyV
This page consists of a pretty design thing, and a google search bar. However, when I press enter, rather than searching google it opens the same window with http://codepen.io/Thisisntme/full/VvgeyV?inputbox=TEST_INPUT ("TEST_INPUT" being whatever was typed into the box).
When I press the submit button off to the left, It actually searches.
How can I make this search when the enter key is pressed?
Here is the code important to the form.
HTML:
<form NAME="myform">
<div id = "textbox">
<INPUT type="text" name="inputbox" value="" placeholder="Search with me!">
</div>
<input type="button" name="button" value="Click" onClick="google(this.form)">
</form>
CSS:
#backgroundstuff canvas {
outline: 0px;
position: fixed;
left: 0px;
top: 0px;
/*width: auto;
height: 100%;*/
z-index: -99;
}
Javascript
function google(form) {
var gSearch = form.inputbox.value;
window.location.href = 'https://www.google.com/search?q=' + gSearch;
//window.location.replace('https://www.google.com/search?q=' + gSearch);
}
The enter key automatically submits the form.
If you do not have an action defined on your form, it will default to the same page.
The posted data will use the name parameter of your form fields.
Using proper form markup will solve both issues.
Setting an action:
<form method="GET" action="https://www.google.com/search">
Setting name to the name of the parameter you want to pass:
<input type="text" name="q" placeholder="Search with me!">
With both of these taken care of, you won't need the google function. Your "search" button can be a simple submit:
<input type="submit" value="Click">
change your html to:
<form NAME="myform" onsubmit="event.preventDefault(); google(this)">
<div id = "textbox">
<INPUT type="text" name="inputbox" value="" placeholder="Search with me!">
</div>
<input type="submit" name="button" value="Click">
</form>
So that it works on the submit of the form not on the click of the button.
Also make sure to cancel the event, like Juan Mendes showed below.
You can do something like:
<form onsubmit="return google(this)">
<input type="text">
<input type="submit">
</form>
And change your google function to:
function google(form) {
// YOUR LOGIC HERE
return false;
}
This way you can implement search results based on keyboard click.
$( "#txtBox" ).keypress(function( event,value ) { if ( event.which == 13 ) { var gSearch = form.inputbox.value; window.location.href = 'https://www.google.com/search?q=' + gSearch; } });
When you hit enter, it submits the form and reloads the page. You need to listen to the form submit event instead of the click. Then you can call event.preventDefault() to prevent the form from being submitted.
<form NAME="myform" onsubmit="event.preventDefault(); google(this)">
However, you don't need JavaScript, just the action attribute of the form to be https://www.google.com/search and make the text field's name be "q"
<form NAME="myform" method="GET" action="https://www.google.com/search">
<input type="text" name="q" placeholder="Search with me!">
Since it is a form pressing enter will launch an event.
This event is what submits your request and reloads the page.
To make it go to google instead you should start by capturing the event and making sure it doesn't bubble up or do anything by default.
To do this, simply add an id to your form and capture the event e.g.
<form name="myform" id="to_cancel_submit">
then in your JS, target the element here
form = document.getElementById('to_cancel_submit')
after you have the form in a variable (or directly, doesn't matter) you bind the submit handler for it and prevent the default events like this
form.submit = function(e) {
e.preventDefault(); // pretty obvious
e.cancelBubble(); // prevents bubbling to parents
return false; // both of the above
// call your functions here...
}

Input Tags and Submit form outside the <form>

I know how to submit a form from outside the form, for example:
<form action="Get?id_sec=120" method="post" id="form15" name="form15" style="display:none"></form>
<input type="submit" class="finish-button primary-button button" border="0" value="Limpar pedido" form="form15" onclick="javascript:document.form15.submit();" />
But I want to put a tag with a reference to the form with javascript too, because command form="example" doesn't work in Internet Explorer.
example:
<input class="input-cep" name="pr001" id="cepfrete" type="text" form="form15"/>
or
<input type="radio" name="tipofrete" value="4" form="form15">`
How can I do that?
Hey Vince, thanks, this works. Very useful help! I need just one other thing. How can I put an input and select in the same form in jQuery?
example:
<input type="text" data-form="dataForm" name="external-input-2">
<Select id="selectField_1" name="selectField_1" data-form="dataForm" >
<option value="52" data-form="dataForm">A</option>
</Select>
To submit a form from outside the form:
HTML
<form id="theForm">...</form>
<button id="submitTheForm">Click to Submit</button>
jQuery
$('#submitTheForm').on('click', function() {
$('#theForm').submit();
});
To include external inputs in the form submission:
HTML
<form id="theForm">...</form>
<button id="submitTheForm">Click to Submit</button>
<input type="text" data-form="theForm" name="external-input-1">
<input type="text" data-form="theForm" name="external-input-2">
jQuery
You can append the external inputs as hidden inputs to the form:
$('#submitTheForm').on('click', function() {
var form = $('#theForm');
$('input[data-form="theForm"]').each(function() {
var input = $(this);
var hidden = $('<input type="hidden"></input>');
hidden.attr('name', input.attr('name'));
hidden.val(input.val());
form.append(hidden);
});
form.submit();
});
I'm not sure that I can completely understand your question but if you are asking how to submit a form externally in different situations, her is my answer.
For the future, just put an id on the form like this.
<form id="form15"></form>
Then to submit this form from anywhere, all you have to do is call the following javascript line in an onclick, a function, etc.
document.getElementById("form15").submit();

Categories