I'm using the jquery autocomplete to fetch data from a coldfusion CFC and display matching data when a user types.
That part is working, but I'd like to disable the submit button and show a message if there is data returned as that tells me that the data is not unique, which it needs to be.
I can sort of make it work but once my message appears "Name MUST BE Unique" and the button disables, it doesn't re-enable and make that message change to "Name is Unique".
What am I doing wrong?
Here is my CFC:
<cffunction name="lookupCustomers" access="remote" output="no" hint="I return a list of customers" returnformat="JSON">
<cfargument name="term" required="false" default="" />
<!--- Define variables --->
<cfset var returnArray =ArrayNew(1)>
<!--- Do search --->
<cfquery name="data" datasource="#datasource#">
select company_name
From customer_table
where company_name LIKE <cfqueryparam cfsqltype="cf_sql_varchar" value="%#arguments.term#%" />
order by company_name
</cfquery>
<cfif #data.recordcount# eq 0>
<!--- Build result array --->
<cfset titleStruct = structNew() />
<cfset titleStruct['value'] = 'No results'/>
<cfset titleStruct['label'] = 'No results' />
<cfset arrayAppend(returnArray,titleStruct) />
<!--- And return it --->
<cfreturn returnArray />
<cfelse>
<!--- Build result array --->
<cfloop query="data">
<cfset titleStruct = structNew() />
<cfset titleStruct['value'] = company_name/>
<cfset titleStruct['label'] = company_name />
<cfset arrayAppend(returnArray,titleStruct) />
</cfloop>
<!--- And return it --->
<cfreturn returnArray />
</cfif>
</cffunction>
Here is my Javascript:
<!---Autocomplete for customer name--->
<script>
$(document).ready(function() {
$( "#new_customer_name" ).autocomplete({
source: "cfcs/existing_customers_lookup.cfc?method=lookupCustomers&returnformat=json",
minLength: 1,
select: function(event, ui) {
$('#new_customer_name').val(ui.item.value);
},
response: function(event, ui) {
// ui.content is the array that's about to be sent to the response callback.
if (ui.content.length == 0) {
$("#empty-message").text( "" );
//$("#empty-message").text( "Name is Unique" );
$("#add_new_customer_btn").prop('disabled', False);
} else if (ui.content.length != 0) {
$("#empty-message").text( "Name MUST BE Unique" );
$("#add_new_customer_btn").prop('disabled', true);
}
}
});
});
</script>
Here is my form:
<!--- New customer modal --->
<div id="new-customer-modal" style="display:none; width:50%; padding:10px;">
<fieldset>
<legend><h1>New Customer Form</h1></legend>
<form name="add_customer" id="add_customer">
<input name="new_customer_name" id="new_customer_name" type="text" required placeholder="Customer Name"><br><br>
<strong>Primary Contact*:</strong><br>
<input name="new_first_name" id="new_first_name" type="text" required placeholder="First Name*">
<input name="new_middle_name" id="new_middle_name" type="text" placeholder="Middle Initial/Name" size="15">
<input name="new_last_name" id="new_last_name" type="text" required placeholder="Last Name*">
<br><br>
<input name="new_email_address" id="new_email_address" type="email" required placeholder="Email Address"><br>
<input name="new_primary_phone" id="new_primary_phone" type="text" required placeholder="Primary Phone Number"><br>
<input name="new_alternate_phone" id="new_alternate_phone" type="text" placeholder="Alternate Phone Number"><br><br>
<strong>Company Address:</strong><br>
<input name="new_address1" id="new_address1" type="text" required placeholder="Address 1"><br>
<input name="new_address2" id="new_address2" type="text" placeholder="Address 2"><br>
<input name="new_city" id="new_city" type="text" required placeholder="City"><br>
<input name="new_state" id="new_state" type="text" required placeholder="State"><br>
<input name="new_zip" id="new_zip" type="text" required placeholder="Zip"><br><br>
<br><br>
<input type="hidden" name="customer_type" value="billable">
<input type="hidden" name="ticket_type" value="billable">
<input class="stylized_btn" type="submit" value="Add Customer"><div class="response" id="addCustomerMessage"></div>
</form>
</fieldset>
I was able to eventually figure this out my self. I created a separate function to check the name being entered into the field. The big difference was return a string instead of a query and testing the output that way.
In that function I included an if statement to perform tasks based on the results. I also created another CFC function dedicated to querying the database based on what was entered.
Hope this helps someone.
Here is my javascript:
<script>
$(document).ready(function() {
$( "#new_customer_name" ).autocomplete({
source: "cfcs/existing_customers_lookup.cfc?method=lookupCustomers&returnformat=json",
minLength: 1,
select: function(event, ui) {
$('#new_customer_name').val(ui.item.value);
},
response: function(event, ui) {
}
});
});
</script>
<script>
function check_customer_name() {
<!--- Get customer name --->
$.ajax({
dataType: 'json',
data: {
check_customer_name: $('#new_customer_name').val()
},
url: "cfcs/existing_customers_lookup.cfc?method=checkCustomers&returnformat=json",
beforeSend: function(){
$('.loader').show();
},
complete: function(){
$('.loader').hide(3000);
},
success: function(response) {
// ui.content is the array that's about to be sent to the response callback.
console.log(response);
if ( response == 'unique') {
document.getElementById("empty-message").style.color = 'green';
document.getElementById('empty-message').innerHTML = "This company name is unique.";
$("#add_new_customer_btn").prop('disabled', false);
} else {
document.getElementById("empty-message").style.color = 'red ';
document.getElementById('empty-message').innerHTML = "Company name not unique. Please try again.";
$("#add_new_customer_btn").prop('disabled', true);
}
}
});
}
</script>
Here is my form:
<fieldset>
<legend><h1>New Customer Form</h1></legend>
<form name="add_customer" id="add_customer" method="post" action="actionpages/add_customer.cfm">
<input name="new_customer_name" id="new_customer_name" type="text" required placeholder="Customer Name" onblur:"check_customer_name();" onFocus="check_customer_name();" onChange="check_customer_name();"><pre class="response" id="empty-message"></pre><br><br>
<strong>Primary Contact*:</strong><br>
<input name="new_first_name" id="new_first_name" type="text" required placeholder="First Name*">
<input name="new_middle_name" id="new_middle_name" type="text" placeholder="Middle Initial/Name" size="15">
<input name="new_last_name" id="new_last_name" type="text" required placeholder="Last Name*">
<br><br>
<input name="new_email_address" id="new_email_address" type="email" required placeholder="Email Address"><br>
<input name="new_primary_phone" id="new_primary_phone" type="text" required placeholder="Primary Phone Number"><br>
<input name="new_alternate_phone" id="new_alternate_phone" type="text" placeholder="Alternate Phone Number"><br><br>
<strong>Company Address:</strong><br>
<input name="new_address1" id="new_address1" type="text" required placeholder="Address 1"><br>
<input name="new_address2" id="new_address2" type="text" placeholder="Address 2"><br>
<input name="new_city" id="new_city" type="text" required placeholder="City"><br>
<input name="new_state" id="new_state" type="text" required placeholder="State"><br>
<input name="new_zip" id="new_zip" type="text" required placeholder="Zip"><br><br>
<br><br>
<input type="hidden" name="customer_type" value="billable">
<input type="hidden" name="ticket_type" value="billable">
<input class="stylized_btn" type="submit" value="Add Customer"><div class="response" id="addCustomerMessage"></div>
</form>
</fieldset>
Here are my CFC functions:
<cffunction name="lookupCustomers" access="remote" output="no" hint="I return a list of customers" returnformat="JSON">
<cfargument name="term" required="false" default="" />
<!--- Define variables --->
<cfset var returnArray =ArrayNew(1)>
<!--- Do search --->
<cfquery name="data" datasource="#datasource#">
select company_name
From customer_table
where company_name LIKE <cfqueryparam cfsqltype="cf_sql_varchar" value="%#arguments.term#%" />
order by company_name
</cfquery>
<!--- Build result array --->
<cfloop query="data">
<cfset titleStruct = structNew() />
<cfset titleStruct['value'] = company_name/>
<cfset titleStruct['label'] = company_name />
<cfset arrayAppend(returnArray,titleStruct) />
</cfloop>
<!--- And return it --->
<cfreturn returnArray />
</cffunction>
<cffunction name="checkCustomers" access="remote" output="no" hint="I return a list of customers" returnformat="string">
<cfargument name="check_customer_name" required="false" default="" />
<!--- localize function variables --->
<cfset var data = "">
<!--- Do search --->
<cfoutput>
<cfquery name="data" datasource="#datasource#">
select company_name
From customer_table
where company_name = <cfqueryparam value="#ARGUMENTS.check_customer_name#" cfsqltype="cf_sql_varchar">
</cfquery>
<cfif #data.recordcount# eq 0>
<cfset result = "unique">
<cfelse>
<cfset result = "taken">
</cfif>
<!--- And return it --->
<cfreturn result />
</cfoutput>
</cffunction>
Related
I have an HTML form and I'm wondering how I can set that info when submitted to the variables in my js file.
HTML
<input id="column-left" type="text" name="first-name" placeholder="First Name"/>
<input id="column-right" type="text" name="last-name" placeholder="Last Name"/>
<input id="input-field" maxlength="16" type="text" name="number" placeholder="Card Number"/>
<input id="column-left" maxlength="4" type="text" name="expiry" placeholder="MM / YY"/>
<input id="column-right" maxlength="3" type="text" name="cvc" placeholder="CCV"/>
(Leaving out unimportant info)
JS
var order_info = {name: "your name", // your first and last name
email: "your#email.com", // your email
phone: "5555555555", // your phone number
address1: "123 street lane", // your street address
address2: "apartment 1", // leave blank if you dont have one
zip_code: "00000", // your zip code
city: "New York", // city
state_code: "NY", // state code, if you dont know this then look it up son
country: "USA" // only two options, "USA" or "CANADA"
};
I need to set the info from the form into these fields.
One of many ways to get values from html form tag to Javascript object.
document.querySelector("#myForm").addEventListener("keyup", function(){
var data = {};
var inputs = document.querySelectorAll('input');
inputs.forEach(input => {
data[input.name] = input.value;
});
document.querySelector("#text").innerText = JSON.stringify(data);
});
document.querySelector("#myForm").dispatchEvent(new Event('keyup'));
<form id="myForm">
<input value="Niklesh" type="text" name="first_name" placeholder="First Name"/>
<input value="Raut" type="text" name="last_name" placeholder="First Name"/>
<input value="" type="text" name="email" placeholder="Email"/>
<div id='text'></div>
</form>
var fname = document.getElementById("fname").value;
var lname = document.getElementById("lname").value;
var card = document.getElementById("card").value;
var expire = document.getElementById("expire").value;
var cvc = document.getElementById("cvc").value;
var order_info = {
fname: fname ? fname : '',
lname: lname ? lname : '',
card: card ? card : '',
expire: expire ? expire : '',
cvc: cvc ? cvc: ''
}
console.log(order_info);
<input id="fname" type="text" name="first-name" value="sourav" placeholder="First Name"/>
<input id="lname" type="text" name="last-name" value="singh" placeholder="Last Name"/>
<input id="card" maxlength="16" type="text" name="number" value="" placeholder="Card Number"/>
<input id="expire" maxlength="4" type="text" name="expiry" value="08/12" placeholder="MM / YY"/>
<input id="cvc" maxlength="3" type="text" name="cvc" value="111" placeholder="CCV"/>
First you should define a unique ID to each input you have, then get the value of this ID using javascript document.getElementById('ID').value or using jQuery $('ID').val().
Second part, you must match your number of inputs with your array.
Now you have an array of data, do what ever you want to do with it.
document.getElementById("save").addEventListener("click", function() {
var order_info = {
firstName: document.getElementById('first-name').value,
lastName: document.getElementById('last-name').value,
number: document.getElementById('number').value,
expiry: document.getElementById('expiry').value,
cvc: document.getElementById('cvc').value,
};
console.log(order_info);
});
<input id="first-name" type="text" name="first-name" placeholder="First Name"/>
<input id="last-name" type="text" name="last-name" placeholder="Last Name"/>
<input id="number" maxlength="16" type="text" name="number" placeholder="Card Number"/>
<input id="expiry" maxlength="4" type="text" name="expiry" placeholder="MM / YY"/>
<input id="cvc" maxlength="3" type="text" name="cvc" placeholder="CCV"/>
<button id="save">Save Data</button>
if you want to serialise data;
var order_info = $('form').serializeArray();
if you want to use formdata :
var fd = new FormData();
var order_info = $('form').serializeArray();
$.each(order_info,function(key,input){
fd.append(input.name,input.value);
});
Using the DOM (Document Object Model) you can access the values of the HTML components.
For example, given your code, you can lookup the element by its "id":
var lastname = document.getElementById("column-right");
var cardnumber = document.getElementById("input-field");
... etc
You can also lookup the element by using the value of its "name" attribute:
var lastname = document.getElementsByName("last-name");
var cardnumber = document.getElementsByName("number");
Tip: You normally do this when the page is loaded (event "onload") and if the values are received by the same page, it needs to implement typically the scenario of the first load as well (where the values are null, not initialized).
Javascript references:
https://www.w3schools.com/jsref/met_doc_getelementsbyname.asp
https://www.w3schools.com/jsref/met_document_getelementbyid.asp
You can use JQuery .serializeArray() method to do so.
like this:
var x = $("form").serializeArray();
You should get Key:Value pairs of all the text fields and their values by doing so.
We have a form and need to iterate over some elements to get the final sum to put in a "total" element.
E.g., here is a working starter script. It doesn't NOT iterate over the other ones. It does NOT consider the elements "item*", below, yet but should. Keep reading.
<script>
$( document ).ready(function() {
$('#taxsptotal').keyup(calcgrand);
$('#shiptotal').keyup(calcgrand);
$('#disctotal').keyup(calcgrand);
function calcgrand() {
var grandtot = parseFloat($('#subtotal').val(), 10)
+ parseFloat($("#taxsptotal").val(), 10)
+ parseFloat($("#shiptotal").val(), 10)
- parseFloat($("#disctotal").val(), 10)
$('#ordertotal').val(grandtot);
}
});
</script>
We are adding more to this. Think of having many items in a cart and each one has the same elements for the following where "i" is a number designating an individual item.
<!-- ordertotal = sum of #subtotal, #taxptotal, #shiptotal and #disctotal -->
<input type="text" id="ordertotal" name="ordertotal" value="106.49">
<input type="text" id="taxsptotal" name="taxsptotal" value="6.72">
<input type="text" id="shiptotal" name="shiptotal" value="15.83">
<input type="text" id="disctotal" name="disctotal" value="0.00">
<!-- sum of the cart "itemtotal[i]" -->
<input type="text" id="subtotal" name="subtotal" value="83.94">
<!-- cart items
User can change any itemprice[i] and/or itemquantity[i]
itemtotal[i] = sum(itemquantity[i] * itemprice[i])
-->
<input type="text" name="itemtotal[1]" value="8.97" />
<input type="text" name="itemquantity[1]" value="3" />
<input type="text" name="itemprice[1]" value="2.99" />
<input type="text" name="itemtotal[2]" value="4.59" />
<input type="text" name="itemquantity[2]" value="1" />
<input type="text" name="itemprice[2]" value="4.59" />
<input type="text" name="itemtotal[3]" value="0.99" />
<input type="text" name="itemquantity[3]" value="10" />
<input type="text" name="itemprice[3]" value="9.90" />
(1) User can change any itemprice[i] and/or itemquantity[i], so each needs a keyup. I can do that in php as it iterates over the items.
(2) These elements will have a $('.itemtotal[i]').keyup(calcgrand); (Or function other than calcgrand, if needed) statement, too. That keyup can be added by the php code as it evaluates the items in the cart.
(3) When an element is changed, then the script should automatically (a) calculate the $('[name="itemtotal[i]"]').val() and (b) replace the value for $('[name="itemtotal[i]"]').val().
(4) Then, the script above will use the $('[name="itemtotal[i]"]').val() to (a) replace the #subtotal value and (b) use that value in the equation.
Can someone help me with this? I am stuck on how to iterate over the [i] elements.
p.s. Any corrections/enhancements to the above code is appreciated, too.
Add a custom class to the desired inputs to sum:
HTML:
<input type="text" class="customclass" name=itemtotal[1] value="8.97" />
<input type="text" class="customclass" name=itemquantity[1] value="3" />
<input type="text" class="customclass" name=itemprice[1] value="2.99" />
JS:
var sum = 0;
$.each('.customclass',function(i, item){
sum = sum + Number($(this).val());
})
alert(sum);
if you for example group your inputs by giving them a class, or have each group in a div like so:
<!-- ordertotal = sum of #subtotal, #taxptotal, #shiptotal and #disctotal -->
<input type="text" id="ordertotal" name="ordertotal" value="106.49">
<input type="text" id="taxsptotal" name="taxsptotal" value="6.72">
<input type="text" id="shiptotal" name="shiptotal" value="15.83">
<input type="text" id="disctotal" name="disctotal" value="0.00">
<!-- sum of the cart "itemtotal[i]" -->
<input type="text" id="subtotal" name="subtotal" value="83.94">
<!-- cart items
User can change any itemprice[i] and/or itemquantity[i]
itemtotal[i] = sum(itemquantity[i] * itemprice[i])
-->
<div class="group">
<input type="text" name="itemtotal[1]" value="8.97" />
<input type="text" name="itemquantity[1]" value="3" />
<input type="text" name="itemprice[1]" value="2.99" />
</div>
<div class="group">
<input type="text" name="itemtotal[2]" value="4.59" />
<input type="text" name="itemquantity[2]" value="1" />
<input type="text" name="itemprice[2]" value="4.59" />
</div>
<div class="group">
<input type="text" name="itemtotal[3]" value="0.99" />
<input type="text" name="itemquantity[3]" value="10" />
<input type="text" name="itemprice[3]" value="9.90" />
</div>
Then you could do the following in javascript:
function calcSubTotal() {
$('[name^="itemtotal"]').each(function(i){
var sum = 0;
$('[name^="itemtotal"]').each(function(i){
sum += $(this).val();
});
$('#subtotal').val(sum);
});
}
$('.group').each(function(i) {
var total = $(this).find('[name^="itemtotal"]');
var qnt = $(this).find('[name^="itemquantity"]');
var price = $(this).find('[name^="itemprice"]');
total.keyup(function(e){
price.val(total.val() * qnt.val());
calcSubTotal();
});
qnt.keyup(function(e){
price.val(total.val() * qnt.val());
calcSubTotal();
});
});
$("[name^='itemprice'], [name^='itemquantity']").keyup(function(){
var input_name = $(this).attr('name');
var temp_name_split = input_name.split(/[\[\]]+/);
var temp_total = parseInt($('[name="itemquantity['+temp_name_split[1] +']"]').val()) * parseFloat($('[name="itemprice['+temp_name_split[1] +']"]').val());
$('[name="itemtotal['+temp_name_split[1]+']"]').val(temp_total.toFixed(2));
var total = 0;
$("[name^='itemtotal']").each(function() {
total += parseFloat($(this).val());
});
$('#subtotal').val(total.toFixed(2));
});
I have an html form with some inputs type=text. I can clone every input but I would like to recover the name to insert informations in my database. Therefore, I have to increment all the name. I can increment only one type of input and not multiple.
<body>
<button id="clone">Cloner</button>
<button id="removebutton">Remove</button>
<form id="myForm">
<div class="equipment" id="eqp">
<h4 class="title4">EQUIPEMENT 1 / EQUIPMENT 1</h4>
<label>Date de prêt / Loan date:</label>
<input type="text" name="loandate" id="datepicker" placeholder="ex: 20170101"/><br/><br/>
<label>Nom du produit / Product Name:</label>
<input type="text" name="productname" placeholder="ex: Asus"/><br/><br/>
<label>Type:</label>
<input type="text" name="type"/><br/><br/>
<label>Numéro de série / Serial Number:</label>
<input type="text" name="serialnumber" placeholder="ex: A003565DS65"/><br/><br/>
<label>Statuts / Status:</label>
<select name="status">
<option>gg</option>
<option>hh</option>
</select><br/><br/>
</div>
</form>
</body>
</html>
JS :
$('#clone').click(function () {
$('#myForm').append($('#eqp:last').clone());
$('#myForm div').each(function (i) {
var textinput1 = $(this).find('input');
var textinput2 = $(this).find('input[text="productname"]');
var select = $(this).find('select');
i++;
textinput1.eq(0).attr('name', 'loandate' + i);
select.eq(0).attr('name', 'status' + i);
});
});
$("#removebutton").click(function() {
if ($('.equipment').length > 1)
$('.equipment:last').remove()
});
//});
Thanks for your help !
Use <input name="loandate[]" >
You won't need to increment name, you will get the result as Array
Here's what you need to change into your HTML and JS:
$('#clone').click(function () {
$('#myForm').append($('.equipment:last').clone());
$('#myForm div').each(function (i) {
});
});
$("#removebutton").click(function() {
if ($('.equipment').length > 1)
$('.equipment:last').remove()
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button id="clone">Cloner</button>
<button id="removebutton">Remove</button>
<form id="myForm">
<div class="equipment">
<h4 class="title4">EQUIPEMENT 1 / EQUIPMENT 1</h4>
<label>Date de prêt / Loan date:</label>
<input type="text" name="loandate[]" id="datepicker" placeholder="ex: 20170101"/><br/><br/>
<label>Nom du produit / Product Name:</label>
<input type="text" name="productname[]" placeholder="ex: Asus"/><br/><br/>
<label>Type:</label>
<input type="text" name="type[]"/><br/><br/>
<label>Numéro de série / Serial Number:</label>
<input type="text" name="serialnumber[]" placeholder="ex: A003565DS65"/><br/><br/>
<label>Statuts / Status:</label>
<select name="status[]">
<option>gg</option>
<option>hh</option>
</select><br/><br/>
</div>
</form>
Consider that you had error into your html. Equipment div element has an ID (#eqp). After cloning that div you're getting multiple elements with the same ID. (That's not good).
What you need to change is:
Remove that ID and use class selector
Edit form names like this: name[]
Simplify your JS. No need to set different names for each element
Into your PHP manipluate with them as an array.
PHP Example:
$i = 0;
do{
$loandate = $_POST['loandate'][$i];
$type = $_POST['type'][$i]
//...
$i++;
}while(isset($_POST['loandate'][$i]))
My website is trackschoolbus.com. You can see a login form at the top right. What I have set up is when a wrong input is given it redirects to home page with a parameter as ?er=1 i.e. http://www.trackschoolbus.com/?er=1.
I need to display a error message when the error url comes so I have written
<script type="text/javascript">
$(function(){
if (document.location.href.indexOf('er=1') > 0)
$("#display").show();
});
</script>
and the html is
<div id="display" style="display:none;">wrong input</div>
my login form is
<form name="login-form" id="login-form" method="post" action="http://www.trackschoolbus.com/vehicleTracking/index.php">
<input name="LoginForm[username]" id="LoginForm_username" type="text" placeholder="Registered Email" value="" class="error" required/>
<input maxlength="30" name="LoginForm[password]" id="LoginForm_password" type="password" placeholder="Password" value="" class="error" required />
<input type="submit" onclick="this.disabled=true;this.form.submit();" name="yt0" class="btn-submit" value="Login" />
</form>
still it shows display none.
use php
<form name="login-form" id="login-form" method="post" action="http://www.trackschoolbus.com/vehicleTracking/index.php">
<input name="LoginForm[username]" id="LoginForm_username" type="text" placeholder="Registered Email" value="" class="error" required/>
<input maxlength="30" name="LoginForm[password]" id="LoginForm_password" type="password" placeholder="Password" value="" class="error" required />
<input type="submit" onclick="this.disabled=true;this.form.submit();" name="yt0" class="btn-submit" value="Login" />
<?php if (isset($_GET['er']) && $_GET['er'] == 1) {
echo '<div id="display">wrong input</div>';
}?>
</form>
You can use this code
if ($_REQUEST['er']==1)
{
echo '<script type="text/javascript">
$("#display").show();
</script>';
}
This is relatively simple in javascript.
Using the code snippet in this thread: How can I get query string values in JavaScript?
function getParameterByName(name) {
name = name.replace(/[\[]/, "\\[").replace(/[\]]/, "\\]");
var regex = new RegExp("[\\?&]" + name + "=([^&#]*)"),
results = regex.exec(location.search);
return results === null ? "" : decodeURIComponent(results[1].replace(/\+/g, " "));
}
if (getParameterByName("er") == "1")
$("#display").show();
});
I have created a .hta form that connects to an excel file. The data entered is pasted in the spreadsheet. I have two problems with this code and I can't seem to figure out what I am doing wrong.
<html>
<head>
<script>
function test() {
var excel = new ActiveXObject("Excel.Application");
excel.visible = true;
var wb = excel.Workbooks.Open("C:\\Users\\Dane\\Desktop\\1.xlsx");
var optionValue;
var s = Form1.select1;
var data = [];
var sCell = wb.sheets("sheet1").cells(1,1).currentregion.offset(1);
data.push(Form1.text1.value);
data.push(Form1.text2.value);
data.push(Form1.text3.value);
data.push(Form1.text4.value);
data.push(s.options[s.selectedIndex].text);
data.push(Form1.text5.value);
data.push(Form1.text6.value);
data.push(Form1.text7.value);
for(var i=0;i<Form1.option1.length;i++) {
if(Form1.option1[i].checked){
data.push(Form1.option1[i].value);
break;
}
}
for(var i=0; i<data.length;i++) {
sCell.offset(0,i) = data[i];
}
for(var i=0;i<Form1.option2.length;i++) {
if(Form1.option2[i].checked){
data.push(Form1.option2[i].value);
break;
}
}
for(var i=0; i<data.length;i++) {
sCell.offset(0,i) = data[i];
}
wb.close(true);
}
</script>
</head>
<body>
<form name="Form1">
<p>
Entry 1: <input name="text1" type="text" size="10" /><br />
Entry 2: <input name="text2" type="text" size="10" /><br />
Entry 3: <input name="text3" type="text" size="10" /><br />
Entry 4: <input name="text4" type="text" size="10" /><br />
Selection 1: <select name="select1">
<option value="1">A</option>
<option value="2">B</option>
<option value="3">C</option>
<option value="4">D</option>
<option value="5">E</option>
<option value="6">F</option>
</select> <br />
Entry 5: <input name="text5" type="text" size="10" /><br />
Entry 6: <input name="text6" type="text" size="10" /><br />
Entry 7: <input name="text7" type="text" size="10" /><br />
Question 1<br />
Yes : <input type="radio" name="option1" value="Yes"><br />
No : <input type="radio" name="option1" value="No"><br />
N/A : <input type="radio" name="option1" value="N/A"><br />
Question 2<br />
Yes : <input type="radio" name="option2" value="Yes"><br />
No : <input type="radio" name="option2" value="No"><br />
N/A : <input type="radio" name="option2" value="N/A"><br />
<input type="button" value="Save to Excel" onclick="test()" />
</form>
</body>
Problems:
The last radio button value is repeated a few times at the end of the spreadsheet.
When the user uses the program a second time, the previous data is overwritten.
Sample to download (make sure to change the file path):
http://www.filedropper.com/new_3
I believe the second problem is caused because this is in your code twice:
for(var i=0; i<data.length;i++) {
sCell.offset(0,i) = data[i];
}
Once you have your array of data, you shouldn't have to cycle through it twice.
For the first problem, I believe it's created by this line:
var sCell = wb.sheets("sheet1").cells(1,1).currentregion.offset(1);
You are saying in essence "select this region here" not "start at this region." Unfortunately, I don't know the code for what you need, but that's my interpretation.