Javascript OnClick before submit button - javascript

Im having an issue getting some bit of code to run before the page submits.
When i change the return value to true to submit the form, the code above doesn't run. The way it is now, the code runs and the page is refreshed. I want to pass a true variable to submit the form Any ideas?
function buildMessageC() {
//Create an ePOS-Print Builder object
var builder = new epson.ePOSBuilder();
//Create a print document
builder.addTextLang('en')
builder.addTextSmooth(true);
builder.addTextFont(builder.FONT_A);
builder.addTextSize(1, 1);
builder.addText(document.getElementById('receipt').textContent);
builder.addFeedLine(1);
builder.addCut(builder.CUT_FEED);
//Acquire the print document
var request = builder.toString();
//Set the end point address
var address = 'http://192.168.1.69/cgi-bin/epos/service.cgi?devid=counter_printer&timeout=10000';
//Create an ePOS-Print object
var epos = new epson.ePOSPrint(address);
//Send the print document
epos.send(request);
return false;
The form button
<sf:form onsubmit="return buildMessageC()">
<input class="addToOrderButton button blue large expand" value="Place Order" name="_eventId_placeOrder" type="submit"/>
</sf:form>
Clarification
function doSubmit(){
buildMessageC();
return false;
} gives me print out and reloads the same page not submiting the form
function doSubmit(){
buildMessageC();
return true;
} doesn't print yet submits the form

Related

Why isnt my javascript function being run?

I'm trying to create a log-in page that validates data before it gets submitted to my php page that handles it. I'm using javascript to validate. This is my code:
<div class = mainInfo>
<?php include "header.php"; ?>
<form name = SignUpForm action = signUpHandler.php method ='POST' class = inputLists>
username: <input type = text name = "userName">
password: <input id= "p1" type = password name = "password">
reenter password: <input id ="p2" type = password name = "passwordConfirmation">
<input type="submit" name =" submitButton" value ="submit">
</form>
<div id="feedback">
</div>
</div>
<script>
function validate()
{
document.getElementById("feedback").innerHTML = "functionbeingcalled";
var p1 = document.getElementById("p1").value,
p2 = document.getElementById("p2").value);
if( ! p1===p2 )
{
document.getElementById("feedback").innerHTML = "passwords dont match";
}
if(p1==="")
{
document.getElementById("feedback").innerHTML = "Must have a password";
}
}
window.setInterval(validate(),1000);
</script>
<?php include "footer.php"; ?>
I would've thought that this script should run every second from the time that the page loads, but the script isn't being run at all. This line:
document.getElementById("feedback").innerHTML = "functionbeingcalled";
isn't working either.
Besides for this question, is it possible to validate data before submitting using only php? I'm new to web programming.
Pass the function instead of calling it.
// no parentheses!
window.setInterval(validate, 1000);
And this is wrong.
if( ! p1===p2 )
it should be this
if( p1!==p2 )
because of the higher precedence of the prefix !
I would suggest that you add listeners on your input fields! ;)
It will then only run the validation code when changes are made. In other words; only when necessary.
It will run the validation code "immediately" when input is changes. Instead of validation every 1000 ms.
I see you are not using jQuery (yet)? If you want to validate on 'change' using plain js, here is a solution: Plain js solution
If you are okay with adding the jQuery library to you code, then it can be done very easy like this jQuery solution
Well, you've got several issues...
First, with setInterval(), you only pass a reference to the function that should be called (validate in your case), you don't actually invoke it as you are doing (validate()). This essentially runs validate immediately and then sets the return value from it as the function to be called every second. Since validate() doesn't return a value, nothing happens every second thereafter.
You also have a typo with: if( ! p1===p2 ), which indicates that the Boolean opposite of p1 is being tested against p2. What you want is: if(p1 !== p2 ), which is how you express "not strictly equal to".
Now, really you are going about validation the wrong way. Instead of running a validation function on a timer, which is inefficient, you'd want to validate in one or more of these cases:
just before the entire form is submitted
just after the user leaves a form field
as the user is entering data
some combination of all 3
Each of those scenarios is handled through event handlers and a working example of each is shown below.
// Get the DOM references you'll need just once:
var feedback = document.getElementById("feedback");
// Don't set variables equal to property values of DOM elements because
// if you decide you need a different property value, you have to re-scan
// the DOM for the same element all over again.
var p1 = document.getElementById("p1")
var p2 = document.getElementById("p2");
var form = document.querySelector("form");
// Use this to validate when submit is pressed (causing form to be submitted):
form.addEventListener("submit", function(evt){
// If validate function returns false, don't submit
if(!validate()){
evt.preventDefault(); // cancel the form submission
feedback.textContent = "Can't submit. Form is not valid!";
}
});
// Get the elements that need to be validated:
var inputs = document.querySelectorAll("input[type=text],input[type=password]");
// Convert that node list into an array:
inputs = Array.prototype.slice.call(inputs);
// Loop over array and set up event handlers for inputs
inputs.forEach(function(input){
input.addEventListener("blur", validate); // Used to validate when user moves off of each element
input.addEventListener("input", validate); // Used to validate as data is being entered
});
function validate() {
// Keep track of whether the form is valid or not. Assume that it is by default
var valid = true;
// .innerHTML is for when you want to assign a string containing
// HTML to a DOM element. This invokes the HTML parser and renders
// the HTML. If you don't have HTML in the string, use .textContent
// instead, which doesn't invoke the HTML parser and is more efficient
// See if the password was typed in both boxes before telling the user
// that the passwords don't match
if(p1.value && p2.value){
// Are they the same?
if(p1.value !== p2.value){
feedback.textContent = "passwords dont match";
valid = false;
} else {
feedback.textContent = "passwords match";
}
} else {
// If both password fields aren't filled in, the form can't be valid
valid = false;
}
if(p1.value === "") {
feedback.textContent = "Must have a password";
valid = false;
}
// Send a result to the caller so it can be known by other code if the form is valid
return valid;
}
<div class = "mainInfo">
<form name="SignUpForm" action="signUpHandler.php" method='POST' class="inputLists">
<div>username: <input type="text" name="userName"></div>
<div>password: <input id="p1" type="password" name="password"></div>
<div>reenter password: <input id="p2" type="password" name="passwordConfirmation"></div>
<!-- Any form element that has a "name" attribute will submit its name/value as
part of the form data when the form gets submitted. You probably don't want
the actual submit button to be included in this, so don't give the button
a "name" attribute. -->
<input type="submit" value="submit"> <input type="reset" value="reset">
</form>
<div id="feedback"></div>
</div>

