jQuery Getting uploaded image's name - javascript

//Picture upload
$(function() {
$(":file").change(function() {
if (this.files && this.files[0]) {
var reader = new FileReader();
reader.onload = imageIsLoaded;
reader.readAsDataURL(this.files[0]);
}
});
});
function imageIsLoaded(e) {
$('#myImg').attr('src', e.target.result);
};
<form id="form_roomtype" class="form-horizontal" style="padding-top: 57px;" action="roomtype" method="POST" enctype="multipart/form-data">
<input type="hidden" id="current_roomtype_id" name="current_roomtype_id" value="0">
<input type="hidden" id="roomtype_id_to_remove" name="roomtype_id_to_remove" value="0">
<input type="hidden" id="chk_tarif_applicable" name="chk_tarif_applicable" value="0">
<input type="hidden" id="photo_name" name="photo_name">
<div>
<span style="font-size: 16.85px; font-family: Arial, Helvetica, sans-serif; color: #757575;">ROOM PICTURE</span>
<br />
<br />
<input type="file" name="file" id="file" />
<br/>
<img id="myImg" src="<%=request.getContextPath()%>/images/insert_images.png" alt="room image" height="175" width="285" onclick="file" />
<br />Destination:
<input type="text" value="C:\Project\Booking_Engine\Java\booking\src\main\webapp\data" name="destination" />
</br>
<br />
<input type="submit" value="Upload" name="upload" id="upload" />
</div>
</form>
I need to take the id of the input (#file) and assign it to the hidden input with id (#photo_name) using the picture upload js on top.
I need to take the id of (<input type="file" name="file" id="file" />) and assign it to the id of (<input type="hidden" id="photo_name" name="photo_name">).
I already have the JS that I posted before... I need to use it to do the assigning of id.
I already have the id of the input file though the JS... (this.file[0]) already gives me the name of the uploaded files... now what I need is take this name and assign it to the id of the hidden input.
I need the value of photo_name in my java code below:
#Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
String currentRoomTypeIdStr = request.getParameter("current_roomtype_id");
Integer currentRoomTypeId = Integer.valueOf(currentRoomTypeIdStr);
String photoName = request.getParameter("photo_name");
if (!Objects.equals(currentRoomTypeId, null) || !Objects.equals(roomtypeIdToRemove, null)) {
try {
mUserTransaction.begin();
if (currentRoomTypeId == 0) { // Add mode
ChambreTypeEntity typeChambreEntity = new ChambreTypeEntity();
typeChambreEntity.setLibelle(inputTypeRoom);
typeChambreEntity.setCode(inputCodeRoom);
typeChambreEntity.setDescription(inputDescriptionRoom);
typeChambreEntity.setNbMinPers(inputMinPerson);
typeChambreEntity.setNbMaxPers(inputMaxPerson);
typeChambreEntity.setNbEnfGratuit(inputChild);
mEntityManager.persist(typeChambreEntity);
ChambrePhotoEntity chambrePhotoEntity = new ChambrePhotoEntity();
chambrePhotoEntity.setNomPhoto(photoName);
chambrePhotoEntity.setTypeChambre(currentRoomTypeId);
mEntityManager.persist(chambrePhotoEntity);
}
else { // Modification mode
Query query = mEntityManager.createQuery("FROM ChambreTypeEntity WHERE id=:pId")
.setParameter("pId", currentRoomTypeId);
List<ChambreTypeEntity> typeChambreEntityList = query.getResultList();
if (!typeChambreEntityList.isEmpty()) {
ChambreTypeEntity typeChambreEntity = typeChambreEntityList.get(0);
typeChambreEntity.setLibelle(inputTypeRoom);
typeChambreEntity.setCode(inputCodeRoom);
typeChambreEntity.setDescription(inputDescriptionRoom);
typeChambreEntity.setNbMinPers(inputMinPerson);
typeChambreEntity.setNbMaxPers(inputMaxPerson);
typeChambreEntity.setNbEnfGratuit(inputChild);
mEntityManager.persist(typeChambreEntity);
mEntityManager.persist(chambreTypeTarifTypeEntity);
ChambrePhotoEntity chambrePhotoEntity = new ChambrePhotoEntity();
chambrePhotoEntity.setNomPhoto(photoName);
chambrePhotoEntity.setTypeChambre(currentRoomTypeId);
mEntityManager.persist(chambrePhotoEntity);
}
}
mUserTransaction.commit();
}
But right now the value of photo_name is "". I need it to be the value that i chose while doing the picture selection.

Is the following is what you're looking for?
//Picture upload
$(function() {
// This is a better way of selecting the input field
$("input[name^=file]").change(function() {
if (this.files && this.files[0]) {
var reader = new FileReader();
reader.onload = imageIsLoaded;
reader.readAsDataURL(this.files[0]);
// This is what you should do
$('#photo_name').val(this.files[0].name);
}
});
});
function imageIsLoaded(e) {
$('#myImg').attr('src', e.target.result);
};
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form id="form_roomtype" class="form-horizontal" style="padding-top: 57px;" action="roomtype" method="POST" enctype="multipart/form-data">
<input type="hidden" id="current_roomtype_id" name="current_roomtype_id" value="0">
<input type="hidden" id="roomtype_id_to_remove" name="roomtype_id_to_remove" value="0">
<input type="hidden" id="chk_tarif_applicable" name="chk_tarif_applicable" value="0">
<input type="hidden" id="photo_name" name="photo_name">
<div>
<span style="font-size: 16.85px; font-family: Arial, Helvetica, sans-serif; color: #757575;">ROOM PICTURE</span>
<br />
<br />
<input type="file" name="file" id="file" />
<br/>
<img id="myImg" src="<%=request.getContextPath()%>/images/insert_images.png" alt="room image" height="175" width="285" onclick="file" />
<br />Destination:
<input type="text" value="C:\Project\Booking_Engine\Java\booking\src\main\webapp\data" name="destination" />
</br>
<br />
<input type="submit" value="Upload" name="upload" id="upload" />
</div>
</form>

Related

Need to correct this form validation

I've this small form in which the 1st field(title) is required by default. The 2nd and the 3rd are required only in a specific condition.
Case-I: If tool name is filled out, both tool name & tool URL become required.
Case-II: If tool URL is filled out, both tool name & tool URL become required.
I'm not sure it is working as expected.
Could you please help me correct my code?
$(document).ready(function(){
articleTitle = $('#title').val();
toolName = $('#toolName').val().trim();
toolURL = $('#toolURL').val();
if(((toolName.length>0)&&(toolURL==="")) || ((toolName.length<=0)&&(toolURL!==""))){
$('#toolName').prop('required', true);
$('#toolURL').prop('required' , true);
} else {
$('#toolName').prop('required', false);
$('#toolURL').prop('required', false);
}
$("#myForm").submit(function(){
sayHello();
return false;
});
});
label {
float: left;
width: 100px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.0/jquery.min.js"></script>
<form id="myForm">
<label for="title">Title:</label> <input type="text" id="title" required> <br /><br />
<label for="toolName">Tool Name: </label><input type="text" id="toolName"> <br /> <br />
<label for="toolURL">Tool URL: </label><input type="url" id="toolURL"> <br /> <br />
<button>Submit</button>
</form>
You can simplify your code quite a bit, please see the comments for a description.
var $toolName = $('#toolName')
var $toolURL = $('#toolURL')
var $toolInputs = $($toolName).add($toolURL)
function sayHelloToMyLittleFriend() {
alert('sup! form was submitted')
}
$toolInputs.on('change', function(e) {
var toolName = $toolName.val()
var toolURL = $toolURL.val()
$toolInputs.prop('required', toolName || toolURL)
})
$('form').submit(function(e) {
var toolName = $toolName.val()
var toolURL = $toolURL.val()
var bothFilled = !!toolName && !!toolURL
var noneFilled = !toolName && !toolURL
if (bothFilled || noneFilled) {
sayHelloToMyLittleFriend()
return true
}
return false
})
label {
float: left;
width: 100px;
}
/* this will show what element has the required attribute */
[required] {
border: 1px solid red;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.0/jquery.min.js"></script>
<form id="myForm">
<label for="title">Title:</label> <input type="text" id="title" required> <br /><br />
<label for="toolName">Tool Name: </label><input type="text" id="toolName"> <br /> <br />
<label for="toolURL">Tool URL: </label><input type="url" id="toolURL"> <br /> <br />
<button>Submit</button>
</form>
Here is a straightforward approach using library-less javascript (rather than jQuery).
(Albeit, you'll see that it's very similar to the jQuery).
Whenever data is entered into or removed from the form, the form inputs are checked and, as appropriate, the required attributes are added or removed.
var myForm = document.getElementById('myForm');
var toolName = document.getElementById('toolName');
var toolURL = document.getElementById('toolURL');
function checkInputs() {
if ((toolName.value !== '') || (toolURL.value !== '')) {
toolName.setAttribute('required','required');
toolURL.setAttribute('required','required');
}
if ((toolName.value === '') && (toolURL.value === '')) {
toolName.removeAttribute('required');
toolURL.removeAttribute('required');
}
}
myForm.addEventListener('keyup', checkInputs, false);
<form id="myForm">
<label for="title">Title:</label> <input type="text" id="title" required> <br /><br />
<label for="toolName">Tool Name: </label><input type="text" id="toolName"> <br /> <br />
<label for="toolURL">Tool URL: </label><input type="url" id="toolURL"> <br /> <br />
<input type="submit" value="Submit" />
</form>

Toggle sub-category divs based on radio button selection

I used the top answer to this question to build a form that feeds into a sheet along with file upload. Now I've hit another wall.
I have categories, and sub-categories. I'd like the sub-categories to only show up IF their parent category has been selected. I just can't figure out A) where I need to put the code (on our website it's right in with the HTML), I've tried putting it in the HTML file and the Code.gs file, or B) if the code I'm using is even right.
Here's the form - the "Co-Op Category" is the parent categories, I have hidden divs for each category that would hold the 'child categories'
HTML:
<script>
// Javascript function called by "submit" button handler,
// to show results.
function updateOutput(resultHtml) {
toggle_visibility('inProgress');
var outputDiv = document.getElementById('output');
outputDiv.innerHTML = resultHtml;
}
// From blog.movalog.com/a/javascript-toggle-visibility/
function toggle_visibility(id) {
var e = document.getElementById(id);
if(e.style.display == 'block')
e.style.display = 'none';
else
e.style.display = 'block';
}
</script>
<div id="formDiv">
<!-- Form div will be hidden after form submission -->
<form id="myForm">
Name: <input name="name" type="text" /><br/>
Co-Op Amount: <input name="amount" type="text" /><br/>
Co-Op Split:<br />
<input type="radio" name="split" value="100%">100%<br>
<input type="radio" name="split" value="50/50">50/50<br>
<input type="radio" name="split" value="75/25">75/25<br>
Other: <input type="text" name="split" /><br />
Reason for Co-Op: <input name="reason" type="text" cols="20" rows="5" /><br />
Brand:
<select name="brand">
<option>Select Option</option>
<option>Bluebird</option>
<option>Brown</option>
<option>Ferris</option>
<option>Giant Vac</option>
<option>Honda</option>
<option>Hurricane</option>
<option>Little Wonder</option>
<option>RedMax</option>
<option>SCAG</option>
<option>Snapper Pro</option>
<option>Sno-Way</option>
<option>SnowEx</option>
<option>Wright</option>
<option>Ybravo</option>
</select><br/>
Co-Op Category:<br />
<input type="radio" name="category" id="dealer" value="Dealer Advertising">Dealer Advertising<br />
<input type="radio" name="category" id="online" value="Digital/Online Marketing">Digital/Online Advertising<br />
<input type="radio" name="category" id="meetings" value="Meetings and Schools">Meetings and Schools<br />
<input type="radio" name="category" id="advertising" value="PACE Advertising">PACE Advertising<br />
<input type="radio" name="category" id="pricing" value="Program Pricing Promotions">Program Pricing Promotions<br />
<input type="radio" name="category" id="correspondence" value="PACE-to-Dealer Correspondence">PACE-to-Dealer Correspondence<br />
Other: <input type="text" id="other" name="category" /><br />
<div class="dealer box" style="display: none;">DEALER</div>
<div class="online box" style="display: none;">ONLINE</div>
<div class="meetings box" style="display: none;">MEETINGS</div>
<div class="advertising box" style="display: none;">ADVERTISING</div>
<div class="pricing box" style="display: none;">PRICING</div>
<div class="correspondence box" style="display: none;">CORRESPONDENCE</div>
Email: <input name="email" type="text" /><br/>
Message: <textarea name="message" style="margin: 2px; height: 148px; width: 354px;"></textarea><br/>
School Schedule (Image Files Only): <input name="myFile" type="file" /><br/>
<input type="button" value="Submit"
onclick="toggle_visibility('formDiv'); toggle_visibility('inProgress');
google.script.run
.withSuccessHandler(updateOutput)
.processForm(this.parentNode)" />
</form>
</div>
<div id="inProgress" style="display: none;">
<!-- Progress starts hidden, but will be shown after form submission. -->
Uploading. Please wait...
</div>
<div id="output">
<!-- Blank div will be filled with "Thanks.html" after form submission. -->
</div>
Code.gs:
var submissionSSKey = '1zzRQwgXb0EN-gkCtpMHvMTGyhqrx1idXFXmvhj4MLsk';
var folderId = "0B2bXWWj3Z_tzTnNOSFRuVFk2bnc";
function doGet(e) {
var template = HtmlService.createTemplateFromFile('Form.html');
template.action = ScriptApp.getService().getUrl();
return template.evaluate();
}
function processForm(theForm) {
var fileBlob = theForm.myFile;
var folder = DriveApp.getFolderById(folderId);
var doc = folder.createFile(fileBlob);
// Fill in response template
var template = HtmlService.createTemplateFromFile('Thanks.html');
var name = template.name = theForm.name;
var amount = template.amount = theForm.amount;
var split = template.split = theForm.split;
var reason = template.reason = theForm.split;
var brand = template.brand = theForm.brand;
var category = template.category = theForm.category;
var message = template.message = theForm.message;
var email = template.email = theForm.email;
var fileUrl = template.fileUrl = doc.getUrl();
// Record submission in spreadsheet
var sheet = SpreadsheetApp.openById(submissionSSKey).getSheets()[0];
var lastRow = sheet.getLastRow();
var targetRange = sheet.getRange(lastRow+1, 1, 1, 9).setValues([[name,amount,split,reason,category,brand,message,email,fileUrl]]);
// Return HTML text for display in page.
return template.evaluate().getContent();
}
//Toggle Secondary Categories
function(){
$('input[type="radio"]').click(function(){
if($(this).attr("id")=="dealer"){
$(".box").not(".dealer").hide();
$(".dealer").show();
}
if($(this).attr("id")=="online"){
$(".box").not(".online").hide();
$(".online").show();
}
if($(this).attr("id")=="advertising"){
$(".box").not(".advertising").hide();
$(".advertising").show();
}
if($(this).attr("id")=="pricing"){
$(".box").not(".pricing").hide();
$(".pricing").show();
}
if($(this).attr("id")=="correspondence"){
$(".box").not(".correspondence").hide();
$(".correspondence").show();
}
if($(this).attr("id")=="meetings"){
$(".box").not(".meetings").hide();
$(".meetings").show();
}
if($(this).attr("id")=="other"){
$(".box").not(".other").hide();
$(".other").show();
}
});
};
This bit specifically is where I'm having trouble:
//Toggle Secondary Categories
function(){
$('input[type="radio"]').click(function(){
if($(this).attr("id")=="dealer"){
$(".box").not(".dealer").hide();
$(".dealer").show();
}
if($(this).attr("id")=="online"){
$(".box").not(".online").hide();
$(".online").show();
}
if($(this).attr("id")=="advertising"){
$(".box").not(".advertising").hide();
$(".advertising").show();
}
if($(this).attr("id")=="pricing"){
$(".box").not(".pricing").hide();
$(".pricing").show();
}
if($(this).attr("id")=="correspondence"){
$(".box").not(".correspondence").hide();
$(".correspondence").show();
}
if($(this).attr("id")=="meetings"){
$(".box").not(".meetings").hide();
$(".meetings").show();
}
if($(this).attr("id")=="other"){
$(".box").not(".other").hide();
$(".other").show();
}
});
};
The unexpected token is due to the function(){ line, which is invalid syntax for the jQuery document ready function. You should have:
$(function(){
$('input[type="radio"]').click(function(){
...
});
});
With that fixed, your next error will be:
Uncaught ReferenceError: $ is not defined
That's because you haven't included jQuery, which is what the $ symbol is referring to in statements like $(this). You'll want to read this for more tips about using jQuery in Google Apps Script. The short story, though: You need to add the following, adjusted for whatever version of jQuery you intend to use:
<script
src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js">
</script>
Updated Form.html, which shows the appropriate <div> as you intended. It also includes the recommended doctype, html, head and body tags:
<!DOCTYPE html>
<html>
<head>
<base target="_top">
</head>
<body>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js">
</script>
<script>
// Javascript function called by "submit" button handler,
// to show results.
function updateOutput(resultHtml) {
toggle_visibility('inProgress');
var outputDiv = document.getElementById('output');
outputDiv.innerHTML = resultHtml;
}
// From blog.movalog.com/a/javascript-toggle-visibility/
function toggle_visibility(id) {
var e = document.getElementById(id);
if (e.style.display == 'block')
e.style.display = 'none';
else
e.style.display = 'block';
}
//Toggle Secondary Categories
$(function() {
$('input[type="radio"]').click(function() {
if ($(this).attr("id") == "dealer") {
$(".box").not(".dealer").hide();
$(".dealer").show();
}
if ($(this).attr("id") == "online") {
$(".box").not(".online").hide();
$(".online").show();
}
if ($(this).attr("id") == "advertising") {
$(".box").not(".advertising").hide();
$(".advertising").show();
}
if ($(this).attr("id") == "pricing") {
$(".box").not(".pricing").hide();
$(".pricing").show();
}
if ($(this).attr("id") == "correspondence") {
$(".box").not(".correspondence").hide();
$(".correspondence").show();
}
if ($(this).attr("id") == "meetings") {
$(".box").not(".meetings").hide();
$(".meetings").show();
}
if ($(this).attr("id") == "other") {
$(".box").not(".other").hide();
$(".other").show();
}
});
});
</script>
<div id="formDiv">
<!-- Form div will be hidden after form submission -->
<form id="myForm">
Name:
<input name="name" type="text" /><br/>
Co-Op Amount: <input name="amount" type="text" /><br/>
Co-Op Split:<br />
<input type="radio" name="split" value="100%">100%<br>
<input type="radio" name="split" value="50/50">50/50<br>
<input type="radio" name="split" value="75/25">75/25<br> Other: <input type="text" name="split" /><br /> Reason for Co-Op: <input name="reason" type="text" cols="20" rows="5" /><br />
Brand:
<select name="brand">
<option>Select Option</option>
<option>Bluebird</option>
<option>Brown</option>
<option>Ferris</option>
<option>Giant Vac</option>
<option>Honda</option>
<option>Hurricane</option>
<option>Little Wonder</option>
<option>RedMax</option>
<option>SCAG</option>
<option>Snapper Pro</option>
<option>Sno-Way</option>
<option>SnowEx</option>
<option>Wright</option>
<option>Ybravo</option>
</select><br/>
Co-Op Category:<br />
<input type="radio" name="category" id="dealer" value="Dealer Advertising">Dealer Advertising<br />
<input type="radio" name="category" id="online" value="Digital/Online Marketing">Digital/Online Advertising<br />
<input type="radio" name="category" id="meetings" value="Meetings and Schools">Meetings and Schools<br />
<input type="radio" name="category" id="advertising" value="PACE Advertising">PACE Advertising<br />
<input type="radio" name="category" id="pricing" value="Program Pricing Promotions">Program Pricing Promotions<br />
<input type="radio" name="category" id="correspondence" value="PACE-to-Dealer Correspondence">PACE-to-Dealer Correspondence<br />
Other: <input type="text" id="other" name="category" /><br />
<div class="dealer box" style="display: none;">DEALER</div>
<div class="online box" style="display: none;">ONLINE</div>
<div class="meetings box" style="display: none;">MEETINGS</div>
<div class="advertising box" style="display: none;">ADVERTISING</div>
<div class="pricing box" style="display: none;">PRICING</div>
<div class="correspondence box" style="display: none;">CORRESPONDENCE</div>
Email: <input name="email" type="text" /><br/>
Message: <textarea name="message" style="margin: 2px; height: 148px; width: 354px;"></textarea><br/>
School Schedule (Image Files Only): <input name="myFile" type="file" /><br/>
<input type="button" value="Submit" onclick="toggle_visibility('formDiv'); toggle_visibility('inProgress');
google.script.run
.withSuccessHandler(updateOutput)
.processForm(this.parentNode)" />
</form>
</div>
<div id="inProgress" style="display: none;">
<!-- Progress starts hidden, but will be shown after form submission. -->
Uploading. Please wait...
</div>
<div id="output">
<!-- Blank div will be filled with "Thanks.html" after form submission. -->
</div>
</body>
</html>

How to display buttons when a text box is focused in Javascript

I have written the following code for a virtual keyboard using javascript.
Jsp page:
<form>
<label for="text">Enter Text: </label>
<input id="text" name="text" type="text" size="50" onfocus="myFunction(this)" />
<input name="" type="reset" value="Clear" />
</form>
Javascript:
function myFunction(x)
{
}
function clicked(val)
{
var txt;
txt = document.getElementById('text').value;
if(val != 'B')
{
txt = txt + '' + val;
}
else
{
txt = txt.substr(0,(txt.length)-1);
}
document.getElementById('text').value = txt;
}
$(".dialog").dialog({
autoOpen: false,
height: 200,
width: 930,
modal: false,
draggable: true,
resizable: true,
buttons : {
"ESC":function(){
var val="Esc";
clicked(val);
},
"1":function(){
var val="1";
clicked(val);
},
"Tab":function(){
var val="T";
clicked(val);
},
"Caps":function(){
var val="q";
clicked(val);
},
"Shift":function(){
var val="";
clicked(val);
},
"B":function(){
var val=" ";
clicked(val);
},
},
});
When the text box is focused display dialog like keyboard, when i click some button its entered button value in textbox except Caps,Shift,Enter and Tab.
Please provide the required code for those Caps,Shift,Enter,Tab .
I'm not sure how to maintain code in clicked(val) method .
Use jQuery:
$("#text").on("focus", function() {
$("#button1").show();
$("#button2").show();
});
I just noticed you commented on somebody else's answer saying you want to create buttons with JS dynamically.
Here's a way to do it:
HTML:
<div id="myDiv"></div>
jQuery:
var myBtn = $('<button/>', {
text: 'Awesome button',
click: function () {
alert("Hello!");
}
});
$("#myDiv").append(myBtn);
DEMO
I hope the following example would be helpful:
<script type="text/javascript">
<!--
function fClose() {
document.getElementById('divWithButtons').style.display = 'none';
}
function myFunction(x) {
document.getElementById('divWithButtons').style.display = '';
}
//-->
</script>
<div style="display:none; position:absolute; top: 100px; left: 100px; background-color: #eee;" id=divWithButtons>
<input type=button value=Really onclick=fClose() style="margin: 100px">
<input type=button value="Why not" onclick=fClose() style="margin: 100px">
</div>
<form>
<label for="text">Enter Text: </label>
<input id="text" name="text" type="text" size="50" onfocus="myFunction(this)" />
<input name="" type="reset" value="Clear" />
</form>
Wrtie the function like this:
function myFunction(x)
{
document.getElementById("btn1").style.display="block";
document.getElementById("btn2").style.display="block";
}
Also set the id of buttons as well.
<form>
<label for="text">Enter Text: </label>
<input id="text" name="text" type="text" size="50" onfocus="myFunction(this)" />
<input name="" type="reset" value="Clear" />
<button id="btn1" class="btn">Btn1</button>
<button id=btn2" class="btn">Btn2</button>
</form>
Hope this will work for you.
Try this
HTML
<form>
<label for="text">Enter Text: </label>
<input id="text" name="text" type="text" size="50" />
<input name="" type="reset" value="Clear" />
</form>
Script
$(function() {
$("#text").focusin(function() {
$('form').append('<button class="btn">Btn1</button>\
<button class="btn">Btn2</button>'); // It will add dynamically two buttons
$(".btn").show();
})
});
DEMO
try this with jQuery:
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<script type="text/javascript">
jQuery( document ).ready(function() {
jQuery("#text").focus(function() {
jQuery('.btn').show();
});
// if you want button disappear after focus out
jQuery("#text").focusout(function() {
jQuery('.btn').hide();
});
});
</script>
...
<form>
<label for="text">Enter Text: </label>
<input id="text" name="text" type="text" size="50" />
<input name="" type="reset" value="Clear" />
<input class="btn" type="button" value="button2" name="btn2" style="display:none;"/>
<input class="btn" type="button" value="button1" name="btn1" style="display:none;"/>
</form>

Javascript form submission

I have a form that posts its data to Sugar CRM. The data is being successfully submited in Firefox but not redirecting correctly. In Chrome the data is not being submitted but is redirecting correctly.
<form method="POST" class="brochurelead webtoleadform" name="WebToLeadForm" id="WebToLeadForm">
<fieldset>
<label for="firstname">First name*:</label>
<input type="text" name="first_name" id="first_name" />
<br />
<label for="lastname">Last name*:</label>
<input type="text" name="last_name" id="last_name" />
<br />
<label for="phone_work">Primary phone*:</label>
<input type="text" name="phone_work" id="phone_work" onchange="validateHuman();"/>
<br />
<label for="email">Email*:</label>
<input type="text" name="email1" id="email1" onchange="validateEmailAdd();" />
<span style="padding-left:268px"><input type="submit" value="Download" name="Submit" class="button" onclick="submit_form();" />
</fieldset1>
<input type="hidden" name="lead_source" id="lead_source" value="Brochure Download" />
<input type="hidden" name="user" id="user" value="lead_capture_form" />
<input type="hidden" value="dbce057c" name="campaign_id" id="campaign_id" />
<input type="hidden" value="http://www.somewebsite.com/somearticle" name="redirect" id="redirect" />
<input type="hidden" value="blahblah" name="assigned_user_id" id="assigned_user_id" />
<input type="hidden" value="first_name;last_name;phone_work;email1;" name="req_id" id="req_id" />
<input type="hidden" value="<?php echo $article->category; ?>" name="area_of_interest_c" id="area_of_interest_c">
<input type="hidden" name="probability_c" id="probability_c" value="1" />
<input type="hidden" id="human" name="human" value="0">
</form>
This is my javascript for handling the form:
function submit_form(){
if(typeof(validateCaptchaAndSubmit)!='undefined'){
validateCaptchaAndSubmit();
}else{
check_webtolead_fields();
}
}
function check_webtolead_fields(){
if(document.getElementById('req_id') != null){
var reqs=document.getElementById('req_id').value;
reqs = reqs.substring(0,reqs.lastIndexOf(';'));
var req_fields = new Array();
var req_fields = reqs.split(';');
nbr_fields = req_fields.length;
var req = true;
for(var i=0;i<nbr_fields;i++){
if(document.getElementById(req_fields[i]).value.length <=0 || document.getElementById(req_fields[i]).value==0){
req = false;
break;
}
}
if(req && document.getElementById('human').value == '50'){
document.WebToLeadForm.action = "http://crm.somewebsite.com/index.php?entryPoint=WebToLeadCapture";
document.WebToLeadForm.submit();
window.location = document.getElementById('redirect').value;
return true;
}
else{
alert('Please provide all the required fields');
return false;
}
return false
}
else{
document.WebToLeadForm.action = "http://crm.somewebsite.com/index.php?entryPoint=WebToLeadCapture";
document.WebToLeadForm.submit();
window.location = document.getElementById('redirect').value;
}
}
function validateEmailAdd(){
if(document.getElementById('email1').value.length >0) {
if(document.getElementById('email1').value.match(/^\w+(['\.\-\+]?\w+)*#\w+([\.-]?\w+)*(\.\w{2,})+$/) == null){
alert('Not a valid email address');
}
}
}
function validateHuman(){
document.getElementById('human').value = "50";
}
Because you are submitting a form and trying to set the page's location at the same time. That is not going to happen. It is a race condition!
Either you will have to submit the form with Ajax can on the response you redirect OR you need the serverside to actually do the redirection!

Adding file inputs dynamically with jquery?

To make my weppage as compatible as possible I will go with the regular file input, the problem is that I need to offer multiple uploads.
My thought is that when the first input is set a second will be shown (up to a max of 10). Say that we have filled 5 and there is 6 visible. We now clear the second input, this will result in two empty inputs so then the last(6(empty)) input should be hidden.
Is this possible to to with Jquery?
Edit1: This is what I manage to create, it works fine. I am however sure that someone that know jquery better could make a smarter script:
In the view:
<div id="fileInput0" class="fileVisible">
<input type="file" id="file0" name="files" />
<input type="button" value="Töm" onclick="resetFileField(0)" />
</div>
<div id="fileInput1" class="fileHidden">
<input type="file" id="file1" name="files" />
<input type="button" value="Töm" onclick="resetFileField(1)" />
</div>
<div id="fileInput2" class="fileHidden">
<input type="file" id="file2" name="files" />
<input type="button" value="Töm" onclick="resetFileField(2)" />
</div>
<div id="fileInput3" class="fileHidden">
<input type="file" id="file3" name="files" />
<input type="button" value="Töm" onclick="resetFileField(3)" />
</div>
<div id="fileInput4" class="fileHidden">
<input type="file" id="file4" name="files" />
<input type="button" value="Töm" onclick="resetFileField(4)" />
</div>
<div id="fileInput5" class="fileHidden">
<input type="file" id="file5" name="files" />
<input type="button" value="Töm" onclick="resetFileField(5)" />
</div>
<div id="fileInput6" class="fileHidden">
<input type="file" id="file6" name="files" />
<input type="button" value="Töm" onclick="resetFileField(6)" />
</div>
<div id="fileInput7" class="fileHidden">
<input type="file" id="file7" name="files" />
<input type="button" value="Töm" onclick="resetFileField(7)" />
</div>
<div id="fileInput8" class="fileHidden">
<input type="file" id="file8" name="files" />
<input type="button" value="Töm" onclick="resetFileField(8)" />
</div>
<div id="fileInput9" class="fileHidden">
<input type="file" id="file9" name="files" />
<input type="button" value="Töm" onclick="resetFileField(9)" />
</div>
The Script:
function fileChangeHandler() {
var hiddenClass = 'fileHidden';
var visibleClass = 'fileVisible';
var parentDiv = $(this).parent;
var idNr = $(this).attr('id').replace('file', '');
idNr++;
if($(this).val().length > 0){
for(var i = idNr; i < 10; i++){
if($('#fileInput' + i).hasClass(visibleClass)){
if($('#file' + i).val().length < 1){ return;}
}
else{
$('#fileInput' + i).attr('class' , visibleClass);
return;
}
}
}
}
function resetFileField(id) {
var hiddenClass = 'fileHidden';
var visibleClass = 'fileVisible';
var counter;
$('#fileInput'+id).html($('#fileInput'+id).html());
$('#file'+id).change(fileChangeHandler);
for(var i = 9; i > -1 ;i--)
{
if(id != i)
{
if($('#fileInput' + i).hasClass(visibleClass)){
if($('#file' + i).val().length < 1){
$('#fileInput' + i).attr('class', hiddenClass);
}
}
}
}
}
What is a better solution?
You could have a container div which will harbor the new file input fields and a button to add new inputs:
$('#addFile').click(function() {
// when the add file button is clicked append
// a new <input type="file" name="someName" />
// to a filesContainer div
$('#filesContainer').append(
$('<input/>').attr('type', 'file').attr('name', 'someName')
);
});
Yes, you can just add a file input to the form as you would any other element:
$("#theForm").append("<input type='file' name='foo'>");
I thought this sounded familiar: [jquery]How do I add file uploads dynamically?
Another option, since you are using JQuery is the Bootstrap fileInput. It lets you upload multiple images with one control. You have additional options too like the allowed file types, size, height, width, etc.
<script type="text/javascript">
$("#postedImage").fileinput({
uploadUrl: "/SomeUrl", // you must set this for ajax uploads
maxFileCount: 10,
enctype: "multipart/form-data",
overwriteInitial: false
});
</script>
<input id="postedImage" type="file" class="file" multiple>
Here is a link for other uploaders if you are interested.
if you want to have diffrent input names
var i;
$('#addFile').click(function() {
i=i+1;
$('#filesContainer').append(
$('<input/>').attr('type', 'file').attr('name', 'file'+i)
);
});

Categories

Resources