Submit name value pair from javascript? - javascript

Can JS submit name/vale pairs through a document.testform.submit(); ?
or does it have to be submitted through the html tags, for example
<INPUT TYPE="text" NAME="inputbox1" VALUE="This is such a great form!" SIZE=50><P>

Typically you include an <input type="hidden"> in the form, and set the value you want in the event handler before it gets submitted.
<form method="post" action="thing" id="sandwich"><fieldset>
<input type="text" name="inputbox1" value="This is such a great form!" />
<input type="hidden" name="jsremark" />
</fieldset></form>
<script type="text/javascript">
document.getElementById('sandwich').onsubmit= function() {
this.elements.jsremark.value= 'Secretly it aint that great';
return true;
}
</script>

no, you'll have to mash it yourself into JSON using javascript

With jquery it is very simple:
$("#formid").bind("submit", function(){
var str = $("#formid").serialize();
$.post("url?"+str);
return false;
}

You could set the post data of an ajax request using only JS.

It's plain simple using jQuery:
$.post(url, {"name":"value"})

Related

Can't get input validation Javascript to work

Apologies if this question isn't layed out correctly (my first time using stack overflow).
I'm trying to validate if my inputs on a form are filled in when a user presses submit, it alerts the user when the inputs are empty but also when they are not, I'm not sure whats going wrong. Here is my Javascript:
<script>
function validation() {
var x = document.forms["bookingForm"]["id"].value;
if (x == "") {
alert("Ensure all fileds are filled");
return false;
} else {
sendSMS();
alert("Success");
return true;
}
}
</script>
Here is a link to an expanded part of the code for reference:https://pastebin.com/Dj5fA3gB
The general syntax for accessing a form element and element's value are:
document.forms[number].elements[number]
document.forms[number].elements[number].value
If you are using submitButton as in and you are calling validation on onSubmit of the form then you need to call event.preventDefault();
<!DOCTYPE html>
<html>
<body>
<form onsubmit="validation()" name="bookingForm">
First Name: <input type="text" name="id" value="Donald"><br>
Last Name: <input type="text" name="lname" value="Duck">
<input type="submit" value="Submit" />
</form>
<script>
function validation() {
event.preventDefault();
var x = document.forms["bookingForm"]["id"].value;
if (x == "") {
alert("Ensure all fileds are filled");
return false;
} else {
sendSMS();
alert("Success");
return true;
}
}
</script>
</body>
</html>
As suggested in my comment the most clean solution is to use the html attribute required by adding it to your inputs.
Looks something like this.
<form>
<input type="text" name="example" required>
<input type="submit" name="send">
</form>
The biggest advantage is that it works without any additional JS which is in my opinion always the prefered solution.
You didn't include return keyword in the form tag and adding unnecessary keyword "name" in the form tag.
<form onsubmit="return validation()" method="POST"
action="">
remove the "name" attribute from form tag and add action attribute.
Within the parenthesis in the action attribute, mention what happen if your validation success
Ex:(this code help you understand "action" attribute)
<form onsubmit="return productsvalidationform();" method="POST"
action="AddProductServlet">
when the form was successfully validated, I directed to AddProductServlet.(AddProductServlet is JSP servlet).
so that mention where do you need to redirect.

Is it possible to execute simple javascript statments from an input field in a document?

In the example below I've attached a function main to an input field. the function contains instructions to send an alert with a variable message (whatever the user enters into the field).
<form>
<input type="text" onsubmit="main()" />
<input type="submit" />
</form>
<script>
function main (param) {
alert(param)
}
//main();
</script>
It doesn't work, but I believe that's because I've made some noob error that I'm failing to recognize. The result of a functioning version of this code would be the ability to submit "hello world" and produce an alert box stating 'hello world' (without quotes).
But, further than this, I'd like to be able to pass the likes of main("hello world"); or just alert('hello world'); to the input field to produce the same result.
The problem I think I'm running into is that the page is refreshed every time I submit. There are a few questions on here with similar problems where people have suggested the use of onsubmit="main(); return false;", but in fact this does not seem to work.
Looks like you want to eval() the value of the input.
Use with caution, has security impact...
Returning false from a handler stops the regular action so you have no redirect after submitting:
<form onsubmit="main(); return false;">
<input id="eval-input" type="text" />
<input type="submit" />
</form>
<script>
function main () {
eval(document.getElementById('eval-input').value);
}
</script>
Here's how you can detect a form submission:
<form onsubmit="foo()">
<input type="text">
<input type="submit">
</form>
<script>
function foo(){
alert("function called");
}
</script>
I however advise you do this (preference), if you desire to manage the form data through a function:
<form id="myform">
<input type="text">
<input type="submit">
</form>
<script>
document.getElementById("myform").onsubmit=function(event){
alert("function called");
//manage form submission here, such as AJAX and validation
event.preventDefault(); //prevents a normal/double submission
return false; //also prevents normal/double a double submission
};
</script>
EDIT:
use eval() to execute a string as JavaScript.
jQuery way:
You create event listener which will be triggered when user click 'submit'.
<form>
<input type="text" id="text"/>
<input type="submit" />
</form>
<script>
$( "form" ).submit(function( event ) {
event.preventDefault();
alert( $('#text').val() );
});
</script>
To prevent page reloading - you should use event.preventDefault();
Pure JavaScript:
<form>
<input type="text" id="text"/>
<input type="submit" id="submit" />
</form>
<script>
var button = document.getElementById("submit");
var text = document.getElementById("text");
button.addEventListener("click",function(e){
alert(text.value);
},false);
</script>
If I understand what you want to do, you can call the function like this, and writing params[0].value you can access the input value:
function main(params) {
//dosomething;
document.write(params[0].value);
}
<form onsubmit="main(this)">
<input type="text">
<input type="submit">
</form>
Try something like this
onchange="main()"
onmouseenter, onMouseOver, onmouseleave ...
<input type="text" onmouseenter="main()" />

I have 1 form with 2 submit buttons

I am trying to set-up a form that has 2 buttons, accept and deny. It doesn't seem to be working. Any thoughts on what I should fix?
<form name="iform" method="post" onsubmit="" onreset="" enctype="multipart/form-data" action="formapprovedeny" class="iform">
Form content here.
<input type="button" onclick="submitForm('html_form_approve.php')" class="submit_button" value="Approved" name="Approved" />
<input type="button" class="submit_button" onclick="submitForm('html_form_deny.php')" value="Denied" name="Denied" />
</form>
Here is the script part.
<script>
function submitForm(action)
{
document.getElementById('formapprovedeny').action = action;
document.getElementById('formapprovedeny').submit();
}
</script>
Your Javscript is trying to submit a form with an id of formapprovedeny but your form does not have an id. Try adding id="formapprovedeny" to your form
It should id="formapprovedeny" not action="formapprovedeny"
<form name="iform" method="post" onsubmit="" onreset="" enctype="multipart/form-data" id="formapprovedeny" class="iform">
You have a problem with your naming.
You try to get the form by it's id, but it is not set. It's name is.
You should use either getElementByName or give your form an id.
The type of button must be 'submit' and the value whatever you want, look this:
<input type="submit" class="submit_button" value="Approved" name="Approved" />
<input type="submit" class="submit_button" value="Denied" name="Denied" />
What do you want to achieve using the 2 buttons? What do you expect?
http://jsfiddle.net/xaW5P/
<script>
function submitForm(action)
{
alert('hello submitForm '+action);
document.getElementById('formapprovedeny').action = action;
document.getElementById('formapprovedeny').submit();
}
</script>
if I use your code (added an alert) this seems to work...whatever it should be doing ;)