How to submit a form with JavaScript using python Requests?

I have a page as follows.
www.pict.ethdigitalcampus.com
I wish to submit the form data on this page using python Requests.
But unfortunately on this website, when the Submit button is clicked it calls a validate function.
<input type="submit" value="Sign In" onclick="return validate();" style="font-family: Verdana">
Now this validate function actually encrypts the password using some algorithm and then submits it to the server.
This is how the validate function works:
function validate()
{
if(isBlank(document.loginForm.loginid.value) || isNull(document.loginForm.loginid.value))
{
alert('Please Enter Login Id.');
document.loginForm.loginid.focus();
return false;
}
if(isBlank(document.loginForm.password.value) || isNull(document.loginForm.password.value))
{
alert('Please Enter Password.');
document.loginForm.password.focus();
return false;
}
var hashObj = new jsSHA("mySuperPassword", "ASCII");
var password = hashObj.getHash("SHA-512", "HEX");
var textval =document.loginForm.password.value; //The actual password entered by the user
var encryptedString = $.jCryption.encrypt(textval, password); //The password is encrypted and stored
document.loginForm.password.value = encryptedString; //The password field of the form is updated with "encrypedString"
document.loginForm.hiddenfield.value=password;
document.loginForm.service_id.value=get_cookie(document.loginForm.loginid.value.toUpperCase());
document.loginForm.action="http://pict.ethdigitalcampus.com:80/DCWeb/authenticate.do";
return true;
}
Now since I cannot directly submit form data to the action page, I have no choice but to click that button and execute this JavaScript function.
I have tried using urllib and still no luck. What do I do?

