use javascript and html form input in form action= - javascript

I have a simple form. A user inputs text and I need that text to be used in the action attribute of form. I also need to use a JavaScript variable in the form attribute action. The other thing I need is to be able to test the form input to make sure it's ok.
<script>
function validate(form){
var formVal=document.forms["myForm"]["test"].value;
simple test code for formVal
return true;
}
var scrt_var=737; //I've got more code to get this variable, I've just hardcoded it for simplicity
</script>
<FORM name="myForm" method="POST" action='http://www.example.com/viewdetails.php?id='+how to get scrt_var + '&page=' + how to get the text input; onsubmit="return validate(this);">
<input type="text" name="test" value="">
<input type="submit" value="Submit">
</form>
So how do I go about getting the variable scrt_var in the action attribute and also the inputted text as well?

This is simple event listener attached to the form onsubmit event. It simply concatenates url string, input value and scrt_var and submits form to given url.
<script>
var form=document.forms['myForm'];
form.addEventListener('submit', function(){
var testVal = this.elements['test'].value,
scrt_var = 737;
if(testVal){
this.action = 'http://www.example.com/viewdetails.php?id=' + scrt_var + '&page=' + testVal;
this.submit();
}
}, false);
</script>
<form name="myForm" method="POST">
<input type="text" name="test" value="">
<input type="submit" value="Submit">
</form>
I don't know what do you mean by statement: "The other thing I need is to be able to test the form input to make sure it's ok.". "Ok input value" is very subjective and varies depending on what you want to achieve. You have to try to validate it on your own (eg. check if the value is empty) ;)

