Show a DIV with form data on submit - javascript

Probably something stupid I'm doing. I want to populate a hidden DIV with values of a form on submit.
The DIV does open with correct data, but then resets after the page is finished loading. What am I doing wrong?
Here's my test:
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content=
"text/html; charset=us-ascii" />
<title>Test</title>
<script type="text/javascript">
function test(){
var usr = document.getElementById('user').value;
var pwd = document.getElementById('passwd').value;
document.getElementById('out').innerHTML = usr + " " + pwd;
document.getElementById('out').style.display = "block";
return true;
}
</script>
</head>
<body>
<form action="" onsubmit="return test()">
<input type="text" id="user" name="user" />
<input id="passwd" type="text" name="passwd" />
<p><input type="submit" value="Go" /></p>
</form>
<div id="out" style="display:none;">
</div>
</body>

Short answer:
Change this
return true;
to this
return false;
Long answer:
Forms are designed to load a new page when they are submitted. However, with scripting we can prevent this behavior by stopping the submit event. This can be achieved in many ways, but for your example, simply returning "false" from your handler will cancel the event, but only if the onsubmit attribute also has a return statement (which you already had).

The onsubmit function is submitting the form back to the page. You need to cancel the event to prevent it from submitting the data and reloading the page. The easy way to do this is to have your test() function return false. If you still want the form to submit and display the data in a div you'll want to submit the form via AJAX or in an iFrame.

Try replacing "return true;" at the end of your function with "return false;". My reasoning is, because you have the action attribute specified but value, it may think that the current page is the value and since you're not cancelling the event the page reloads.

You need to return false
You see, the return value of onsubmit is used to decide whether to continue to submit the form. So if it's true, the page will reload and the values will be lost. If its false, it won't!

This line is probably your problem:
<form action="" onsubmit="return test()">
The blank action attribute causes the page to bounce to itself (reload) when the form is submitted. You can prevent this by making sure test() returns false rather than true, which will keep the form from submitting at all.

When you post the form, the data will be lost. You could stop the form from posting by setting return true to return false, or you could add some logic to print out the user and passwd fields in the DIV id="out" and set the display to block if user and passwd fields have a value.

As an alternativ you can use a link which do the job without submittig the form.
Do

Your problem is on the line
you should fill the action with the name of the page or with php code to directing to the page itself:
i have tested.

Related

What is the proper way to submit a form with JS and still post all form data successfully?