jQuery submit() with spin.js is preventing form from submitting?

I have a form that submits just fine, but when I add jQuery code to show a loading div using spin.js everything stops working.
<form id="search_form" action="<?php echo htmlspecialchars($_SERVER['PHP_SELF']); ?>" method="POST">
<!-- Form inputs here -->
...
<input id="exam_search" type="submit" name="submit" value="Search" />
Once I add the following code the form stops submitting and nothing happens. The loading div shows for a brief moment and then goes away like expected, but it seems like the form isn't actually submitting anymore.
var opts = // Array of options
var spinner = null;
$("#search_form").submit(function() {
spinner_div = document.getElementById('spinner');
if(spinner == null) {
spinner = new Spinner(opts).spin(spinner_div);
$("#search_results, #query").css({"opacity": "0.75"});
$("#search_form :input").attr("disabled", true);
} else {
spinner.spin(spinner_div);
$("#search_results, #query").css({"opacity": "0.75"});
$("#search_form :input").attr("disabled", true);
}
});
If I change all of that code in the submit event to this:
$("#search_form").submit(function() {
alert ("form submitted");
});
It shows the alert and then returns the results of the form submission just fine.
What am I doing wrong here?
EDIT
I saw in the jQuery docs for submit() that I shouldn't use the name "submit" on the input field. I tried changing that as well with no luck.
Well I'm not sure why but simply doing this worked:
$("#search_form").submit(function() {
var spinner_div = document.getElementById('spinner');
var spinner = new Spinner(opts);
spinner.spin(spinner_div);
});

Create URL upon JavaScript submit form

I currently have a form with some JavaScript functions and localstorage.
I'm trying to get that when a user types a value into a textbox, the search bar changes the URL from "mysite.com" to "mysite.com/%userinput%". Then that user can send that link to someone else and that person will then see what the original user saw.
This will change the URL after input.
As I understand from your question and comments, you don't want to load the URL, just change it, so try this fiddle: http://jsfiddle.net/GrP6U/2/show/
The code behind is:
JavaScript
var theForm = document.getElementById('theForm');
var theInput = document.getElementById('subj');
theForm.onsubmit = function(e) {
var myurl = "http://jsfiddle.net/GrP6U/2/show/?input=" + encodeURIComponent(theInput.value);
window.history.pushState('', "Title", myurl);
return false;
}
HTML
<form id="theForm">
<input id='subj'/>
<input type='submit'/>
</form>

passing old value back to javabean from javascript

I have this piece of javascript:
<script type="text/javascript">
function show_confirm()
{
var type = '<%= nameBean.getTxnType() %>';
var old_cd = '<%= nameBean.getCode() %>';
var new_cd = document.getElementById("tbCode").value;
var cd;
if (type == "Update")
{
if(old_cd != new_cd)
{
var response = confirm("Code already exists. Do you want to replace it?");
if (response){
document.NameUpdate.submit();
}
else{
cd = old_cd;
}
}
</script>
and this is what i am doing in my jsp page to invoke this script:
<INPUT TYPE=SUBMIT NAME="action" onclick="show_confirm()" VALUE="Save Changes">
Its working fine when I hit ok.. but my question is how can i pass the value of old_cd back to the bean so it wont update it with the new code that was entered by the user in the tbcode box.. when user hit cancel i want to ignore what value was entered in textbox and not to update that field in database
I'm not entirely clear on the use case here, but here are a couple of answers:
If the question is, "how do I stop the form from submitting when the user hits cancel?", then the answer is, return false in the click handler:
if (response){
document.NameUpdate.submit();
}
else{
cd = old_cd;
return false;
}
If you need to submit the form no matter which one the user clicks, then you probably need to submit the old value in a hidden input field and have a way to tell the server that user hit "cancel" (probably another hidden field), e.g.:
<!-- html -->
<input type="hidden" name="old_cd" value="<%= nameBean.getCode() %>">
<input type="hidden" id="canceled" name="canceled" value="0">
and javascript:
// js snippet
if (response){
document.NameUpdate.submit();
}
else{
document.getElementById("canceled").value = 1;
return true;
}

Categories

Resources