I think you should use jQuery. It is more simplier. :)
With jQuery:
function validiate(){
//your validiation
var testVal = $('#myForm #test').val();
if(testVal == '' || testVal == ' '){
alert('Not valid');
}else{
$('#myForm').attr('action','yourUrl');
$('body').append($('#myForm').attr('action'));
}
return true;
}
$('#myForm').submit(function(e){
e.preventDefault();
validiate();
Demo:
http://jsfiddle.net/kxaAn/

plain and simple
<script>
function validate(){
formVal = document.getElementById('test').value;
var scrt_var=737;
document.forms["myForm"].action='http://www.example.com/viewdetails.php?id='+ scrt_var + '&page=' + formVal;
}
</script>
<FORM name="myForm" method="POST" action='http://www.example.com/viewdetails.php?id='+how to get scrt_var + '&page=' + how to get the text input; onsubmit="validate();">
<input type="text" id="test" value="">
<input type="submit" value="Submit">
</form>

Related

fill and submit form using javascript from console

Here is my form:
<form id="myForm">
<input id="htmlString" type="text" name="htmlField" ><br>
<input type="Submit" value="Submit" >
</form>
And need to fill it from console.
just to use it in my app,
Will inject javascript with data to local html file.
I tried to make the form without a submit button like so:
<body>
<form id="myForm">
<input id="htmlString" type="text" name="htmlField" ><br>
</form>
<script>
htmlString.oninput = function(){
///do some stuff
}
</script>
</body>
Expecting that :
document.getElementById('htmlString').value="moo" ;
It automatically submit the form, because here oninput used.
But it just stayed filled with inputs and not proceed further.
Tried with other solution:
form = document.getElementById("myForm")
form.submit()
But it just refreshed the page and not submitted the form.
The need is just one filed without else, and inject my string to it with javascript to run functions embedded in the html.
Try making the input button hidden.
<body>
<form id="myForm">
<input id="htmlString" type="text" name="htmlField" ><br>
<input type="Submit" value="Submit" style="display: none" >
</form>
<button onclick="simulateConsole()">Try it</button>
<script>
htmlString.oninput = function(){
if(this.value === "moo") {
myForm.submit();
}
}
// This event will be triggered even if you use console
htmlString.onsubmit = function(){
if(this.value === "moo") {
// do something onSubmit
}
}
function simulateConsole() {
// you can simulate this in console
htmlString.value = "moo";
myForm.submit();
}
</script>
</body>
I hope it helps.
You need to supply an action to the form, otherwise it will just reload the page.
See more here: https://developer.mozilla.org/en-US/docs/Web/HTML/Element/form

How to make a form not redirect immediatly if a certain string is detected, but only after submiting?

I've created a form to put in my website and I wanted it to redirect to a URL if a certain string was submitted in that form. But now it redirects immediatly if the string is detected in the form and I only want it to redirect if that string is submitted... How can I solve this problem? Here is the code I've made:
<form method="POST" id="myform">
<textarea name="inputBox123" id="myTextarea" oninput="myFunction(this)">
</textarea>
<input type="submit" value="Submeter"/>
</form>
<script type="text/javascript">
function myFunction(val) {
var testThis = document.getElementById("myTextarea").value;
if ( testThis.indexOf("launch") > -1 ) {
window.location = 'http://www.cateto.weebly.com/benoit.html';
return false;
}
}
</script>
Change input type from "submit" to "button" and add onclick="myFunction()", also add button Label
<form method="POST" id="myform">
<textarea name="inputBox123" id="myTextarea" oninput="myFunction(this)">
</textarea>
<input type="button" value="Submeter" onclick="myFunction()" />
</form>
<script type="text/javascript">
function myFunction(val) {
var testThis = document.getElementById("myTextarea").value;
if ( testThis.indexOf("launch") > -1 ) {
window.location = 'http://www.cateto.weebly.com/benoit.html';
return false;
}
}
</script>
Your tag mentions jQuery, so here's an answer that uses it's selectors.
event.preventDefault()
Will stop the default event from triggering, in the circumstance where you might be beholden to using submit.
Example:
$(document).on("submit", "form", function(event){
event.preventDefault();
//do other things...
return false;
});
Here is the native javascript documentation for event.preventDefault().

Convert input text to lowercase on submitting a form

I have a form in which there is one text field is provided with a submit button.On clicking submit button,it redirects to second php page from first php page.
index.php
<form action="submit.php" method="get">
<input type="text" name="search" id="search" />
<input type="submit" value="submit" onclick="convert()" />
</form
<script type="text/javascript">
function convert()
{
alert("hi");
var str ;
str = document.getElementById("search").value;
document.writeln(str.toLowerCase());
}
</script>
On submitting the form,i want the url to become like submit.php?search=text
I want this text to be in lower case,although if text entered is uppercase.
Please guide me how to make this text lower case,I am using the above script for converting it to lower case.But its not converting the text in lower case in URL.
Please guide me on this..
There was a few errors, you were missing the right angle bracket on </form> and you were trying to write the value rather than setting the field value, try this...
<form action="submit.php" method="get">
<input type="text" name="search" id="search" />
<input type="submit" value="submit" onclick="convert();" />
</form>
<script type="text/javascript">
function convert() {
alert("hi");
var str;
var srch=document.getElementById("search");
str = srch.value;
srch.value=str.toLowerCase();
}
</script>
You can do this only using javascript with a few extra stuff:
1) Give your <form> an id
<form action="submit.php" method="get" id="form1">
2) Make your <input> type as button. The reason for this is because we want to make sure the convert() function is executed first, and after that we will submit the form.
<input type="button" value="submit" onclick="convert()" />
3) Finally javascript to:
function convert()
{
alert("hi");
var str ;
str = document.getElementById("search");
str.value = (str.value.toLowerCase());
//get the form id and submit it
var form = document.getElementById("form1");
form.submit();
}
Fiddle
You are use form element so you can get any elements inside form element access by name, Here Our form name is form1 and inside this form inputbox name="search" and access this value by this way, document.form1.search.value.toLowerCase();
Check this Demo jsFiddle
JavaScript
function convert() {
alert("hi");
var str = document.form1.search.value.toLowerCase();
document.writeln(str);
//console.log(str);
}
HTML
<form name="form1" method="get">
<input type="text" name="search" id="search" />
<input type="submit" value="submit" onclick="convert();" />
</form >
try like this:
alert("hi");
document.getElementById("search").value = document.getElementById("search").value.toLowerCase();
return true;
Fiddle Live

Validate a form using JavaScript