I'm working with an embedded app on our dev site and when I click the submit button inside the iframe, I am triggering a manual submission event on another form (not in an iframe) on that page. If I manually click the submit button for the form, my data posts and everything works correctly. However, I want to eliminate an extra user click and submit the external form automatically when a user submits the other form inside the iframe.
I've got everything working correctly on a base level. When a user clicks the submit button in the iframe, I am using JQuery to grab values from inside the iframe and set values in this external form. Using the jquery 'submit()' event, I am then able to submit that external form. The problem is, the page refreshes and the data doesn't go anywhere. If I remove the 'submit()' event and manually click the submit button, the form posts and in this case, adds a product with custom data to the product cart.
As a proof of concept, this is my 'iframed' HTML.
<!DOCTYPE html>
<html>
<head></head>
<body>
<h1>Proof of Concept</h1>
<p>Total cost: $<span id="cust_price">222.22</span> plus shipping.</p>
<p>Quote number: <span id="quot_num">1546751962211</p>
<form method="POST" enctype="multipart/form-data" id="newQuoteForm">
<button type="submit" class="btn btn-primary" name="new-app-btn">Add to Cart</button>
</form>
</body>
<footer>
</footer>
</html>
Here is my on-page form that is OUTSIDE the iFrame.
<form method="POST" enctype="multipart/form-data" id="outer-quote-form" action="/checkout/">
<label class="quote_number">Quote Number:
<input type="text" id="quote_number" name="quote_number" value="">
</label>
<label class="custom_price">price:
<input type="text" id="custom_price" name="custom_price" value="">
</label>
<button type="submit" class="btn btn-primary" name="ws-add-to-cart">Add to Cart</button>
</form>
Then, I have JQuery working to grab the iframed values and puts them in the exterior form. Afterwards, it fires a 'submit()' event on that form.
<script>
jQuery('#newQuoteApp').load(function() {
var iFrameDOM = jQuery("iframe#newQuoteApp").contents();
jQuery('#newQuoteApp').contents().find('#newQuoteForm').submit(function() {
jQuery("input#custom_price").val(jQuery('#newQuoteApp').contents().find('#cust_price').text()); // updated
jQuery("input#quote_number").val(jQuery('#newQuoteApp').contents().find('#quot_num').text());
jQuery("#outer-quote-form").submit();
return true; //return false prevents submit
});
});
</script>
Except when the jquery submit() event fires, the form appears to submit and the page refreshes but no data is posting as it does when I manually submit the form. Is there an extra step here or a better way to fire the form submit with post data?
Edit: Adding the PHP function that isn't firing on jquery submit() for context.
if (isset($_POST['ws-add-to-cart'])) {
add_action( 'init', 'add_product_to_cart' );
function add_product_to_cart() {
global $woocommerce;
global $product;
$product_id = 138;
$woocommerce->cart->add_to_cart($product_id);
}
header("Location:https://www.devsite.com/checkout/");
}
The reason for the form not submitting because you are submitting the whole form without the submit button which is <button type="submit" class="btn btn-primary" name="ws-add-to-cart">Add to Cart</button> which you have declared in php to get a post request like this
if (isset($_POST['ws-add-to-cart'])) {...
When you call submit(); on the form via the get method, you see '/new-quote/?quote_number=1546751962211&custom_price=222.22'
but where's ws-add-to-cart, it's not submitting and that's the reason why php isn't getting your request
The fix will be to add .click() on the submit button instead of submitting the form
<script>
function enterVals($val){
var price = $val.price;
document.getElementById("quote_number").value = $val.num
document.getElementById("custom_price").value = $val.price
document.getElementsByName("ws-add-to-cart").click();
}
</script>
Or in your script in case you want to use jquery, this is the fix
<script>
jQuery('#newQuoteApp').load(function() {
var iFrameDOM = jQuery("iframe#newQuoteApp").contents();
jQuery('#newQuoteApp').contents().find('#newQuoteForm').submit(function() {
jQuery("input#custom_price").val(jQuery('#newQuoteApp').contents().find('#cust_price').text()); // updated
jQuery("input#quote_number").val(jQuery('#newQuoteApp').contents().find('#quot_num').text());
jQuery("button[name=ws-add-to-cart]").click();
return true; //return false prevents submit
});
});
</script>
This is definitely the answer and sorry for my stupidity, i didn't pay required attention before
try removing return true from your js code
if that doesn't work, try changing the <form method="POST" to <form method="GET" to debug the values in the url just for checking that the form actually fires up with values
Alternative method: Old school method
code for page OUTSIDE the Iframe
<script>
function enterVals($val){
var price = $val.price;
document.getElementById("quote_number").value = $val.num
document.getElementById("custom_price").value = $val.price
document.getElementById("outer-quote-form").submit();
}
</script>
code for the Iframe file
<script type="text/javascript">
$('#newQuoteForm').on('submit', function(event) {
var Page = window.parent;
var allVals = {
price:$('#cust_price').text(),
num:$('#quot_num').text()
}
Page.enterVals(allVals);
event.preventDefault();
});
</script>
Explanation
window.parent refers to the parent window where the iframe is loaded on, with reference to this we can trigger functions that are in the parent window so by this, we created a variable and added the information which is sent by the function enterVals() to the window
The enterVals() function just puts the values and submits the form without any jQuery.
What is the proper way to submit a form with JS?
This might not be the 'best' way to submit a form with js but is cross-browser which is good

JavaScript code keeps failing

I have hidden a div tag and I am using JavaScript to make that div tag appear on the screen upon form submission, the problem is that the div tag appears but then it quickly disappears, I have no idea what is going on, I need it to stop disappearing, once the form is submit the div tag should remain visible on the page, the div tag only contains a p tag with some text, I have tried onClick on the button but I get the same result.
<html>
<body>
<form onSubmit="validateRadio()">
<div style="display: none" id="validationText" >
<p style="border: 1px solid black;">
"This field is mandatory".
</p>
</div>
<div>
<input type="submit">
</div>
</form>
</body>
<script type="text/javascript">
function validateRadio(){
validationText.style.display="block";
}
</script>
</html>
Your page is likely refreshing (the action parameter defaults to the current URL if it isn't provided) which causes the DIV to "reappear". If you would like to block the form submission, use onSubmit but make sure to return false in your method.
function validateRadio(){
validationText.style.display="block";
// returning false will prevent the form submission
return false;
}
You're not doing anything to prevent the form from actually being submitted. Change your function to return false:
function validateRadio() {
validationText.style.display = "block";
return false;
}
and your handler to <form onSubmit="return validateRadio()">
jsFiddle example
Yes..
when you submit form, a new page is loaded (or same page is reloaded)
If you will see your validationText, you did'nt submit page, for example transform your
<form onSubmit="return validateRadio()">
and
function validateRadio(){
validationText.style.display="block";
return false
}

Submit and onclick not working together

<input type="submit" class="sub" onClick="exefunction2()" id="button">
When I click on the submit button onClick is not working. How can I fix this? I need to work this on submitting the form because onClick event contains values.
The best way is to call you method on the form tag like this:
<form onsubmit="return exefunction2();">
...
</form>
Returning false will not submit the form, true will submit!
to post more data (builded with exefunction2) you can use this
<script type="text/javascript">
function exefunction2(form) {
//add dynamic values
var dynValues = {
"val1": 1,
"val2": "bla"
};
for(var name in dynValues) {
//check if field exists
var input = null;
if(document.getElementsByName(name).length === 0) {
input = document.createElement('input');
input.setAttribute('name', name);
input.setAttribute('type', 'hidden');
form.appendChild(input);
}
else {
input = document.getElementsByName(name)[0];
}
input.setAttribute('value', dynValues[name]);
}
return true;
}
</script>
<form onsubmit="return exefunction2(this);">
<input type="submit" />
</form>
W3 schools has a good explanation here: http://www.w3schools.com/js/js_validation.asp
Basically, submit waits for a return value from onClick before doing anything. You can wire up a confirm() request too, if you like. If the form validates, just write something like return confirm("continue"). It's an old question, but I hope it helps anyone who stumbles across it. Another big reason for failure is a bug in your script. Unfortunately, unless you are running a debugger in your browser, it is very difficult to know what if anything is crashing your script. Turning on your browser debugger can be helpful to trace any issues. In Chrome you can use CTRL-SHIFT-I for Windows or CMD-OPTION-I for Mac. If you pause on caught errors, you can find any syntax or fatal errors that are prematurely stopping your script.
You can submit the form with Javascript.
<form id="form_id" ...>
<input type="button" class="sub" onclick="exefunction2();" id="button">
The Javascript:
function exefunction2() {
...
document.forms["form_id"].submit();
}
Well, I don't know if that's the "official" expected behavior, but that's how it works: a submit-type button will no longer submit if you add to it an onclick Javascript function. Just have the function also submit the form or have the function return false
Try <form onSubmit="exefunction2()">.
Agreeing to #silly , I used the same idea . I am sharing the implementation. My objective was , to disable a button "Execute" which is used to submit a form , until a response is received , upon which , the "execute" button should be enabled again. I am using Flask .
My Form:
<form onsubmit="return disableExecuteButton();" method="POST" action="/dothis">
.....
</form>
My JS:
function disableExecuteButton(){
var executeButton = document.getElementById("executeButton");
executeButton.setAttribute("disabled","disabled");
return true;
}
function reactivateExecuteButton(){
var executeButton = document.getElementById("executeButton");
executeButton.setAttribute("disabled","enabled");
}
From Flask, I return:
return render_template('result.html', message=message, error=error, html_content=result, history=session['actions_taken'], done=True)
The "done=True" , is what I use to indicate, that the response is received and we need to enable the button again.
To re enable the button:
{% if done %}
<script type="text/javascript">
reactivateExecuteButton()
</script>
{% endif %}
Change the event to onsubmit, and return false to avoid the form to be submitted.
<input type="submit" class="sub" onsubmit="exefunction2();return false;" id="button">

Strange issue with jQuery.get()

I'm having a strange behaviour with this code:
<script type="text/javascript">
function get()
{
alert("gggg");
jQuery.get (
"http://localhost:8080/c/portal/json_service",
{
serviceClassName: "com.liferay.test.service.TrabajadorServiceUtil",
serviceMethodName: "findByName",
servletContextName: "TrabajadorPlugin-portlet",
serviceParameters: "[param]",
param : document.getElementById("nombre")
}
);
}
</script>
<div>
<form>
<input type="text" id="nombre" value="<%=searching%>"/>
<input type="button" value="Submit" onClick="javascript:get()"/>
</form>
</div>
Liferay portal gets blocked when the button "Submit" is pressed. The pop-up with the message "gggg" is showed, but after click ok on it, the page becomes blocked.
If I remove the line 'param : document.getElementById("nombre")', it doesn't block.
Can anyone explain me where is the error, or the reason of this behaviour?
Thanks in advance,
Rafa
The problem is that you're trying to pass an entire DOM element as the value for param, which jQuery isn't going to like. What type of element has ID nombre, and what property from that element do you want? If it's some kind of input, you likely want the value property, so you'd do:
param : document.getElementById("nombre").value
Updated Answer:
Thinking this through a little more, you should probably do this in a different way altogether. You're sending the data when the user clicks on the submit button, but remember if a user hits enter while typing in the input text box the form will submit but your code will not catch that.
A more robust solution would be to do it this way instead:
<div>
<form id="nombre_search">
<input type="text" id="nombre" value="<%=searching%>"/>
<input type="submit" value="Submit"/>
</form>
</div>​
<script type="text/javascript" charset="utf-8">
$(document).ready(function() {
$("#nombre_search").submit(function(){
$.get("http://localhost:8080/c/portal/json_service", {
serviceClassName: "com.liferay.test.service.TrabajadorServiceUtil",
serviceMethodName: "findByName",
servletContextName: "TrabajadorPlugin-portlet",
serviceParameters: "[param]",
param : $("#nombre").val()
});
return false;
});
});
</script>
Changes to your code:
Added an id to the form.
Made the submit button a submit button instead of just a button.
Placed code inside $(document).ready block.
Code runs when form is submitted not when button is clicked.
Hope this helps,
Sandro

How to change the value of textbox when form is submitted?

I have a form which has fields pre-filled with a default value, like this:
<input type=text name=first value="First Name" class="unfilled" />
When the textbox is clicked, the class unfilled is removed from the textbox, and the textbox is made blank so the user can type in his/her own info.
The problem is that when the form is submitted, its getting submitted with these default values, which is messing up the server side validation. How can I do it so that when the form is submitted, all the fields which have a default value are made blank, so the server side validation would throw the error: 'Please fill in this field'?
I'm trying the following code which isn't working:
$("#myForm").submit(function()
{
$(".unfilled").val('');
}
);
This does make the fields blank, but the server still receives them with their previous default values.
I think you simply have a syntax error. You're missing the closing parenthesis on your submit method.
I just whipped this up and it works fine
<!DOCTYPE html>
<html>
<body>
<?php
var_dump($_POST);
?>
<form action="test.php" method="post">
<input type="text" name="first" value="First Name" class="unfilled">
<input type="submit">
</form>
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js"></script>
<script type="text/javascript">
jQuery(function($) {
$('form').submit(function() {
$('.unfilled').val('');
});
});
</script>
</body>
</html>
You need to stop the form execution first, change the values, and then manually submit the form.
$("#myForm").submit(function(e)
{
// Stop the form submit
e.preventDefault();
$(".unfilled").val('');
$(this).submit();
}
You have to return true; if you want the form to submit, or false, if you don't.
The problem with this approach is that the fields will 'blink' before posting the values, thus creating a bit of unprofessional feel.
It is better to use hidden values and set them in submit() event.
I think you need the .click() function of JQuery.
Example:
$(function () { // shorthand for document.ready
$('.unfilled').click(function () {
$(this)
.val('')
.removeClass('unfilled');
})
});
UPDATE
Sorry, i missunderstand you, thought you need a feature like a placeholder.
Of couse you can do it with return false;, but this cancel the submitting. Or like GreenWebDev says to use e.preventDefault();.

Categories

Resources