I'm using jquery file upload to upload files to server side action. However, I would like to also send additional form fields as part of the form submit. Additionally, I want the formsubmit to happen only when the "submit" button is clicked.
Is this doable using jquery file upload?
I've created a jsbin: http://jsbin.com/mozujilede/1/edit?html,js,output
Desired behavior:
user should be alerted if they try to upload more files than allowed limit
additional form data should be sent to the server side along with multiple files
the form submit should happen only when user clicks submit button.
This is what I'm doing at the moment:
var maxFiles = 10;
$('#fileupload').fileupload({
singleFileUploads: false,
url: '/uploadUrl'
}).bind('fileuploadadd', function (e, data) {
var input = $('#input');
data.formData = {example: input.val()};
var fileCount = data.files.length;
if (fileCount > maxFiles) {
alert("The max number of files is "+maxFiles);
return false;
}
});
Try This
var byButton = false;
$("#sub-but").on("click",function(){
var inp = $("#files")[0];
if(inp.files.length > 10){
alert("Max number of files");
return false;
}
byButton = true;
$("#myForm").submit();
});
function validate(){
if(!byButton)
return false;
byButton = false;
return true;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form id="myForm" onsubmit="return validate();">
<input type="text" placeholder="some extra items"/>
<input type="file" id="files" multiple="multiple"/>
<input type="button" value="Submit" id="sub-but"/>
</form>
Related
I have a basic form. I have hidden inputs outside the form. I want to set the form action with JavaScript to include the values from the hidden parameters as variables in the GET of the form when the user press the enter/submit button.
The form's current action is "https://example.com". I want to use JavaScript to take the values from the hidden inputs and concatenate them to the form's action so that the information stored outside the form is submitted with the form.
For example, the desired output for the form's action would be "https://example.com?firstParameter=parameter&secondParameter=secondParameter".
Here is what I have so far.
<form action="https://example.com" method="GET">
<input type="text"></input>
<button type="submit"></button>
</form>
<input type="hidden" id="firstParameter" value="parameter">
<input type="hidden" id="secondParameter" value="anotherParameter">
<script>
function setFormAction() {
var firstParameter= $("#firstParameter").val();
var secondParameter= $("#secondParameter").val();
var url = "https://example.com?";
if(firstParameter!== ""){
url = url + "&firstParameter=" + firstParameter;
}
if(secondParameter!== ""){
url = url + "&secondParameter=" + secondParameter;
}
// form action = url; (Need help here)
}
</script>
A simpler solution might be to add names to the hidden inputs then append them to the form so they get submitted by default process.
HTML
<input type="hidden" id="firstParameter" name="firstParameter" value="parameter">
<input type="hidden" id="secondParameter" name="secondParameter" value="anotherParameter">
JS
$('form').submit(function(){
const $form = $(this);
$('#firstParameter, #secondParameter').each(function(){
if(this.value){
$form.append(this)
}
});
});
Try the following:
document.querySelector('form').setAttribute('action', url);
function setFormAction() {
var firstParameter = $("#firstParameter").val();
var secondParameter = $("#secondParameter").val();
var url = "https://example.com";
if (firstParameter !== "") {
url = url + "&firstParameter=" + firstParameter;
}
if (secondParameter !== "") {
url = url + "&secondParameter=" + secondParameter;
}
document.querySelector('form').setAttribute('action', url);
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form action="https://example.com" method="GET">
<input type="text" />
<button type="button" onclick="setFormAction()">Test</button>
</form>
<input type="hidden" id="firstParameter" value="parameter">
<input type="hidden" id="secondParameter" value="anotherParameter">
Use encodeURIComponent() in case of user input to sanitise it.
I think you should avoid using form submission if you are not actually submitting a form in the general sense and use a simple button with an event to a function. You can then declare states which do different things with the submission like:
<button id="submit-button">Submit</button>
let state = 'default'
function onFormSubmit()
{
if (state == 'default') doDefaultThings()
else doLessDefaultThings()
}
async function doDefaultThings()
{
//collect necessary data
let url = "https://example.com" //append here
let res = await fetch(url)
//do other things or redirect
}
document.getElementById('submit-button'
.addEventListener('click', onFormSubmit)
I want to validate my mobile number using javascript and my code is:
function checkLength(){
var textbox = document.getElementById("textbox");
if(textbox.value.length == 10){
alert("success");
}
else{
alert("mobile number must be 10 digits long");
textbox.focus();
return false;
}
}
and calling function is:
<input type="text" name="Contact-No." id="textbox" required >Contact(Mobile No.)
<input type="submit" value="Submit" onclick="checkLength()">
All works fine but after showing alert message it should be return on same page but it takes me to some other blank page.
remove the onClick event from button and add onSubmit to <form..>.
Something like <form onSubmit='return checkLength();>'.
1) Your form needs to prevent the default submit action so that if you find error the form doesnt actually submit.. you should hook into the onsubmit event in your form.
an example assuming you've included jQuery 1.7+ on the page
html
<form id="myform" action="/">
<input type="text" name="Contact-No." id="textbox" />
Contact(Mobile No.)<br><br>
<input type="submit" value="Submit" id="submit" />
</form>
javascript
$("#myform").on("submit",function(e){
if(checkLength()==false){
alert('prevent form submit');
e.preventDefault();
}else{
alert('form submits as normal');
}
});
function checkLength(){
var textbox = document.getElementById("textbox");
if(textbox.value.length == 10){
alert("success");
return true;
}
else{
alert("mobile number must be 10 digits long");
textbox.focus();
return false;
}
}
example at:
http://jsfiddle.net/Lqbn6unp/
As pointed out elsewhere, the listener should be on the form's submit handler since the form can be submitted without pressing the submit button. Also, you can reference form controls as named properties of the form, which is more efficient than using getElementById and means the control doesn't need an ID.
So pass a reference to the form from the listener, e.g.
In the form:
<form onsubmit="return checkLength(this)" ... >
<input type="text" name="Contact-No." required >Contact(Mobile No.)
then in the function:
function checkLength(form) {
var textbox = form['Contact-No'];
if (textbox.value.length == 10) {
alert("success");
} else {
alert("mobile number must be 10 digits long");
textbox.focus();
return false;
}
}
I have downloaded JQuery Multiple file uploader from this site
http://www.fyneworks.com/jquery/multiple-file-upload/
I need to check whether the file input field is null or not before submitting the form.
<form onsubmit="return validate();">
<input type="file" name="File" class="multi" />
<input type="file" name="File" class="multi" />
<input type="submit" name="BtnSubmit" value="save" />
</form>
I tried
function validate() {
$(".multi").each(function () {
var multi = $(this).val();
if (multi) {
return true;
} else {
return false;
}
});
}
Not working because the filed is always empty. So is there any other way to achieve this ?
try this
var multi = $(".multi").val();
if (multi) {
console.log("multi");
} else {
console.log("no multi");
}
fiddle:
http://jsfiddle.net/w4qVv/
UPDATE:
or you can do it like this
function validate(field) {
var fieldVal = $(field).val();
if(!fieldVal) alert("No files selected");
}
and then:
validate(".multi");
fiddle:
http://jsfiddle.net/jk8aZ/
UPDATE2:
yep, you can use each like this
var multi = (".multi");
$(multi).each(function () {
validate(this);
});
fiddle:
http://jsfiddle.net/jk8aZ/1/
I'm trying to insert records into DB using AJAX. I'm not sure why, but it seems the javascript function referenced in the onclick tag of the submit button gets fired twice, and hence I get two records in my DB per click.
Placing alerts in the JS, I have managed to figure out that the problem is in the JS function getting called twice, and not the PHP script making two inserts. So, I'm not posting the PHP script, unless asked.
Here's the HTML for the form:
<form id="notify" method="post" action="add_notify.php">
Name: <input type="text" class="formname" name="name" value="" size="20"/>
Email: <input type="text" class="formname" name="email" value="" size="20"/>
<input type="submit" class="sendform" name="submit" onclick="processInfo()" value="Go!"/>
</form>
Javascript:
$("document").ready(function() {
$("#notify").submit(function() {
processInfo();
return false;
});
});
function processInfo()
{
var errors = false;
// Validate name
var name = $("#notify [name='name']").val();
if (!name) {
errors = true;
document.getElementById('name_error').innerHTML = 'You must enter a name.';
}
var email = $("#notify [name='email']").val();
if (!email)
{
errors = true;
document.getElementById('email_error').innerHTML = 'You must enter an email.';
}
else
{
var validEmail = true;
validEmail = validateEmail(email);
if (!validEmail)
{
errors = true;
document.getElementById('email_error').innerHTML = 'You must enter a valid email address.';
}
}
if (!errors)
{
$("#notify").ajaxSubmit({success:showResult});
return false;
}
}
You are calling processInfo twice once in submit handler and once in click handler. This might be the reason.
Here onclick="processInfo()" and inside
$("#notify").submit(function() {
processInfo();
return false;
});
processInfo() is called twice, both here, when the form submits:
$("#notify").submit(function() {
processInfo();
return false;
});
and here, when you click the submit button:
<input type="submit" class="sendform" name="submit" onclick="processInfo()" value="Go!"/>
You should remove one of them.
You are calling the processInfo() function twice: once on the form submit event, and once on the onclick on the input.
You should only attach the processInfo() function on the submit event. Remove the onlick dom0 event handler (inline scripts are to be avoided).
Also, do not use return false; as it prevents event bubbling. Use ev.preventDefault() instead.
$("document").ready(function() {
$("#notify").submit(function(ev) {
ev.preventDefault();
processInfo();
});
});
I have a html form. I want to take the input value (a url), extract a number from the url using regex ( '/[0-9]{5,}/') , and then refresh the form value with the number extracted and appended to another url. If I can't find a number - I just want an error to appear in the form box. All using Jquery to avoid page reload.
This is the existing form
<form id = "submit" method="post">
<label for="link_website_url">Create a short url</label>
<input id="link_website_url" name="link" size="30" type="text" />
<input class="go" name="commit" type="submit" value="Go!" /></form>
$('#submit').submit(function(){
var url = $('#link_website_url').val(); //http://example.com/12345
var num = yourNumExtractorFunction(url); //returns -1 if there is no number extracted
if(num > -1){
$('#link_website_url').val('http://otherdomain.com/' + num); //http://otherdomain.com/12345
}else{
$('#link_website_url').after('<span id="error_link_web_url" class="error">Incorrect format! Please try again.</span>');
return false; //error, so cancel this submit
}
});
If you perform additional validation, cancel the submit even if an individual check passes, clear error messages per check that validates (e.g. $('#error_link_web_url').remove();) and submit after all checks pass:
var checkFailed = false;
$('#submit').submit(function(){
var url = $('#link_website_url').val(); //http://example.com/12345
var num = yourNumExtractorFunction(url); //returns -1 if there is no number extracted
if(num > -1){
$('#link_website_url').val('http://otherdomain.com/' + num); //http://otherdomain.com/12345
$('#error_link_web_url').remove();
}else{
$('#link_website_url').after('<span id="error_link_web_url" class="error">Incorrect format! Please try again.</span>');
checkFailed = true;
}
/*Other checks...*/
if(checkFailed){
return false; //cancel submit
}
});
$('#submit').submit(function(){
var url = $('#link_website_url').value();
var val = <do your processing here>;
$('#link_website_url').value(val);
return false;
});