show and hide div after submiting an action when checkbox is check and uncheck

I am trying to show or hide div after submitting an action. so let say I have textarea and I put "example" there then checked the checkbox. after submitting, the "receipt.php" page must display "example" , and if I unchecked the checkbox and submit, the receipt.php page must hide the "example". I tried searching similar to my problem but I really don't have idea how to solve it. I have this code so far but i dont have any codes in "receipt.php" since I really don't have idea. pls help me
<form method ="POST" action ="receipt.php">
<textarea name ="comment"></textarea><br>
<input type="checkbox" id="checkbox" value ="1" >Show this comment in receipt<br>
<input type ="submit" value ="Print">
</form>
You don't need the server response to recognize if the checkbox was checked unless you have some validation on server side. If using JQuery, you can do this:
$('#checkbox').change(function(){
$('#your_div').toggle();
});
If you want to rely on what your server says you need to return something to your ajax call.
for example {response: true/false}
In Html:-
<form method ="POST" action ="receipt.php">
<textarea name ="comment"></textarea><br>
<input type="checkbox" name="reciept-chk" id="checkbox" value = "1" >Show this comment in receipt<br>
<input type ="submit" value ="Print">
</form>
In receipt.php:
<?php
..//recept.php
if(isset($_POST['reciept-chk'])){
// Write Code example here
}
?>
If you want to validate it client side before posting your value in receipt.php then
you can simply validate by piece of jquery.
$(document).ready(function(){
$('#checkbox').change(function(){
if ($('#checkbox').is(':checked')) {
$("#exampleDiv").show();
} else {
$("#exampleDiv").hide();
}
});
});
Please avoide toggle() as it deprecated in 1.8
Here is the code you'll need in your unique PHP file :
<form method="POST">
<textarea name="comment">
<?php (isset($_POST['checkbox1']) && $_POST['checkbox1'] == '1') ? echo "Example"; : echo ""; ?>
</textarea>
<br>
<label for="checkbox1">Show this comment in receipt</label>
<input type="checkbox" id="checkbox1" name="checkbox1" value="1" />
<br>
<input type="submit" value="Print" />
</form>
Replace what you want in place of "Example".
If you are using javascript only, you might try something like this:
<script>
function show(){
if(form.toggledisplay.checked == false){
document.getElementById('example').style.display = "none";
}
else{
document.getElementById('div').style.display = "block";
}
}
</script>
<form method = "POST" action="receipt.php" onsubmit="show()">
<textarea name = "comment"></textarea><br>
<input type="checkbox" name="toggledisplay" id="checkbox" value = "1" >Show this comment in receipt<br>
<input type = "submit" value = "Print">
</form>
<div id="example" style="display:none;">This is the div you want to show</div>
If you are populating the contents of the div from the receipt.php file, you could make a post request to it, when the onsubmit() function is fired and fill the contents of the div like:
document.getElementById('div').innerHTML = "Result from the get/post request"
Hope this points you in the right direction.

