I simply validate one input file and get the file name. but I can not do it with second one.
<div id="app">
<form action="#">
<label class="btn btn-xs btn-primary">
<input type="file" name="pic1" id="12" #change="onFileChangePic" multiple/>
Upload file
</label>
{{fileName}}
<div><input type="submit" value="submit" :disabled="vvv == false"></div>
</form>
</div>
<script>
const app = new Vue({
el: '#app',
data: {
fileName:null,
vvv:false
},
methods:{
onFileChangePic(event){
var fileData = event.target.files[0];
this.fileName=fileData.name;
if(fileData.type == 'application/pdf'){
this.vvv = true
}else{
this.vvv = false
}
console.log(event);
}
}
})
</script>
i want to add
<input type="file" name="pic2" id="13" #change="onFileChangePic" multiple/>
how can I validate the second input too?
methods:{
onFileChangePic(event){
let isGoodToGo = true
let files = event.target.files
for (let i=0; i<files.length; i++) {
let file = files[i]
if(file.type != 'application/pdf'){
isGoodToGo = false
}
}
this.vvv = isGoodToGo
}
}
Fiddle link: https://jsfiddle.net/shivampesitbng/k3h1x0jq/11/
Loop through all the files to check its type for validation.
Related
I need to search two addresses on the same webpage, one for location, one for correspondence. The first Google API Address works fine, I then tried duplicating the function and form modifying it, but it doesn't populate the second address, it always tries to populate the first address, can anyone tell me where I am going wrong please? Thanks for your help.
function initMap() {
const componentForm = [
'street_number',
'route',
'location',
'locality',
'administrative_area_level_2',
'postal_code',
];
const autocompleteInput = document.getElementById('location');
const options = {
types: ['(cities)'],
componentRestrictions: { country: 'gb' }
};
const autocomplete = new google.maps.places.Autocomplete(autocompleteInput);
autocomplete.addListener('place_changed', function () {
const place = autocomplete.getPlace();
if (!place.geometry) {
// User entered the name of a Place that was not suggested and
// pressed the Enter key, or the Place Details request failed.
window.alert('No details available for input: \'' + place.name + '\'');
return;
}
fillInAddress(place);
});
function fillInAddress(place) { // optional parameter
const addressNameFormat = {
'street_number': 'short_name',
'route': 'long_name',
'locality': 'long_name',
'administrative_area_level_2': 'short_name',
'postal_code': 'short_name',
};
const getAddressComp = function (type) {
for (const component of place.address_components) {
if (component.types[0] === type) {
return component[addressNameFormat[type]];
}
}
return '';
};
document.getElementById('location').value = getAddressComp('street_number') + ' '
+ getAddressComp('route');
for (const component of componentForm) {
// Location field is handled separately above as it has different logic.
if (component !== 'location') {
document.getElementById(component).value = getAddressComp(component);
}
}
}
}
function initMapAddress2() {
const componentForm = [
'street_number',
'route',
'location',
'locality',
'administrative_area_level_2',
'postal_code',
];
const autocompleteInput = document.getElementById('location2');
const options = {
types: ['(cities)'],
componentRestrictions: { country: 'gb' }
};
const autocomplete2 = new google.maps.places.Autocomplete(autocompleteInput);
autocomplete2.addListener('place_changed', function () {
const place2 = autocomplete2.getPlace();
if (!place2.geometry) {
// User entered the name of a Place that was not suggested and
// pressed the Enter key, or the Place Details request failed.
window.alert('No details available for input: \'' + place2.name + '\'');
return;
}
fillInAddress(place2);
});
function fillInAddress(place2) { // optional parameter
const addressNameFormat = {
'street_number2': 'short_name',
'route2': 'long_name',
'locality2': 'long_name',
'administrative_area_level_22': 'short_name',
'postal_code2': 'short_name',
};
const getAddressComp = function (type) {
for (const component of place2.address_components) {
if (component.types[0] === type) {
return component[addressNameFormat[type]];
}
}
return '';
};
document.getElementById('location2').value = getAddressComp('street_number2') + ' '
+ getAddressComp('route2');
for (const component of componentForm) {
// Location field is handled separately above as it has different logic.
if (component !== 'location2') {
document.getElementById(component).value = getAddressComp(component);
}
}
}
}
<div class="card-container">
<div class="panel">
<div>
<img class="sb-title-icon" src="https://fonts.gstatic.com/s/i/googlematerialicons/location_pin/v5/24px.svg" alt="">
<span class="sb-title">Correspondence Address</span>
</div>
<input type="text" placeholder="Search Address" id="location" />
<input type="text" placeholder="" id="street_number" />
<input type="text" placeholder="" id="route" />
<input type="text" placeholder="" id="locality" />
<div class="half-input-container">
<input type="text" class="half-input" placeholder="" id="administrative_area_level_2" />
<input type="text" class="half-input" placeholder="" id="postal_code" />
</div>
</div>
</div>
<script src="https://maps.googleapis.com/maps/api/js?key=****************Zv_k&libraries=places&callback=initMap&channel=GMPSB_addressselection_v1_cA" async defer></script>
<div class="card-container">
<div class="panel">
<div>
<img class="sb-title-icon" src="https://fonts.gstatic.com/s/i/googlematerialicons/location_pin/v5/24px.svg" alt="">
<span class="sb-title">Location Address</span>
</div>
<input type="text" placeholder="Search Address" id="location2" />
<input type="text" placeholder="" id="street_number2" />
<input type="text" placeholder="" id="route2" />
<input type="text" placeholder="" id="locality2" />
<div class="half-input-container">
<input type="text" class="half-input" placeholder="" id="administrative_area_level_22" />
<input type="text" class="half-input" placeholder="" id="postal_code2" />
</div>
</div>
</div>
<script src="https://maps.googleapis.com/maps/api/js?key=****************Zv_k&libraries=places&callback=initMapAddress2&channel=GMPSB_addressselection_v1_cA" async defer></script>
For anyone else having the same issue, I found a solution here Multiple Address on same page
I'm new to vueJS.
I want to add a required validator in image using vee-validate.
Built-in required validador isn't working so I created a custom validator img_required.
here's what I've done so far.
.vue html part
<ValidationProvider rules="image|img_required" bail="false" v-slot="{ errors, validate }">
<div class="row row-xs mg-t-20 mx-0">
<label class="col-sm-4 form-control-label">
<span class="tx-danger">*</span> Image:
</label>
<div
#dragover.prevent
#change="validate"
#drop.prevent
class="file-wrapper col-sm-8 mg-t-10 mg-sm-t-0"
>
<div v-if="imgUrl">
<button #click="imageNull" class="img-close">
<b-icon icon="x"></b-icon>
</button>
<img style="height: 127px" :src="imgUrl" />
</div>
<input type="text" hidden v-model="imgUrl" />
<div v-if="!imgUrl" #drop="handleImage($event, 'drop')">
<input
type="file"
class="form-control"
name="file"
accept="image/*"
#change="handleImage($event, 'input'); validate()"
/>
Drop image
</div>
</div>
</div>
<div v-for="error in errors" :key="error">{{ error }}</div>
</ValidationProvider>
I can't use v-model in input type file so I created a dummy hidden input field and passed imgUrl in v-model <input type="text" hidden v-model="imgUrl" />
imgUrl gets image src from file drop or input file.
I added a close button to nullify imgUrl variable.
<button #click="imageNull" class="img-close">
<b-icon icon="x"></b-icon>
</button>
I pass this imgUrl to vee-validate extend method.
.vue script part
data() {
return {
imgUrl: ""
}
},
methods: {
handleImage(e, action) {
var file;
if (action == "input") file = e.target.files[0];
else if (action == "drop") file = e.dataTransfer.files[0];
var reader = new FileReader();
reader.onload = (e) => {
this.imgUrl = e.target.result;
};
reader.readAsDataURL(file);
},
imageNull() {
this.imgUrl = "";
},
}
here's validation.js file
extend('img_required', {
validate(imgUrl) {
console.log(imgUrl);
return imgUrl !== "";
},
message() {
return "Image is required!";
}
});
Here I'm checking if imgUrl is an empty base64 string or not.
And when I hit close button, imgUrl nullifies.
The issue here is when I print this imgUrl it shows event.target.files.
I'm new to vue.js. Please tell me if I'm doing something wrong
I think the problem is that you're handleImage function is not correct
Try this;
var reader = new FileReader();
reader.readAsDataURL(file);
reader.onload = () => {
this.imgUrl = reader.result;
};
I am trying to upload a PDF file to Google Drive and insert the link to the file in Google Sheets. Here is the ajax:
$.ajax({
type: 'POST',
url: 'https://script.google.com/macros/s/AKfycbxyjjBv84uONFouZaiNeC2xwoMPP3p-3dzYxbQBCbJnEza0aPn-/exec',
data: serializedData,
success: function(result) {
var myMessage = $(document.activeElement).attr('id');
$('#sucessMessage2').html('<div class=\"successActive\">Your application has been successfully sent</div>');
document.getElementById("regform").reset();
},
error : function(error) {
alert('Error: Something went wrong. Please refresh the page and try again');
}
});
Here is the HTML:
<form id="regform">
<input id="FirstName" tabindex="1" name="FirstName" type="text" placeholder="First Name *" />
<input id="LastName" tabindex="2" name="LastName" type="text" placeholder="Last Name *" />
<input id="Occupation" tabindex="3" name="Occupation" type="text" placeholder="Occupation" />
<input name="Resume" type="file" tabindex="4" /><br/>
<div class="successMessage" id="sucessMessage2"></div>
<input class="btn-submit" id="submitFormTwo" tabindex="5" type="submit" value="Submit Application to Rent" />
</form>
And Code.gs:
var SHEET_NAME = "Sheet1";
var SCRIPT_PROP = PropertiesService.getScriptProperties(); // new property service
function doGet(e){
return handleResponse(e);
}
function doPost(e){
return handleResponse(e);
}
function handleResponse(e) {
var lock = LockService.getPublicLock();
lock.waitLock(30000); // wait 30 seconds before conceding defeat.
try {
var doc = SpreadsheetApp.openById(SCRIPT_PROP.getProperty("key"));
var sheet = doc.getSheetByName(SHEET_NAME);
var headRow = e.parameter.header_row || 1;
var headers = sheet.getRange(1, 1, 1, sheet.getLastColumn()).getValues()[0];
var nextRow = sheet.getLastRow()+1; // get next row
var row = [];
for (i in headers){
if (headers[i] == "Timestamp"){ // special case if you include a 'Timestamp' column
row.push(new Date());
} else { // else use header name to get data
row.push(e.parameter[headers[i]]);
}
}
sheet.getRange(nextRow, 1, 1, row.length).setValues([row]);
return ContentService
.createTextOutput(JSON.stringify({"result":"success", "row": nextRow}))
.setMimeType(ContentService.MimeType.JSON);
} catch(e){
return ContentService
.createTextOutput(JSON.stringify({"result":"error", "error": e}))
.setMimeType(ContentService.MimeType.JSON);
} finally { //release lock
lock.releaseLock();
}
}
function setup() {
var doc = SpreadsheetApp.getActiveSpreadsheet();
SCRIPT_PROP.setProperty("key", doc.getId());
}
Everything is populating in the Google Sheet, but I have no idea how to get the Resume to upload to Google Drive and add the link to the Google Sheet.
You can upload a file to drive with a combination of FileReader and google.script.run as following:
Modify <input name="Resume" type="file" tabindex="4" /><br/>
to
<input id = "pdf" name="Resume" type="file" tabindex="4" /><br/>
Modify
<input class="btn-submit" id="submitFormTwo" tabindex="5" type="submit" value="Submit Application to Rent" />
to
<input class="btn-submit" id="submitFormTwo" tabindex="5" type="submit" onClick="formSubmit()" value="Submit Application to Rent" />
Write the javascript function:
function formSubmit() {
var pdf = document.getElementById("pdf").files[0];
var reader = new FileReader();
if (pdf) {
reader.readAsDataURL(pdf);
reader.onloadend = function () {
google.script.run.getResume(reader.result);
}
}
}
In Code.gs, add the function
function getResume(pdf){
var mimeType = pdf.substring(5,pdf.indexOf(';'));
var bytes = Utilities.base64Decode(pdf.substr(pdf.indexOf('base64,')+7));
var title='my_pdf';
var blob = Utilities.newBlob(bytes, mimeType, title);
var file=DriveApp.createFile(blob);
var link = file.getUrl();
Logger.log(link);
}
Integrate link into your existing code as desired, e.g. push it into row and into the spreadsheet.
Explanation: You convert with FileReader the content of the pdf file
into a data URL. Apps Script can use this data URL to read the file as
a blob and convert the blob into a file on your drive.
UPDATE
A sample how to pass the form data completely with google.script.run without Ajax:
Index.html:
<form id="regform">
<input id="FirstName" tabindex="1" name="FirstName" type="text" placeholder="First Name *" />
<input id="LastName" tabindex="2" name="LastName" type="text" placeholder="Last Name *" />
<input id="Occupation" tabindex="3" name="Occupation" type="text" placeholder="Occupation" />
<input id = "pdf" name="Resume" type="file" tabindex="4" /><br/>
<input class="btn-submit" id="submitFormTwo" tabindex="5" type="submit" onClick="formSubmit()" value="Submit Application to Rent" />
</form>
<script>
function formSubmit() {
var firstName = document.getElementById("FirstName").value;
var lastName = document.getElementById("LastName").value;
var occupation = document.getElementById("Occupation").value;
var pdf = document.getElementById("pdf").files[0];
var reader = new FileReader();
if (pdf) {
reader.readAsDataURL(pdf);
reader.onloadend = function () {
google.script.run.withSuccessHandler(success).withFailureHandler(error).getResume(firstName, lastName, occupation, reader.result);
}
}
}
function success(){
alert ("Your application has been successfully sent");
}
function error(){
alert ("There was an error");
}
</script>
Code.gs
function doGet(){
return HtmlService.createHtmlOutput("index.html");
}
function getResume(firstName, lastName, occupation, pdf){
var mimeType = pdf.substring(5,pdf.indexOf(';'));
var bytes = Utilities.base64Decode(pdf.substr(pdf.indexOf('base64,')+7));
var title='my_pdf';
var blob = Utilities.newBlob(bytes, mimeType, title);
var file=DriveApp.createFile(blob);
var link = file.getUrl();
var doc = SpreadsheetApp.openById(SCRIPT_PROP.getProperty("key"));
var sheet = doc.getSheetByName(SHEET_NAME);
var values = [firstName, lastName, occupation, link];
var nextRow = sheet.getLastRow()+1;
sheet.getRange(nextRow, 1, 1, values.length).setValues([values]);
}
function setup() {
var doc = SpreadsheetApp.getActiveSpreadsheet();
SCRIPT_PROP.setProperty("key", doc.getId());
}
I am making a simple website that has a feature to upload images. I tried it Laravel way which I made it in blade template and it works fine. Now I am trying to make it inside Vue Components
Here's my Create.vue
<template>
<div>
<div class="row">
<input type="hidden" name="_token" :value="csrf">
<div class="col-md-5">
<div class="detail-container">
<label for="title">Book Title:</label>
<input type="text" name="title" id="title" v-model="book_title" class="form-control">
</div>
<div class="detail-container">
<label for="title">Book Description:</label>
<textarea type="text" name="description" id="description" v-model="book_description" class="form-control" rows="5"></textarea>
</div>
<div class="detail-container">
<label for="title">Tags:</label>
<multiselect v-model="tags" :show-labels="false" name="selected_tags" :hide-selected="true" tag-placeholder="Add this as new tag" placeholder="Search or add a tag" label="name" track-by="id" :options="tagsObject" :multiple="true" :taggable="true" #tag="addTag" #input="selectTags">
<template slot="selection" slot-scope="tags"></template>
</multiselect>
</div>
</div>
<div class="col-md-7">
<!-- BOOK COVER WILL GO HERE -->
<div class="detail-container">
<label>Book Cover:</label>
<input type="file" class="form-control-file" id="book_cover" name="selected_cover" #change="onFileChange">
<small id="fileHelp" class="form-text text-muted">After you select your desired cover, it will show the preview of the photo below.</small>
<div id="preview">
<img v-if="url" :src="url" height="281" width="180" />
</div>
</div>
</div>
<div class="detail-container" style="margin-top: 20px;">
<button class="btn btn-primary" #click="saveBook()">Next</button>
</div>
</div>
</div>
</template>
<script>
import Multiselect from 'vue-multiselect'
// register globally
Vue.component('multiselect', Multiselect)
export default {
// OR register locally
components: { Multiselect },
data () {
return {
csrf: document.querySelector('meta[name="csrf-token"]').getAttribute('content'),
url: null,
selected_cover: null,
tags: [],
tagsObject: [],
selected_tags: [],
book_title: '',
book_description: ''
}
},
methods: {
getTags() {
let vm = this;
axios.get('/admin/getTags').then(function(result){
let data = result.data;
for(let i in data) {
vm.tagsObject.push({id: data[i].id, name: data[i].name});
}
});
},
addTag (newTag) {
const tag = {
name: newTag,
id: newTag.substring(0, 2) + Math.floor((Math.random() * 10000000))
}
this.tagsObject.push(tag);
this.tags.push(tag);
},
selectTags(value) {
this.selected_tags = value.map(a=>a.id);
},
onFileChange(e) {
const file = e.target.files[0];
this.url = URL.createObjectURL(file);
this.selected_cover = file;
},
saveBook() {
const fd = new FormData();
fd.append('image', this.selected_cover, this.selected_cover.name)
console.log(this.selected_cover);
var book_details = {
'title': this.book_title,
'description': this.book_description,
'book_cover': this.selected_cover,
'tags': this.selected_tags
};
axios.post('/admin/saveBook', book_details).then(function(result){
console.log('done')
})
}
},
created() {
this.getTags();
}
}
</script>
<!-- New step!
Add Multiselect CSS. Can be added as a static asset or inside a component. -->
<style src="vue-multiselect/dist/vue-multiselect.min.css"></style>
and here's my controller
public function store(Request $request)
{
$this->validate(request(), [
'title' => 'required|min:5',
'description' => 'required|min:10',
'book_cover' => 'required|image|mimes:jpeg,jpg,png|max:10000'
]);
// File Upload
if($request->hasFile('book_cover')) {
$fileNameWithExt = $request->file('book_cover')->getClientOriginalName();
// GET FILE NAME
$filename = pathinfo($fileNameWithExt, PATHINFO_FILENAME);
// GET EXTENSION
$extension = $request->file('book_cover')->getClientOriginalExtension();
// File Unique Name
$fileNameToStore = $filename. '_'. time().'.'.$extension;
$path = $request->file('book_cover')->storeAs('public/book_covers', $fileNameToStore);
} else {
$fileNameToStore = 'noimage.jpg';
}
$book = new Book;
$book->title = request('title');
$book->description = request('description');
$book->book_cover = $fileNameToStore;
$book->save();
$book->tags()->sync($request->tags, false);
return back()->with('success', 'Book Created Successfully!');
}
I never touched my controller because this is what I used when I do this feature in Laravel Way but when I save it, the details are being saved but the image is not uploading instead it saves noimage.jpg in the database. Does anyone know what I am doing wrong?
i tried to add this part const fd = new FormData(); in book_details but when i console.log(fd) it returned no data.
you should pass the fd object and not the book_details in your POST request.
you could do it something like this.
onFileChange(e) {
const file = e.target.files[0];
// this.url = URL.createObjectURL(file);
this.selected_cover = file;
},
saveBook() {
const fd = new FormData();
fd.append('image', this.selected_cover)
fd.append('title', this.book_title)
fd.append('description', this.book_description)
fd.append('book_cover', URL.createObjectURL(this.selected_cover))
fd.append('tags', this.selected_tags)
axios.post('/admin/saveBook', fd).then(function(result){
console.log('done')
})
}
and also, you can't just console.log the fd in the console. what you can do instead is something like this
for (var pair of fd.entries()) {
console.log(pair[0]+ ', ' + pair[1]);
}
FormData is a special type of object which is not stringifyable and cannot just be printed out using console.log. (link)
I am validating two sections of a webpage the first validation section validates however the second validator is not for some reason.
$(function(){
/* first validation - works*/
jVal = {
//validate firstName
'firstName': function(){
//appends #firstNameInfo with .info to body
$('body').append('<div id="firstNameInfo" class="info"></div>');
//create variables
var firstNameInfo = $('#firstNameInfo');
var ele = $('#firstName');
var patt = /^[a-zA-Z][a-zA-Z]{1,20}$/;
if(!patt.test(ele.val())) {
jVal.errors = true;
firstNameInfo.removeClass('correct').addClass('error');
ele.removeClass('normal').addClass('wrong');
}else{
firstNameInfo.removeClass('error').addClass('correct');
ele.removeClass('wrong').addClass('normal');
}
},
//validate lastName
'lastName': function() {
$('body').append('<div id="lastNameInfo" class="info"></div>');
var lastNameInfo = $('#lastNameInfo');
var ele =$('#lastName');
var patt = /^[a-zA-Z][a-zA-Z]{1,20}$/;
if(!patt.test(ele.val())){
jVal.errors = true;
lastNameInfo.removeClass('correct').addClass('error');
ele.removeClass('normal').addClass('wrong');
}else{
lastNameInfo.removeClass('error').addClass('correct');
ele.removeClass('wrong').addClass('normal');
}
},
//validate phone
'phone' : function(){
$('body').append('<div id="phoneInfo" class="info"></div>');
var phoneInfo = $('#phoneInfo');
var ele = $('#phone');
var patt = /^((\+?1-)?\d\d\d-)?\d\d\d-\d\d\d\d$/;
if(!patt.test(ele.val())) {
jVal.errors = true;
phoneInfo.removeClass('correct').addClass('error');
ele.removeClass('normal').addClass('wrong');
}else{
phoneInfo.removeClass('error').addClass('correct');
ele.removeClass('wrong').addClass('normal');
}
},
//validate zipcode
'zip' : function() {
$('body').append('<div id="zipInfo" class="info"></div>');
var zipInfo = $("#zipInfo");
var ele = $('#content_form #zip');
var patt = /^\d\d\d\d\d$/;
if(!patt.test(ele.val())){
jVal.errors = true;
zipInfo.removeClass('correct').addClass('error');
ele.removeClass('normal').addClass('wrong');
}else{
zipInfo.removeClass('error').addClass('correct');
ele.removeClass('wrong').addClass('normal');
}
},
//submit button code
'sendForm':function(){
if(!jVal.errors){
$('#content_form').submit();
}
},
};
$('#content_form #submit').click(function(){
var obj = $.browser.webkit ? $('body') : $('html');
jVal.errors = false;
jVal.firstName();
jVal.lastName();
jVal.phone();
jVal.zip();
jVal.sendForm();
return false;
$('#firstName').change(jVal.firstName);
$('#lastName').change(jVal.lastName);
$('#email').change(jVal.email);
$('#content_form #zip').change(jVal.zip);
});
/**** Second Validation Does Not work ******/
kVal ={
'zip' : function() {
$('body').append('<div id="Infozip" class="info"></div>');
var Infozip = $("#Infozip");
var ele = $('#form #zip');
var patt = /^\d\d\d\d\d$/;
if(!patt.test(ele.val())){
kVal.error = true;
Infozip.removeClass('correct').addClass('error');
ele.removeClass('normal').addClass('wrong');
}else{
Infozip.removeClass('error').addClass('correct');
ele.removeClass('wrong').addClass('normal');
}
},
//submit button code
'send':function(){
if(!kVal.errors){
$('#form').submit();
}
},
};
$('#form button#submit').click(function(){
var obj = $.browser.webkit ? $('body') : $('html');
kVal.errors = false;
kVal.zip();
kVal.send();
return false;
$('#form #zip').change(kVal.zip);
});
}); /*main function closer*/
HTML FOR FIRST Validation -WORKING -
<div id="content_form">
<p>
<label class="block">
<input type="text" id="firstName" type="firstName" autocomplete="on" value="first name">
</label>
<label class="block">
<input type="text" id="lastName" type="lastName" autocomplete="on" value="last name">
</label>
<label class="block">
<input type="text" id="phone" type="phone" autocomplete="on" value="phone">
</label>
<label class="block">
<input type="text" id="zip" type="zip" autocomplete="on" value="zip code">
</label>
<button type="submit" id="submit" value="Submit" title="submit">submit</button>
</p>
</div><!-- end form -->
HTML FOR SECOND Validation
<div id="form">
<p>
<label class="block">
<input type="text" id="zip" type="zip" autocomplete="on" value="zip code">
</label>
<button type="submit" id="submit" value="CHECK NOW" title="check now">check now</button>
</p>
</div><!-- end form -->
You have the same id on both zip fields, which is probably causing your problems. The docs for the jQuery #id selector has this to say;
Each id value must be used only once within a document. If more than
one element has been assigned the same ID, queries that use that ID
will only select the first matched element in the DOM. This behavior
should not be relied on, however; a document with more than one
element using the same ID is invalid.
That is, your selection in $('#form #zip').change(kVal.zip); will not use the hierarchy under #form to find #zip, it will still find the first instance in the entire DOM.