Change input text value in before submitting form - javascript

I'm trying to change the value of my input text field before submitting the form using jQuery like this:
<form actions="http://test.com/" method="GET">
<input name="test" id="autocompleteform" type="text"/>
</form>
<script>
$('#form-customer-attr-new').submit(function(e) {
var value = $("#autocompleteform").val();
value = value.substr(0, value.indexOf(' '));
if (!isNan(value) && !empty(value)) {
$("#autocompleteform").val(value);
alert($("#autocompleteform").val());
return true;
} else {
alert("Invalid Postcode");
return false;
}
});
</script>
when i alert the value of the input file, it's showing the new value, but when the form submitten, the paramether in url still showing the old value of the input, for example:
old_input_value = "1234 justice spoiler message";
new_input_value = "1234";
the_url_after_form_submit_now = "http://test.com?test=1234+justice+spoiler+message";
the_url_after_form_submit_should_be ="http://test.com?test=1234";

<form action="" id="form_id">
<input type="text" name="change_value" id="change_value">
<input type="text" name="d" id="d">
<input type="submit" name="">
</form>
$("#form_id").on("submit", function (e) {
e.preventDefault();//stop submit event
var self = $(this);//this form
$("#change_value").val("deneme");//change input
$("#form_id").off("submit");//need form submit event off.
self.submit();//submit form
});

Couple of things:
id of form was not set, add id="form-customer-attr-new" to form tag
isNan should be isNaN
!empty should be !!
Now it should work. full working example:
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, user-scalable=no,
initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
<script
src="https://code.jquery.com/jquery-3.2.1.min.js"
integrity="sha256-hwg4gsxgFZhOsEEamdOYGBf13FyQuiTwlAQgxVSNgt4="
crossorigin="anonymous"></script>
</head>
<body>
<form actions="http://test.com/" method="GET" id="form-customer-attr-new">
<input name="test" id="autocompleteform" type="text"/>
<input type="submit" />
</form>
<script>
$('#form-customer-attr-new').submit(function(e) {
var value = $("#autocompleteform").val();
value = value.substr(0, value.indexOf(' '));
if (!isNaN(value) && !!(value)) {
$("#autocompleteform").val(value);
alert($("#autocompleteform").val());
return true;
} else {
alert("Invalid Postcode");
return false;
}
});
</script>
</body>

Here is a slightly different approach, but I believe that it should work.
(1) Create a named function for your logic (I corrected/changed some syntax that was problematic)
<script type="text/javascript" language="javascript">
function prepSubmittal()
{
var result = false;
var value = null;
try
{
value = $("#autocompleteform").val();
if(value.indexOf(" ")>-1) value = value.substring(0, value.indexOf(" "));
if (!isNaN(value) && value.trim().length>0)
{
$("#autocompleteform").val(value);
result = true;
}
else
{
alert("Invalid Postcode");
result = false;
}
}
catch(e)
{
result = false;
alert("prepSubmittal Error: " + e.Message);
}
finally
{
}
return result;
}
</script>
(2) Change your form element to the following (note you had actions attribute instead of action and I added onsubmit="return prepSubmittal()")
<form action="http://test.com" method="GET" onsubmit="return prepSubmittal()">
Let me know how it goes.

You submit the form before you change the value. You have to submit the form using jQuery, after you change the value.
Change the submit button to link to jquery function, change all you have to change and then submit form using:
$("#formId").submit();

To accomplish that you need to:
Prevent form submission
Change input value
submit form with jquery $('#form').submit()
Prevent form submission with e.preventDefault() right inside your callback handler

