I'm trying to add a button to my form that would essentially run some different php code than my regular form submission code, that would, instead of emailing me the form, convert my page into a nice pdf ready to print. I have everything working except that pressing the button is giving me an error.
Firebug says :
Here's the code:
<form id="adaugareanunt" name="adaugareanunt" action="mailerPDF.php" method="post">
<table width="535" border="0" cellspacing="2" cellpadding="3">
<tr class="TrDark">
//... more form code
and for the button:
<div style="text-align:right"><img src="images/print-button.png" onClick="chgAction()" width="60px" height="20px"></div>
with the script:
<script language="JavaScript" type="text/JavaScript">
function chgAction()
{
document.getElementById["adaugareanunt"].action = "mailerXFDF.php";
document.getElementById["adaugareanunt"].submit();
document.getElementById["adaugareanunt"].action = "mailerPDF.php";
}
</script>
document.getElementById["adaugareanunt"]
change to
document.getElementById("adaugareanunt")
Use round brackets to get the MDN: document.getElementById()
const EL_form = document.getElementById("form");
EL_form.action = "someOtherURL.php";
EL_form.submit();
// PS! Make sure you don't have any name="submit" inputs in your form
Don't use inputs with name="submit"
Make also sure, if you want to use the .submit() method - that you don't have any name="submit" input in your form. Call it differently if really needed like i.e name="button_submit".
Here's the issue with name="submit" inputs: they overtake the function submit since any element with a set name attribute becomes a property of that form Element.
Example of the problem:
// EXAMPLE OF THE ISSUE:
const EL_form = document.getElementById("form");
// Why does EL_form.submit() not work?
console.log(EL_form.submit); // It's the actual INPUT with name="submit"
console.log(EL_form.submit()); // Therefore the "Not a function" error.
<form id="form">
<input type="submit" name="submit">
</form>
This works fine
<script language="javascript" type="text/javascript">
function chgAction()
{
document.getElementById("adaugareanunt").action ="mailerXFDF.php";
document.getElementById("adaugareanunt").submit();
document.getElementById("adaugareanunt").action ="mailerPDF.php";
}
</script>
Change the block brackets : []
To
The round brackets : ()
Square brackets means new Array.
var ar = newArray( " a " , " b " ) ;
var ar = [ " a " , " b " ] ;
Related
I'm using wordpress but making my own form for payments, i have two inputs of type select, like this:
<div id="S03" class="Selectos"><select tabindex="4" name="Mes" required="">
<option...[Code goes on]
And this:
<div id="S04" class="Selectos"><select tabindex="5" name="Ano" required="">
<option...[Code goes on]
Those works fine, but i want to join them in one input, i have research all day long, i found some clues about what i have to do, but in especifics no one does help me.
This is the input for the joining:
<input id="Expires" name="Expires" type="hidden" />
And the way i call the form:
<div class="container"><form id="contact" class="RV_donateForm" action="https://eps.banorte.com/secure3d/Solucion3DSecure.htm" method="post">
And how it close:
<fieldset><button id="contact-submit" name="submit" type="submit" data-submit=" ">Donar</button></fieldset>
</form></div>
Then i look for some way to joining and this one looks the better way to do it at the submit event:
<script type="text/javascript">
button.onclick = function (){
document.getElementById('Expires').value = document.getElementById('S03').value + '/' + document.getElementById('S04').value; cn = document.getElementById('Expires').value ;
alert(cn);
};
</script>
Well, at the bank 'post' they throw me all the vars ok, except for Expires that never joins and shows null, and i notice also because it never show me the alert. I'm new at html and JavaScript, and i'm not sure what could be wrong. All the code on the file are on this order for exception that the call of the form is at the beginning of everything, ¿maybe is the position on line that i have to put the javascript?
I appreciate any help. Thanks a lot stackfellas!
You may want to check this https://developer.mozilla.org/es/docs/Web/API/EventTarget/addEventListener
I guess you first need to get the button, then add the listener
<script type="text/javascript">
var button = document.getElementById('contact-submit')
button.addEventListener('click', function () {
document.getElementById('Expires').value = document.getElementById('S03').value + '/' + document.getElementById('S04').value;
cn = document.getElementById('Expires').value ;
alert(cn);
});
</script>
Finally! It does work like Omar says, but loading the addEventListener at onload body function, it will run the function that the event refers when you click on submit button.
<script type="text/javascript">
function putExpires(){
var cm = document.getElementById('S03').value;
var ca = document.getElementById('S04').value;
document.getElementById("Expires").value = cm + '/' + ca;
var cn = document.getElementById("Expires").value;
}
function load() {
var button = document.getElementById("contact-submit");
button.addEventListener("click", function(){putExpires()}, false);
}
</script>
<body onload="load();">
Thanks Omar!
I have the following form:
<form action="http://example.co.uk/order" method="post" id="voucher" class="AVAST_PAM_nonloginform">
<fieldset>
<h4>Vouchers</h4>
<input type="text" class="discount_name form-control" id="discount_name" name="discount_name" value="">
<input type="hidden" name="submitDiscount">
<button type="submit" name="submitAddDiscount" class="button btn btn-default button-small"><span>OK</span></button>
</fieldset>
</form>
and am using the following script:
<script>
window.onload = function(){
document.getElementById(\"discount_name\").value = \"50681\";
}
</script>
to populate the input. I then use:
<script>
window.onload = function(){
document.forms['voucher'].submit();
}
</script>
to activate the submit.
However, use the second script, it stops the "50681" from being inputted into the text box (instead submits a blank input).
Originally I had the code as :
<script>
window.onload = function(){
document.getElementById(\"discount_name\").value = \"50681\";
document.forms['voucher'].submit();
}
</script>
(I split it up thinking it may be a timing issue).
Any ideas?
p.s. the reason for the backslash's is due to it currently being run under php until I can get it working
The issue seems to be with (\"discount_name\").value = \"50681\"; & document.forms['voucher'].submit();
In either of the case you can avoid \ & for form you need to target by the index number. Assuming there is only one form present , so passing 0 in index
window.onload = function(){
document.getElementById("discount_name").value = "50681";
document.forms[0].submit();
}
Note: In the demo I have changed the action url to https else it will prohibit to make call from jsfiddle. In your case you can still keep http in code
DEMO USING ID
I have a login form on a modal jquery dialog with the usual 2 text INPUTs. When I enter a login name and password then click the submit, the call back function is called.
The first thing the callback does is try to extract the values of the two INPUTs, but the values returned are empty strings (I have a breakpont here, and have even stepped through the jquery processing of the objects - they objects are correctly identified as the fields on the form, but value="" for both).
At this point I can still see the values in the form, and when the callback exits and the focus goes back to the form, the values are still in the INPUTS. I also tried .prop("value") rather than .val(), but the result was the same.
I just can't figure why I can't read the values - any help appreciated.
<form id="cp-loginform" action="/cypo/index.php" method="POST" >
<input type="hidden" name="Login" value="Login">
<input type="hidden" name="pp" value="0" />
<input type="text" id="cp-loginname" name = "loginname" placeholder = "Login ID" class="loginforminput cp-width-50" autofocus >
<input type="password" id="cp-password" name = "password" placeholder = "password" class="loginforminput cp-width-50"></p>
<input type="submit" id="cp-submit" name = "submit" onclick="ProcessLogin()" ></p>
</form>
function ProcessLogin() {
var loginval = $("#cp-loginname").val();
var passwordval = $("#cp-password").val();
console.log(loginval.concat(" ",passwordval));
}
PROBLEM RESOLVED:
I felt that this was a scope issue. The form itself was obviously OK (if submitted from the dialog it worked) - it was just the attempt to check the INPUT values using jquery that wasn't working.
I found that my select had to start with the dialog element and include a descendent path to my INPUTs. It's as if the dialog puts a wrapper around the elements inside so they are no longer visible as owned by the document.
If I login with xxx and zzz and step therough the following code I see this:
var loginval = $("#cploginname").val(); << = ""
var passwordval = $("#cppassword").val(); << = ""
var loginval = $("#cp-loginform #cploginname").val(); << = ""
var passwordval = $("#cp-loginform #cppassword").val(); << = ""
var loginval = $("#cpdialog #cp-loginform #cploginname").val(); << = "xxx"
var passwordval = $("#cpdialog #cp-loginform #cppassword").val(); << = "zzz"
console.log(loginval.concat(" ",passwordval));
I can't say I understand what's going on, but I have a solution so I am happy. Thanks to all who answered.
FINAL WORD
Thanks to #CMedina, I now understand. The form was defined in a hidden DIV at the top of my BODY section, and I passed $("#loginform") to a f() that created the dialog. The dialog was added to the DOM just before the . I had missed the fact that my original form was still in the DOM, so I was referencing that, not the dialog copy. When I included the dialog wrapper in the path, I finally 'found' the second copy.
Your button is the type submit (their natural behavior is to send the form). Remove the onclick in your button html.
<input type="submit" id="cp-submit" name = "submit">
You must add preventDefault to prevent submit the form and do what you want. Add the code JS for the button onclick event
$("#cp-submit").on("click", function(e){
e.preventDefault();
var loginval = $("#cp-loginname").val();
var passwordval = $("#cp-password").val();
console.log(loginval.concat(" ",passwordval));
});
Result: https://jsfiddle.net/cmedina/svjqb2a4/
Try it :
<html>
<head>
</head>
<body>
<form id="cp-loginform" action="/cypo/index.php" method="POST">
<input type="hidden" name="Login" value="Login">
<input type="hidden" name="pp" value="0" />
<input type="text" id="cp-loginname" name = "loginname" placeholder = "Login ID" class="loginforminput cp-width-50" autofocus >
<input type="password" id="cp-password" name = "password" placeholder = "password" class="loginforminput cp-width-50">
<input type="submit" id="cp-submit" name ="submit" onclick="ProcessLogin(event)">
</form>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
<script>
function ProcessLogin(e) {
e.preventDefault();
var loginval = $("#cp-loginname").val();
var passwordval = $("#cp-password").val();
alert(loginval.concat(" ",passwordval));
}
</script>
</body>
</html>
I am trying to make a demo involving an html input file uploader and ajax, but I can't even get my script to getElementById.
I keep receiving an TypeError: form is null.
Here is my html and script:
<form id="file-form" action="handler.php" enctype="multipart/form-data" method="POST">
<input type="file" id="file-select" name="photos[]" multiple/>
<button type="submit" id="upload-button">Upload</button>
</form>
<script type="text/javascript">
var form = document.getElementById("file-form");
var fileSelect = document.getElementById("file-select");
var uploadButton = document.getElementById("upload-button");
form.onsubmit = function (event) {
event.preventDefault();
// Update button text.
uploadButton.innerHTML = 'Uploading...';
}
</script>
Note that 'fileSelect' and 'uploadButton' are receiving their elements and are not null.
For some reason form is not able to getElement.
I've seen several similar questions, but it seems like I am doing the right thing. Let me know if you have any suggestions.
Thanks in advance.
EDIT: I should add that this demo is in an ASP .ascx User Control Form. kami-sama's Code Snippet worked perfectly fine, but it will not do the same in my solution.
I log the 'form' variable after getElementById and it returns null and does not proceed past the form.onsubmit = function(event) line.
You should declare that your form will be handling uploaded files by adding the enctype="multipart/form-data"
w3
w3schools
I just added closing bracket to your code and it's working just fine in StackOverflow code snippet and in Firefox with html file.
var form = document.getElementById("file-form");
var fileSelect = document.getElementById("file-select");
var uploadButton = document.getElementById("upload-button");
form.onsubmit = function (event) {
event.preventDefault();
// Update button text.
uploadButton.innerHTML = 'Uploading...';
}
<form id="file-form" action="handler.php" method="POST">
<input type="file" id="file-select" name="photos[]" multiple/>
<button type="submit" id="upload-button">Upload</button>
</form>
I'm trying to pass a JavaScript variable to the value of an hidden input button to use in my PHP file output.
My HTML is:
<input type = "hidden" id = "location2" name = "location2" value = ""/>
I'm using this onclick="myFunction();" in my "Submit Form" input to run the function as it is not able to be done in the window.load()
My JavaScript below is calling indexes from another function and assigning the text to the variable 'location' (I know this sounds strange but it was the only way I have got it to work so far):
function myFunction() {
var x = document.getElementById("box2").selectedIndex;
var y = document.getElementById("box2").options;
var location=(y[x].text);
document.getElementById("location2").value=(location);
}
Any help would be hugely appreciated as I am really struggling and have been working on this for some time (as you can probably tell, I dont really know what I'm doing) - I just need to call the value of this variable into my PHP file output and the majority of my web form is completed.
Thanks very much
Marcus
I've just changed my HTML as follows
I've removed myFunction from my submit
I've added the following HTML button:
<button onclick="myFunction();" id = "location2" name = "location2" value="">Click me</button>
The variable is now passing!!!! The only problem is when I press the onclick button, it is now submitting my form!!
Is it okay for me to replace my previous submit button with this code??
THANKS TO EVERYONE FOR THEIR HELP ON THIS!!
I Was not sure what you doing but below example may help you. It will post the value as well as the option text.
Here we are using print_r to print the $_POST array from the AJAX Request. using this method, you should be able to debug the issue.
<!DOCTYPE html>
<html>
<body>
<?php if($_POST) {
print_r($_POST); die;
} ?>
<form name="" id="" method="post" >
Select a fruit and click the button:
<select id="mySelect">
<option>Apple</option>
<option>Orange</option>
<option>Pineapple</option>
<option>Banana</option>
</select>
<input type = "hidden" id = "location2" name = "location2" value = ""/>
<input type = "hidden" id = "locationname" name = "locationname" value = ""/>
<button type="submit" id="submit">Display index</button>
</form>
<script>
function myFunction() {
var x = document.getElementById("mySelect").selectedIndex;
var y = document.getElementById("mySelect").options;
//alert("Index: " + y[x].index + " is " + y[x].text);
document.getElementById("location2").value=(y[x].index);
document.getElementById("locationname").value=(y[x].text);
//alert($("#location2").val());
}
var submit = document.getElementById('submit');
submit.onsubmit = function(e){
myFunction();
};
</script>
</body>
</html>
i'm assuming your form method is 'POST' and action value is the same php page where you are expecting to see the 'location2' hidden input value, if that is the case, you can use $_POST['location2'] to get the value in that php page.
Yes it is fine to use button tag by default it acts like the submit button inside the form tag. You can also make it act like button(won't submit the form) by using the attribute type='button'.
Edited
button or input type='submit' can submit the form only when it is placed within the form tag(without javascript).
<form action='http://www.stackoverflow.com/'>
<button>stackoverflow</button> <!-- this works -->
</form>
<form action='http://www.stackoverflow.com/'></form>
<button>stackoverflow</button><!-- this won't work -->
var go = function() {
document.forms[0].submit();
};
<form action='http://www.stackoverflow.com/'></form>
<button onclick='go()'>stackoverflow</button><!-- still works -->