I'm having this very simple form to enter user name and choose a file to upload. User name is required but file is not. It's styled and has a function to check file type and size before submitting the form. If you choose a wrong file the function will work and the submit button will be disabled. If you don't choose a file the user name validation won't work. If you click in the text input then blur it will go red but the form will submit.
JSFIDDLE
HTML
<form method="post" class="contact" onsubmit="return validate();" enctype="multipart/form-data">
<table cellspacing="30">
<tr>
<td>
<label id="userlabel">user name</label>
<input type="text" id="user" name="username" onblur="checkUser()"></td>
</tr>
<tr>
<td>
<div id="FileUpload">
<input type="file" size="4" id="BrowserHidden"
onchange="getElementById('FileField').value = getElementById('BrowserHidden').value;" name="pic" />
<div id="BrowserVisible"><input type="text" id="FileField" /></div>
</div>
</td>
</tr>
<tr>
<td><input type="submit" name="send" id="save" value="send" /></td>
</tr>
</table>
</form>
JS
function checkUser(){
var userlen = $("#user").val().length;
if(userlen<4){
$("#userlabel").css("color","rgb(224, 19, 19)");
return false;
}
else{
$("#userlabel").css("color","#000");
return true;
}
}
$("#BrowserHidden").change(function (e) {
var file = this.files[0];
var name = file.name;
var extension = name.substr((name.lastIndexOf('.') + 1));
var str = 'doc,docx,pdf';
if (str.indexOf(extension) > -1) {
console.log('y');
size = file.size;
console.log(size);
if (size > 10000000) {
alert('file size is larger than 10 MB');
$("#save").attr("disabled", "disabled");
return false;
}
else {
$("#save").removeAttr("disabled");
return true;
}
}
else {
alert('file type is not allowed');
$("#save").attr("disabled", "disabled");
return false;
}
});
function validate(){
$.each($('form :input'),function(){
$(this).blur().change();
});
if(!checkUser() ){
return false;
}
else{
return true;
}
}
This is how you can make it working:
change your submit button to normal one and add onclick attribute to it
remove onsubmit attribute from your form tag
change your validate() function to submit form if checkUser() returns true
That's it!
Fiddle
Hope that worked for you!
Related
I created a page which collect few information and when submit it loads to completely wrong page even though URL is correct.
Here is my script
<script type="text/javascript">
jQuery(document).ready(function () {
jQuery(".ch1").change(function () {
jQuery(".ch1").prop("checked", false);
jQuery(this).prop("checked", true);
});
jQuery(".ch2").change(function () {
jQuery(".ch2").prop("checked", false);
jQuery(this).prop("checked", true);
});
jQuery("#tour_date").datepicker({
dateFormat: "yy-mm-dd",
showOn: "button",
buttonText: "Select Date",
buttonImageOnly: true,
buttonImage: "http://jqueryui.com/resources/demos/datepicker/images/calendar.gif",
});
});
function validateForm() {
var children = jQuery("#child_cnt").val();
var adlt_cnt = jQuery("#adlt_cnt").val();
var tour_date = jQuery("#tour_date").val();
if (children == "") {
alert("Please enter No. of children");
return false;
}
if (adlt_cnt == "") {
alert("Please enter No. of adults");
return false;
}
if (tour_date == "") {
alert("Please enter tour date");
return false;
}
if (!validateTripTypes()) {
alert("Please select a trip type");
return false;
}
if (!validateServices()) {
alert("Please select a service");
return false;
}
}
function validateTripTypes() {
if (jQuery('.ch1:checked').length > 0) {
return true;
} else {
return false;
}
}
function validateServices() {
if (jQuery('.ch2:checked').length > 0) {
return true;
} else {
return false;
}
}
</script>
[vc_section][vc_column_text]
<form method="post" name="page1_form" onsubmit="return validateForm()" action="[insert_php] bloginfo('url'); [/insert_php]/new-tour-booking-next2/">
<label>No. of Children:</label> <input name="child_cnt" size="10" type="number" id="child_cnt"/>
<label>No. of Adults:</label> <input name="adlt_cnt" id="adlt_cnt" size="10" type="number" />
<label>Tour Date:</label> <input name="tour_date" id="tour_date" size="10" type="text" placeholder="Select Date"/>[/vc_column_text][/vc_section]
[insert_php]
$wp_session = WP_Session::get_instance();
$wp_session['child_cnt'] = 0;
global $wpdb;
$trip_types = $wpdb->get_results(
$wpdb->prepare("SELECT * FROM jtb_trip_types WHERE status = %d", array(1))
);
[/insert_php]
[vc_row][vc_column][vc_text_separator title="Type of Trip" title_align="separator_align_left"][/vc_column][/vc_row][vc_section][vc_column_text]
[insert_php]
$trip_type_list = "";
foreach ($trip_types as $trip_type) {
$trip_type_list .= '<input name="trip_type_list[]" size="10" type="checkbox" class="ch1" value="'.$trip_type->id.'" /><label>'.$trip_type->trip_type_name.'</label>
';
}
echo $trip_type_list;
[/insert_php]
[/vc_column_text][/vc_section][vc_row][vc_column][vc_text_separator title="Services" title_align="separator_align_left"][/vc_column][/vc_row][vc_row][vc_column][vc_column_text]
<input name="services_list[]" size="10" type="checkbox" class="ch2" value="1"/> <label>Vehicles</label>
<input name="services_list[]" size="10" type="checkbox" class="ch2" value="2"/> <label>Hotels</label>
<input name="services_list[]" size="10" type="checkbox" class="ch2" value="3"/> <label>Both</label>
[/vc_column_text][/vc_column][/vc_row][vc_row][vc_column][vc_btn title="Next" name="btn_next_form_1" type="submit" align="left"][/vc_column][/vc_row]
[insert_php]
//echo count($trip_types);
[/insert_php]
</<form>
It redirect to the correct URL. Which is this one http://www.jaudatravels.com/new-tour-booking-next2/
But it loads this page data even though URL is correct. http://www.jaudatravels.com/tours/
NB: This happens only when we submit the from through this page. http://www.jaudatravels.com/new-tour-booking/
Is there any reason for this behaviour?
The problem is your custom form & the right side search form both have been bind to a single submit event.
That is the reason the data getting loaded is not the one which you are expecting even though URL is correct because the URL is just to display the processing happens at the server side.
Solution:
There is a syntax error in ending form: </<form> rectify it
Or Just remove that search widget & try.
And also always be careful about the form structure when form start there must not be any div or a table interruption like
<div>
<form>
<input type="text" name="my_input"/>
</div>
</form>
Or
<table>
<tr>
<form>
<th><td><input type="text" name="my_input"/></td></th>
</tr>
</table>
</form>
So always include entire element (like div Or table Or anything) within the form so that no interruptions happen.
I am having difficulty trying to disable submit button for form until all fields have values in xslt using javascript.
I am using a xml file and transforming it to html using xslt. The code below shows what I am trying to do.
Xslt file
<input id="save_choice" type="submit" value="Save Choice" />
The error says "can't find variable" in line 1
(function() {
$('form > input').keyup(function() { !can't find variable
var empty = false;
$('form > input').each(function() {
if ($(this).val() == '') {
empty = true;
}
});
if (empty) {
$('#save_choice').attr('disabled', 'disabled');
} else {
$('#save_choice').removeAttr('disabled');
}
});
})()
Can you please advice? thank you
Update
Below is full xslt file and js file I am working with. thank you for any help in advance
<head><script src="validation.js" type="text/javascript"/>
</head>
<body>
<h1>Give As You Earn</h1>
<xsl:for-each select="data/options">
<fieldset>
<form name="form1" action="#">
<label><xsl:value-of select="selectionText" /></label>
<input type="text" name="{#inputName}" value="{#currentValue}" min="{#minimum}" max="{#maximum}" step="{#increment}"/>
<span><xsl:value-of select="#suffix" /></span>
<br/>
<label>Please tell us which charity you wish to donate to</label>
<input type="text" name="charity"></input>
<br/>
<input id="save_choice" type="submit" value="Save Choice" />
<button>Save Choice</button>
</form>
</fieldset>
</xsl:for-each>
validation.js file
(function() {
$('form > input').keyup(function() {
var empty = false;
$('form > input').each(function() {
if ($(this).val() == '') {
empty = true;
}
});
if (empty) {
$('#save_choice').attr('disabled', 'disabled');
} else {
$('#save_choice').removeAttr('disabled');
}
});
})()
Users will only be able to click the submit button if users select a video file and the textbox is not empty. i can disable the submit button but i cant re-enable it
<form action="upload.php" method="post" enctype="multipart/form-data">
<label for="file"><span></span></label>
<input type="file" name="videofile" id="videofile" />
<br/>
Please enter video title:
<br/>
<input type"text" name="videoTitle" />
<br />
<input type="button" disabled id="Submit" value="Submit" onclick="submit()"/>
</form>
<script>
document.getElementById('submit').disabled = true;
var n=document.getElementById('videoTitle').value;
function submit();
if($('#videofile')[0].files.length != 0) && (n.length > 1)
{
document.getElementById('submit').disabled = false;
}
</script>
Your code had a lot of mistakes. This is your corrected code:
function check() {
if (document.querySelector('#videofile').files.length != 0 && (document.getElementById("videoTitle").value.length > 1)) {
document.getElementById('Submit').disabled = false;
} else {
document.getElementById('Submit').disabled = true;
}
}
Here is the JSFiddle demo
Missing ID added (u added only name attribute, and forgot the ID while still trying to use them)
Changed 'submit' in code to 'Submit'
Remove JQuery $ syntax
Validation on keypress rather than on submit click (which doesn't makes sense since u cant click the button while its disabled)
Else code added to re-disable the button if conditions are not valid
onclick event over submit button does not make sense here. You must listen change event of the file input and keyup event of the text input and apply conditions accordingly. You have not assigned id attribute as well(videoTitle)
Also note that click handler will not be invoked if the button is disabled
Try this:
var submitBtn = document.getElementById('Submit');
function enableDisable() {
var elem = document.getElementById('videofile');
var n = document.getElementById('videoTitle').value;
if (elem.files.length && n) {
submitBtn.disabled = false;
} else {
submitBtn.disabled = true;
}
}
<form action="upload.php" method="post" enctype="multipart/form-data">
<label for="file"><span></span></label>
<input type="file" name="videofile" id="videofile" onchange='enableDisable()' />
<br/> Please enter video title:
<br/>
<input type="text" name="videoTitle" id='videoTitle' onkeyup='enableDisable()' />
<br />
<input type="button" disabled id="Submit" value="Submit" />
</form>
Can you try to make your submit function do something?
function submit() {
if($('#videofile')[0].files.length != 0) && (n.length > 1) {
document.getElementById('submit').disabled = false;
}
};
you should use change event for text and videofile elements. So that whenever you modify something, change event is triggered and ur condition is checked inside it. Submit button is enable according to it.
Se the below code for reference!
<form action="upload.php" method="post" enctype="multipart/form-data">
<label for="file"><span></span></label>
<input type="file" name="videofile" id="videofile" />
<br/>
Please enter video title:
<br/>
<input type"text" name="videoTitle" id="videoText"/>
<br />
<input type="button" disabled id="Submit" value="Submit" onclick="submit()"/>
</form>
<script>
document.getElementById('submit').disabled = true;
var n=document.getElementById('videoTitle').value;
function submit();
$('#videofile').change(function() {
if($('#videofile')[0].files.length != 0) && (n.length > 1) {
document.getElementById('submit').disabled = false;
} else {
document.getElementById('submit').disabled = true;
}
});
$('#videoText').change(function() {
if($('#videofile')[0].files.length != 0) && (n.length > 1) {
document.getElementById('submit').disabled = false;
} else {
document.getElementById('submit').disabled = true;
}
});
</script>
I feel this is a bit simpler way to achieve this
<script>
document.getElementById("submit").style.pointerEvents = "none"; //Disable
var n=document.getElementById('videoTitle').value;
function submit();
if($('#videofile')[0].files.length != 0) && (n.length > 1)
{
document.getElementById("submit").style.pointerEvents = "all"; //Enable
}
</script>
Just replace your script with this one & try..
Hope this works for you..
I'm trying to check whether the user has actually chosen a file before pressing on upload or not, if so then check if the file is bigger than 4 MB. If the user has pressed on upload without choosing a file then a message should be sent telling them to go back and choose a file. But this code doesn't seem to work.
<div id="postUpload-wrapper">
<form id="uploadpost-form" action="/uploadpost" enctype="multipart/form-data" method="POST">
<input type="text" id="postname" placeholder="Title" name="postname">
<br>
<input id="fileupload" type="file" name="image">
<br>
<input type="submit" id "uploadpost-btn" value="Upload" name="uploadpost">
</form>
</div>
//UPLOAD A POST
router.post('/uploadpost', upload.single('image'), function(req, res){
var errors = "";
if(req.body.postname === ""){
errors += "Write a title";
res.send(errors);
return false;
}
//problem here
if(req.file.size === 0){
errors += "You need to choose a file";
res.send(errors);
return false;
}else{
if(req.file.size > 4000000){
errors += "Files can only be up to 4 MB in size";
res.send(errors);
return false;
}
}
Try setting input type="submit" element property disabled to "true" , use onchange event of input type="file" element to check if user selected file at FileList object , set type="submit" element to disabled="true" , disabled="false" if file.size greater than 4000000 bytes . If file not selected , file size over 4000000 bytes submit button set to disabled
var input = document.getElementById("fileupload");
input.onchange = function() {
var file = this.files, submit = this.nextElementSibling.nextElementSibling;
if (file.length > 0) {
if (file[0].size >= 4000000) {
submit.disabled = true;
alert("file size limit")
} else {
submit.disabled = false;
console.log(this.files)
}
}
}
<div id="postUpload-wrapper">
<form id="uploadpost-form" action="/uploadpost" enctype="multipart/form-data" method="POST">
<input type="text" id="postname" placeholder="Title" name="postname">
<br>
<input id="fileupload" type="file" name="image">
<br>
<input type="submit" id="uploadpost-btn" value="Upload" name="uploadpost" disabled="true">
</form>
</div>
I believe you should check this on the client side before allowing the file to be uploaded.
if(document.getElementById("uploadpost-btn").value != "") {
// you have a file
}
You can later check on the server-side. If req.body has any data then there was a file uploaded.
I have the following JavaScript function that is not supposed to allow blank fields to be sent to my back end code, but it's doing it anyway. Even if one or both of my fields is empty, this code is sending 2 blank values. (It works just fine if they're both filled in.) It's also not making my error messages appear. Can anyone help me? Here is my JavaScript.
function submitForm() {
var allValid = true;
var name = $("#name").val();
var comment = $("#comment").val();
if (name == null || name.length == 0) {
allValid = false;
$("#nameReq").css("visibility", "block");
} else {
$("#nameReq").css("visibility", "hidden");
}
if (comment == null || comment.length == 0) {
allValid = false;
$("#commentReq").css("display", "block");
} else {
$("#commentReq").css("display", "hidden");
}
if (allValid) {
clearForm();
$.ajax({
type : "post",
url : "writeComment",
data : "name=" + name + "&comment=" + comment,
success : function(response) {
},
error : function(error) {
}
});
document.getElementById('submit').disabled = true;
}
}
function clearForm() {
$("commentForm").reset();
}
Here is my form.
<form:form id="commentForm" method="post">
<table>
<tr>
<td>Name:<span style="display: none" id="nameReq">
<font style="font-weight: bold; color: red; visibility: hidden;">
<c:out value='Name required' /></font></span><br />
<input type="text" id="name" maxlength="30" /></td>
</tr>
<tr>
<td>Comment:<span style="display: none" id="commentReq">
<font style="font-weight: bold; color: red; visibility: hidden;">
<c:out value='Comment required' /></font></span><br />
<textarea id="comment" rows="20" cols="125" /></textarea></td>
</tr>
<tr>
<td><input id="submit" type="submit" value="Submit comment" onClick="submitForm()" /></td>
<td> </td>
</tr>
</table>
</form:form>
Your form will submit regardless of the action in your onclick function because the input button type is submit. If you'd like to only submit using your AJAX call, change the input to type="button".
Even if you'd like to submit without the ajax call, you can still use type="button" and submit the form using $('#commentForm').submit();
Your textarea is both self-terminating and has a closing tag. When I tried to run this, that confused it to the point that the onClick of the button was not run.