Use your custom submit via ajax. i.e.,
<form id="form-customer-attr-new" actions="http://test.com/" method="GET">
<input name="test" id="autocompleteform" type="text"/>
</form>
<script>
$('#form-customer-attr-new').submit(function(e) {
var value = $("#autocompleteform").val();
value = value.substr(0, value.indexOf(' '));
var urlPost = 'http://test.com/'
if (!isNan(value) && !empty(value)) {
$("#autocompleteform").val(value);
alert($("#autocompleteform").val());
$.ajax({
type: "GET",
url: urlPost+'?test='+value ,
data: '',
dataType: "text",
success: function(resultData){
alert("Save Complete");
}
} else {
alert("Invalid Postcode");
//return false;
}
});
</script>

Submit API for jQuery
The handler will execute as a response to the $('#form-customer-attr-new').submit() (it's a callback function practically), so you will need to move the code from that function to before you do the actual submit.
So move the code right before the jQuery submit() call.
Also, i see that your id is not added to the HTML, please do that as the call will not work otherwise.

Step 1: call a java script function while form submitted
<form onsubmit="return test();">
Step 2: inside test function set value in your text field.
<script>
function test()
{
document.getElementById("myTextFieldId").value = "12345";
return true;
}
</script>

<form id="form-customer-attr-new" action="" method="get">
<input name="test" id="autocompleteform" type="text" value=""/>
</form>
<script>
$('#form-customer-attr-new').submit(function(e) {
var value = $("#autocompleteform").val();
value = value.substr(0, value.indexOf(' '));
if (!isNaN(value) && value!='') {
$("#autocompleteform").val(value);
alert($("#autocompleteform").val());
return true;
} else {
alert("Invalid Postcode");
return false;
}
});
</script>

Related

Input form that will accept string of characters and redirect to URL?

I am attempting to create a form on a page that requires the user to input text. Once the form is submitted by clicking a button it will run sanitizeDomainInput() and redirectLink(domain), the user will then be redirected to the URL in the function redirectLink(). Any advice?
Form example is here
function redirectLink(domain) {
return `https://dashboard.getorda.com/signup/?state=${domain}`
}
function sanitizeDomainInput(input) {
input = input || 'unknown.com'
if (input.startsWith('http://')) {
input = input.substr(7)
}
if (input.startsWith('https://')) {
input = input.substr(8)
}
var regexp = new RegExp(/^(([a-zA-Z]{1})|([a-zA-Z]{1}[a-zA-Z]{1})|([a-zA-Z]{1}[0-9]{1})|([0-9]{1}[a-zA-Z]{1})|([a-zA-Z0-9][a-zA-Z0-9-_]{1,61}[a-zA-Z0-9]))\.([a-zA-Z]{2,6}|[a-zA-Z0-9-]{2,30}\.[a-zA-Z]{2,3})$/)
return regexp.test(input) ? input : 'unknown.com'
}
Your function could change the users location directly:
function redirectLink(domain) {
window.location.href = `https://dashboard.getorda.com/signup/?state=${domain}`
}
Or with a more "redirecty" feel:
function redirectLink(domain) {
window.location.replace = `https://dashboard.getorda.com/signup/?state=${domain}`
}
(reference on window.location)
Basic form
function redirect() {
var x = document.forms["myForm"]["domain"].value;
if (x == "") {
alert("Domain must be filled out");
return false;
} else {
alert(`you entered ${x}`)
}
}
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<form name="myForm" onsubmit="return redirect()">
Domain: <input type="text" name="domain">
<input type="submit" value="Submit">
</form>
</body>
</html>

On Submit, variable that is supposed to change doesn't? Why?

What i am trying to do is when the input is the same as the variable name the user can not press the button 'change' but when the input is different the user is allowed to press the button 'change' and the value name will change but the problem is that the variable is not changing... Why?
Here is the code:
<!DOCTYPE html>
<html>
<head>
<title>App</title>
</head>
<body>
<form id="sendNameForm">
<input id="name" type="text" value="John"/>
<button id="sendNameBtn" type="submit" disabled>Change</button>
</form>
<script src="jquery-1.12.4.js"></script>
<script>
$('#sendNameForm').submit(function() {
var name = $('#name').val();
dis_enableNameSend();
alert("Success!");
return false;
});
var name= $('#name').val();
function dis_enableNameSend(){
var newName = $('#name').val();
if(newName==name){
document.getElementById("sendNameBtn").disabled = true;
}else{
document.getElementById("sendNameBtn").disabled = false;
}
}
$('#name').on('input', function() {
dis_enableNameSend();
});
</script>
</body>
</html>
Thanks!
form submit generally refresh your page by default that may be reason why you do not see change.
try preventing default behaviour
$('#sendNameForm').submit(function(event) {
event.preventDefault()
var name = $('#name').val();
dis_enableNameSend();
alert("Success!");
return false;
});

parsley.js - prevent isValid from firing events / just check true or false

Hello I am at my wit's end and I've been stuck creating a more complex version of the form than the example I provide.
I have JS object that is representation of the form. I use parsley's "isValid" on the form itself (checkAll and checkGroup function). These methods are fired on every input that is marked with data-parsley-required attribute. The reason for this is I need to know the state of the whole form and it's parts so I can enable/disable step buttons.
Everything works fine but I also need to call external API when all validations have successed, see line 35. The methods checkAll and checkGroup are basically firing the events again, thus making more AJAX calls (we have limit on calls to the API). Is there a way to force method isValid to just check if the field has been validated and get true/false value out of it?
The whole thing is coded and depends on this structure so the best way would be to have similar functionality. I'm not so experienced so I make lot of mistakes. My example is very simplified version of my actual form but when you open console window you can see what I mean. Uncomment lines 32 and 33 to see the difference and you will know what I mean.
Example code
HTML:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<title>Document</title>
</head>
<body>
<form action="" id="myform">
<div id="section1">
<input type="text" id="field1" data-parsley-required data-parsley-trigger="input" data-parsley-group="group1" data-parsley-lengthvalidator data-parsley-remote="http://pokeapi.co/api/v2/pokemon/1" data-parsley-remote-validator="remotevalidator" /><br />
<button id="next" disabled>Next</button><br />
</div>
<div id="section2">
<input type="text" id="field2" data-parsley-required data-parsley-trigger="input" data-parsley-group="group2" />
</div>
<input type="submit" id="submit-button" disabled />
</form>
</body>
</html>
JS:
function Form(form) {
this.form = form;
this.validations = {};
this.formValid = false;
this.checkAll = function() {
var result = $(form).parsley().isValid();
if (result) {
$('#submit-button').removeAttr('disabled');
console.log('form validated');
} else {
$('#submit-button').attr('disabled', true);
}
this.formValid = result;
};
this.checkGroup = function(e) {
var group = $(e.target).attr('data-parsley-group');
var result = $(form).parsley().isValid({group: group});
if (result) {
$('#next').removeAttr('disabled');
console.log('group validated');
} else {
$('#next').attr('disabled', true);
}
this.validations[group] = result;
};
this.initialize = function() {
var self = this;
$(this.form).parsley();
$('*[data-parsley-required]').on('input', function(e) {
self.checkAll();
self.checkGroup(e);
});
$('#field1').parsley().on('field:success', function() {
console.log('calling another API')
})
Parsley.addValidator('lengthvalidator', {
validateString: function(value) {
console.log('local validator');
return value.length > 0;
}
});
Parsley.addAsyncValidator('remotevalidator', function(response) {
console.log('remote validator');
return response.responseJSON.name === 'bulbasaur';
})
}
}
var form = new Form('#myform');
form.initialize();

Even after validation failed the new page is redirected

I am implementing a simple code just to figure out why validation is not working in my browser.
But validation is not working. Idk y.
It is just redirecting to next page
newjsp.jsp
<%#page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>JSP Page</title>
<script>
function validation()
{
var a=document.form1.txt1.value;
if(a=="")
{
alert("Hey");
return false;
}
return true;
}
</script>
</head>
<body>
<form id="form1" onsubmit="return validation(this)" action="newjsp1.jsp">
<input type="text" id="txt1">
<input type="submit" id="sub">
</form>
</body>
Use opposite logic - something must be OK, then turn TRUE, in all other cases, return FALSE.
function validation()
{
var a = document.getElementById('txt1').value;
if (typeof a != "undefined" && a != "")
{
// `a` is in very good condition :)
return true;
}
alert('hey');
return false;
}
I think, your document.form1.txt1.value is not filled correctly, so your value a is probably undefined and not "", so it will return TRUE.
Try to debug with console.log(a);
And finally, use var a = document.getElementById('txt1').value;, just in case :)
instead of form id use name
<script>
function validation()
{
var a=document.form1.txt1.value;
console.log(a);
if(a=='')
{
alert("Hey");
return false;
}
return true;
}
</script>
</head>
<body>
<form name="form1" onsubmit="return validation(this)" action="newjsp1.jsp">
<input type="text" id="txt1">
<input type="submit" id="sub">
</form>
</body>
Update
Do not use this as a function parameter. this is a keyword. Use any other variable. Something like this
function validation(form) {
var a=form.txt1.value;
if(a==="") {
window.alert("Hey");
return false;
}
return true;
}
When the form is like this
<form name="form1" onsubmit="return validation(this)" action="newjsp1.jsp">
....
</form>
Try document.forms.form1.txt1.value;
function validation(){
var a=document.forms.form1.txt1.value;
if(a==""){
alert("Hey");
return false;
}
return true;
}
Check the demo http://jsbin.com/vuxoha/1/edit

i need help to call add() function and also validate function, so first it will validate and than add

I want to validate the form on submit and with the same click if form is filled correctly than call the add() function. I'm not an advanced user so kindly keep it simple, and if there are any other ways to do it I would appreciate that.
Here is my code:
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>Untitled Document</title>
</head>
<body>
<script>
function validate() {
var x = document.forms["myform"]["fnum"].value;
var y = document.forms["myform"]["snum"].value;
if( x=="" || x ==null){
alert("Please Enter the ist Number");
return false;
}
if( y=="" || y== null){
alert("Please Enter the 2nd Number");
return false;
}
}
function add(){
var x = document.forms["myform"]["fnum"].value;
var y = document.forms["myform"]["snum"].value;
x=parseInt(x);
y=parseInt(y);
var sum = x +y;
document.write(sum);
}
</script>
<form name="myform" onSubmit="return validate()">
First Number: <input type="number" name="fnum">
Second Number : <input type="number" name="snum">
<input type="submit" value="submit">
</form>
</body>
</html>
You need a third function that does this logic, as follows:
function submit() {
if(validate()) {
add();
return true;
} else {
return false;
}
}
And then have
<form name="myform" onSubmit="return submit()">
...
Alternatively, you can have add() call validate() and return false in that case and just have return add() in the form submission.

Categories

Resources