How to manipulate Get query?

I have the following form from http://regain.sourceforge.net/:
<form name="search" action="search.jsp" method="get">
<p class="searchinput">
<b>Suchen nach: </b>
<input name="query" size="30"/>
<select name="order" size="1" ><option selected value="relevance_desc">Relevanz</option><option value="last-modified_asc">Dokumentendatum aufsteigend</option><option value="last-modified_desc">Dokumentendatum absteigend</option</select>
<input type="submit" value="Suchen"/>
</p>
</form>
the search form works fine. The URL looks like the following:
http://localhost:8080/regain/search.jsp?query=queryfieldvalue&order=relevance_desc
Now I want to add a checkbox to manipulate the value of the input field query.
If the checkbox is checked then the query value should look like filename:"queryfieldvalue"
http://localhost:8080/regain/search.jsp?query=filename%3A%22queryfieldvalue%22&order=relevance_desc
What's the best way to do this? Javascript? Do you have a short example for me because I'm really new to javascript.
Thanks a lot in advance.
one way with pure javascript (without jquery) would be
<script type="text/javascript">
function handler()
{
var check = document.getElementById('check');
var query = document.getElementsByName('query')[0];
if(check.checked)
{
query.value = "filename:\"" + query.value + "\"";
}
else
{
query.value = query.value.replace(/^filename:"/, "").replace(/"$/, "");
}
}
</script>
<form>
<input type="text" name="query" />
<input type="checkbox" id="check" onclick="handler()" />box
</form>
it should more or less work, it would be safer if you give query input field an id and then reference it by id, not name
if you use jQuery, something like this should do:
<input type="checkbox" id="chkQuery">Pass queryfield</input>
<script>
$(document).ready(function{}
$("#chkQuery").click(function(){
if ($(this).is(':checked'))
$("input[name='query']").val("filename:queryfieldvalue");
else
$("input[name='query']").val("queryfieldvalue");
});
});
</script>

Categories

Resources