I am a beginner and I have written a code for validating the form as:
function validateForm(){
var x=document.forms["myForm"]["fname"].value;
if (x==null || x==""){
alert("First name must be filled out");
return false;
}}
<!-- html part-->
<form name="myForm" action="demo_form.asp" onsubmit="return validateForm()" method="post">
First name: <input type="text" name="fname">
<input type="submit" value="Submit">
</form><br>
The problem with this code is pressing submit button triggers the validateForm function. How to call the function when the object losses focus?
This is the exact solution to my problem. Where the user gets some kind of notification when the object losses focus:
<script>
function validate(){
var y = document.getElementById("errorResponse");
var x=document.forms["myForm"]["fname"].value;
if (x==null || x==""){
y.innerHTML = "Error";
}
}
</script>
The HTML form is:
<form name="myForm">
First name: <input type="text" name="fname" onBlur = "validate()">
<div id = "errorResponse"></div>
<input type="submit" value="Submit">
</form>
The div can be designed in CSS to red color to get user attention and many more tricks can be played.
replace your input element's code by following
<input type="text" onblur="return validateForm();" name="fname">
i guess thats what you are looking for
<html>
<head>
<script type="text/javascript">
function validateForm(oForm){
var els = oForm.elements;
for(var i = 0; i < els.length; i++){
if('string' === typeof(els[i].getAttribute('data-message'))){
return valEl(els[i]);
}
}
}
function valEl(el){
var method = el.getAttribute('data-valMethod');
if('req' === method && (el.value === null || el.value === '')){
alert(el.getAttribute('data-message'));
return false;
}
}
</script>
</head>
<body>
<form name="myForm" action="#" onsubmit="return validateForm(this)" method="post">
First name:
<input data-message="First name must be filled out" data-valMethod="req" onchange="return valEl(this)"; name="fname"><br />
<input type="submit" value="Submit">
</form>
</body>
</html>​​​​​​​​​​​​​​​​​​​
I have Split it in one function that can validate the elements on "onchange" and another one that fires the validations for each element on form.onsubmit(), if there's the required data-message attribute on a form element.
Since HTML5 the Data-* attributes are very handy for these things :-)
This way you can avoid having to store the name of the form and elements in the validation script, since you pass references to the elements themselfes instead. Which is always a good thing.
From here you can expand the valEl-function to accommodate other types of validation.
Only limitation so far is that there can be only one type of validation per element, but that should be easy enough to get around.
Happy coding.
/G
PS http://jsfiddle.net/ePPnn/11/ for sample code

How can I send a variable to a form using this javascript function?

I've got this onclick call:
onClick="mySubmit();
which calls this function:
function mySubmit(){
document.getElementById("myForm").submit();
}
which then submits this form:
<form id="myForm" action="action.php" method="post">
My question is: how do I send a variable to the form from the onClick to get something like <form id="myForm" action="action.php?id=**(the variable sent from the onclick goes here)**" method="post">
Thanks!
Easiest way: append a hidden field to the form.
<form id="myForm" action="action.php" method="post">
<input type='hidden' id= 'hiddenField' name='id' value='' />
<script>
function mySubmit() {
document.getElementById('hiddenField').value = "Whatever I want here";
document.getElementById("myForm").submit();
}
</script>
Or use a function like
function addHiddenField(form, props) {
Object.keys(props).forEach(fieldName => {
var field = form[fieldName];
if (!field) {
field = document.createElement('input');
field.type = 'hidden';
field.name = fieldName;
form.appendChild(field);
}
field.value = props[fieldName];
});
}
document.querySelector('form').addEventListener('submit', () => {
addHiddenField(this, {
someQueryName: 'someQueryValue',
otherQueryName: 'otherVal'
});
});
<form>
Name
<input name=name />
<input type=submit />
</form>
Note that you can use DevTools to modify the iframe's sandbox to allow it to submit forms and you can verify the posted URL. sandbox="... allow-forms"
place a input type hidden inside the form then submit the form
<input id="id" name="id" type="hidden" />
set the value of the hidden field in your javascript submit()
document.getElementById('id').value = **;
but by setting form method="post" the id will not be the part of query string, i.e. the url will remain action.php
instead
if you really want the id in query string i.e. url action.php?id=** then you need to change the form method="get", by this the hidden field id will automatically be the part of the url i.e action.php?id=**
read about difference between get and post
here is how you access posted value on next page if you really need to use method="post" action="action.php"
Your HTML :
<form id="myForm" action="#" method="post">
<input type='hidden' id="id" name='id' value='123' />
<input type='submit' name='submit' value='Click me !' onclick='addParam()' />
</form>
Your Script :
function addParam() {
var url = "action.php?id=" + document.getElementById('id').value;
document.getElementById("myForm").setAttribute('action', url);
}
Thank You.

Categories