adding an input value and submitting the form on load - javascript

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

Related

html input fileupload returning null

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>

pass JavaScript variable to HTML input box and (to use in PHP file)

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 -->

Pass js variable to form action url

I'm not sure if this is possible, or if I am doing it the wrong way?
I have a form that when submitted, should send the user to a URL depending on the input.
e.g If the users inputs '2', the URL should be books/itemView?id=2
I have created a var = id, which takes the search input box data. Is it possible to add this variable to my current form action? Perhaps there is a more efficient way?
My current code is as follows;
<form id="search" action="<?php echo URL; ?>books/itemView?id=" method="post">
<input type="text" name="search" id="demo"/>
<input type="submit" value="Submit">
</form>
My JS
$(document).ready(function(){
var id = $('#search').val();
});
Quite new to JS so any help appreciated.
JS should be
$('#search').on('submit', function() {
var id = $('#demo').val();
var formAction = $('#search').attr('action');
$('#search').attr('action', formAction + id);
});
If they enter 2 in the search input then your id will be appended to your url like:
url?search=2
So maybe you want to change the name of your search input to id or add another input field.
<form id="search" action="<?php echo URL; ?>books/itemView" method="post">
<input type="text" name="id" id="demo"/>
<input type="submit" value="Submit">
</form>
That should be all you need no jquery or javascript necessary.
When you submit it should result in:
books/itemView?id=2(or whatever is in the search/id input when you click submit)
Hmm, you can try with that:
$(document).ready(function(){
var $form = $('#search');
var id = $form.val();
var $search = $('#demo');
var originalAction = $search.attr('action');
$form.on('submit', function() {
$search.attr('action', originalAction + id);
});
});
Before submitting the form, jQuery's on('submit', handler) function executes the code in handler modifying the attribute action that you want.
originalAction variable stores the content of the action attribute that was partially generated in php, then you append your id dynamically created with js.

Sending form data to a popup on button submit

I have a form with only one selectbox, now when the user hits submit button, a popup opens up. But I need this popup to contain the value from the form. I have written till here, but unable to pass the form values. Read online about this issue but still no help.
Any suggestion would be helpful.
<form action="" method="post">
<select name="sme">
<option value="sometinf">Someting</option>
<option value="p">p</option>
</select>
<input onclick="javascript:popUp();" type="submit" class="btn btn-lg btn-border" value="Upgrade">
</form>
<script type="text/javascript">
function popUp()
{
popupWindow = window.open('admin_upgrade_user.php','User','resizable=yes,scrollbars=yes,width=650,height=550');
popupWindow.focus();
}
</script>
Error now fixed, but not completely
Ok, I seem to be able to get the value. But, no new popup opens up, it displays the value in the current popup, what would trigger this ?
It is easier in this scenario to use the Get method, and include the form value inside the url string.
You could also stop the submit of your form (so refreshing the page) by returning false on submit.
An example might be the following:
function popUp() {
var sme = document.getElementById('sme'), opt;
if (sme) {
opt = sme.options[sme.selectedIndex].value;
popupWindow = window.open('admin_upgrade_user.php?opt=' + opt,'User','resizable=yes,scrollbars=yes,width=650,height=550');
popupWindow.focus();
return false;
}
return false;
}
see this link on jsfiddle: http://jsfiddle.net/Icepickle/7mU4m/
and some smaller changes on the html
<form onsubmit="return popUp();">
<select name="sme" id="sme">
<option value="sometinf">Someting</option>
<option value="p">p</option>
</select>
<input type="submit" class="btn btn-lg btn-border" value="Upgrade" />
</form>
You can do this using basic jquery:-
<form action="" method="post">
<select id="sme">
<option value="sometinf">Someting</option>
<option value="p">p</option>
</select>
<input onclick="popUp();" type="submit" class="btn btn-lg btn-border" value="Upgrade">
</form>
<script type="text/javascript">
function popUp()
{
var value = document.getElementById('sme').value;
//Now if you want to access the select field value in the new window url then write
var popupWindow = window.open('admin_upgrade_user.php?value=' + value,'User','resizable=yes,scrollbars=yes,width=650,height=550');
//else if you want to just access the value within the new popup window page they write
var popupWindow = window.open('admin_upgrade_user.php','User','resizable=yes,scrollbars=yes,width=650,height=550');
popupWindow.selectField=value;
// Now, you can access the value as window.selectField within admin_upgrade_user.php page
popupWindow.focus();
}
</script>
You can pass value to the popup window via query parameter:
function popUp()
{
var popupValue = document.querySelector('select[name=sme]').value;
var popupWindow = window.open('admin_upgrade_user.php?value=' + popupValue,'User','resizable=yes,scrollbars=yes,width=650,height=550');
popupWindow.focus();
}
Using jQuery method serialize() will encode form elements to a string like
myinput=minpuntvalue&myinputtwo=mysecondinputvalue.
function popUp() {
var formData = $('form').serialize();
var popupWindow = window.open('admin_upgrade_user.php?'+ formData +' ','User','resizable=yes,scrollbars=yes,width=650,height=550');
popupWindow.focus();
}
If you later on would like to add more form elements to your string, your javascript function popUp() will not need modification to send the form data. If you're having various forms on the same page it's advisable to add a unique ID to every form and use serialize this way $('#yourFormId').serialize().
Have a look here: http://api.jquery.com/serialize/

Change form submit action and then submit the form

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 " ] ;

Categories