Convert mutlidimensional inputs to JavaScript object - javascript

I've been trying to solve this one for several days now and it's driving me nuts. I have some data that needs to be submitted by Ajax. It is dynamic, so I don't know how many fields it has. On top of that the names of the fields are multidimensional and also dynamic. For example one might have inputs with the name data[name] and data[title] whilst another larger one might have data[images][0][src], data[images][0][alt], data[images][0][description], data[images][1][src], data[images][1][alt], data[images][1][description] with an unknown number of elements to the array. My problem is that I need to get an object I can submit via Ajax whilst maintaining the structure of the data.
I've tried serialising the data, but that just comes up with a string of name = value. I've tried serialise array as well, but that just gives me an array of [name, value]. I've managed to generate the object manually using a regex to split it up, but I can't find a way to merge the resultant objects together. The latest version of my code is:
$('.modal-content').find('input[name^="data"]').each(function () {
var found = $(this).attr('name').match(re).reverse();
var temp = $(this).val();
$.each(found, function ()
{
str = this.substr(1, this.length - 2);
var t = {};
t[str] = temp;
temp = t;
});
data = $.each({}, data, temp);
});
Unfortunately it doesn't merge them, it overwrites what is in data with what is in temp. If data has data.images[0].src = "mysrc" and temp has data.images[0].alt = "myalt" then I just end up with data.images[0].alt = "myalt" and src is no longer there.
There has to be a simple way to do this, hell at this point I'd even take a complicated way to do this. Can someone please help me with this?

Although there is already an accepted answer. Here are my 5 cents:
IMHO working with regex should be avoided when possible. So my suggestion would be to change the HTML a bit, adding some classes to the div that contain the image and change the name attribute of the inputs:
<li class="col-xs-12 col-sm-6 col-md-4 col-lg-3 gallery-image ui-sortable-handle">
<div class="my-image">
<img src="http://localhost:8000/img/example.jpg">
<input type="hidden" name="src" value="img/example.jpg">
<div class="form-group">
<label for="title-0">Title:</label>
<input type="text" name="title" class="form-control" id="title-0" value="Default Example Image 1" placeholder="Title">
</div>
<div class="form-group">
<label for="description-0">Description:</label>
<input type="text" name="description" class="form-control" id="description-0" value="A default example image." placeholder="Description">
</div>
<div class="form-group">
<label for="alt-0">Alt tag (SEO):</label>
<input type="text" name="alt" class="form-control" id="alt-0" value="fluid gallery example image" placeholder="Alt tag">
</div>
<div class="form-group">
<label for="order-0">Order:</label>
<input type="number" name="order" class="form-control image-order" id="order-0" value="0">
</div>
<button type="button" class="btn btn-danger remove-gallery-image-btn">× Delete</button>
</div>
</li>
<li class="col-xs-12 col-sm-6 col-md-4 col-lg-3 gallery-image ui-sortable-handle">
<div class="my-image">
<img src="http://localhost:8000/img/example.jpg">
<input type="hidden" name="src" value="img/example.jpg">
<div class="form-group">
<label for="title-1">Title:</label>
<input type="text" name="title" class="form-control" id="title-1" value="Default Example Image 2" placeholder="Title">
</div>
<div class="form-group">
<label for="description-1">Description:</label>
<input type="text" name="description" class="form-control" id="description-1" value="A default example image." placeholder="Description">
</div>
<div class="form-group">
<label for="alt-1">Alt tag (SEO):</label>
<input type="text" name="alt" class="form-control" id="alt-1" value="fluid gallery example image" placeholder="Alt tag">
</div>
<div class="form-group">
<label for="order-1">Order:</label>
<input type="number" name="order" class="form-control image-order" id="order-1" value="1">
</div>
<button type="button" class="btn btn-danger remove-gallery-image-btn">× Delete</button>
</div>
</li>
Then build the object matching this class:
var obj = {
data: {
images: []
}
}
var groups = $('.my-image');
groups.each(function(idx, el) {
var child = {}
$(el).find('input').each(function(jdx, info){
var $info = $(info);
child[$info.attr('name')] = $info.val();
});
obj.data.images.push(child);
});
We would have the same result, but it might be less error prone. Here is a plunker.

You can loop all inputs with each() loop, create array from name attributes using split() and then use reduce to add to object
var result = {}
$('input').each(function() {
var name = $(this).attr('name');
var val = $(this).val();
var ar = name.split(/\[(.*?)\]/gi).filter(e => e != '');
ar.reduce(function(a, b, i) {
return (i != (ar.length - 1)) ? a[b] || (a[b] = {}) : a[b] = val;
}, result)
})
console.log(result)
.as-console-wrapper { max-height: 100% !important; top: 0; }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<ul id="gallery-images" class="ui-sortable">
<li class="col-xs-12 col-sm-6 col-md-4 col-lg-3 gallery-image ui-sortable-handle">
<div>
<img src="http://localhost:8000/img/example.jpg">
<input type="hidden" name="data[images][0][src]" value="img/example.jpg">
<div class="form-group">
<label for="title-0">Title:</label>
<input type="text" name="data[images][0][title]" class="form-control" id="title-0" value="Default Example Image 1" placeholder="Title">
</div>
<div class="form-group">
<label for="description-0">Description:</label>
<input type="text" name="data[images][0][description]" class="form-control" id="description-0" value="A default example image." placeholder="Description">
</div>
<div class="form-group">
<label for="alt-0">Alt tag (SEO):</label>
<input type="text" name="data[images][0][alt]" class="form-control" id="alt-0" value="fluid gallery example image" placeholder="Alt tag">
</div>
<div class="form-group">
<label for="order-0">Order:</label>
<input type="number" name="data[images][0][order]" class="form-control image-order" id="order-0" value="0">
</div>
<button type="button" class="btn btn-danger remove-gallery-image-btn">× Delete</button>
</div>
</li>
<li class="col-xs-12 col-sm-6 col-md-4 col-lg-3 gallery-image ui-sortable-handle">
<div>
<img src="http://localhost:8000/img/example.jpg">
<input type="hidden" name="data[images][1][src]" value="img/example.jpg">
<div class="form-group">
<label for="title-1">Title:</label>
<input type="text" name="data[images][1][title]" class="form-control" id="title-1" value="Default Example Image 2" placeholder="Title">
</div>
<div class="form-group">
<label for="description-1">Description:</label>
<input type="text" name="data[images][1][description]" class="form-control" id="description-1" value="A default example image." placeholder="Description">
</div>
<div class="form-group">
<label for="alt-1">Alt tag (SEO):</label>
<input type="text" name="data[images][1][alt]" class="form-control" id="alt-1" value="fluid gallery example image" placeholder="Alt tag">
</div>
<div class="form-group">
<label for="order-1">Order:</label>
<input type="number" name="data[images][1][order]" class="form-control image-order" id="order-1" value="1">
</div>
<button type="button" class="btn btn-danger remove-gallery-image-btn">× Delete</button>
</div>
</li>
<li class="col-xs-12 col-sm-6 col-md-4 col-lg-3 gallery-image ui-sortable-handle">
<div>
<img src="http://localhost:8000/uploads/galleries\21\4-tux-30.jpg">
<input type="hidden" name="data[images][2][src]" value="uploads/galleries\21\4-tux-30.jpg">
<div class="form-group">
<label for="title-2">Title:</label>
<input type="text" name="data[images][2][title]" class="form-control" id="title-2" value="" placeholder="Title">
</div>
<div class="form-group">
<label for="description-2">Description:</label>
<input type="text" name="data[images][2][description]" class="form-control" id="description-2" value="" placeholder="Description">
</div>
<div class="form-group">
<label for="alt-2">Alt tag (SEO):</label>
<input type="text" name="data[images][2][alt]" class="form-control" id="alt-2" value="" placeholder="Alt tag">
</div>
<div class="form-group">
<label for="order-2">Order:</label>
<input type="number" name="data[images][2][order]" class="form-control image-order" id="order-2" value="2">
</div>
<button type="button" class="btn btn-danger remove-gallery-image-btn">× Delete</button>
</div>
</li>
<li class="col-xs-12 col-sm-6 col-md-4 col-lg-3 gallery-image ui-sortable-handle">
<div>
<img src="http://localhost:8000/uploads/galleries\21\all-free-backgrounds-simple-style-darkblue-18.jpg">
<input type="hidden" name="data[images][3][src]" value="uploads/galleries\21\all-free-backgrounds-simple-style-darkblue-18.jpg">
<div class="form-group">
<label for="title-3">Title:</label>
<input type="text" name="data[images][3][title]" class="form-control" id="title-3" value="" placeholder="Title">
</div>
<div class="form-group">
<label for="description-3">Description:</label>
<input type="text" name="data[images][3][description]" class="form-control" id="description-3" value="" placeholder="Description">
</div>
<div class="form-group">
<label for="alt-3">Alt tag (SEO):</label>
<input type="text" name="data[images][3][alt]" class="form-control" id="alt-3" value="" placeholder="Alt tag">
</div>
<div class="form-group">
<label for="order-3">Order:</label>
<input type="number" name="data[images][3][order]" class="form-control image-order" id="order-3" value="3">
</div>
<button type="button" class="btn btn-danger remove-gallery-image-btn">× Delete</button>
</div>
</li>
</ul>

Related

Dynamically Calculating field value with js and php

So ive been trying to calculate automatically exchange rates with a rate i get from php and send it to a js script. Unfortunates the first field is calculated correctly but the second stops at a limit. ive tried this approach
<fieldset>
<div class="col-12" style="margin-left: -1rem !important;">
<h6 class="py-50" for="paypal">Choose What You Sell</h6>
</div>
<div class="row mb-75">
<div class="col-12 d-flex">
<div class="cursor-pointer d-flex align-items-center">
<label class="btn btn-outline-primary">
<img src="../app-assets/images/pages/btc.png" alt="BTC Logo">
<input type="radio" name="option" onchange="hideB(this)" id="btc" value="BTC" checked>
</label>
</div>
<div class="cursor-pointer pl-1 d-flex align-items-center">
<label class="btn btn-outline-primary">
<img src="../app-assets/images/pages/eth.png" height="30" alt="ETH Logo">
<input type="radio" name="option" onchange="hideA(this)" id="eth" value="ETH">
</label>
</div>
</div>
<hr>
</div>
<div class="row" id="A">
<div class="col-sm-4">
<div class="form-group">
<label for="value_n">Enter Your amount in USD </label>
<input type="text" id="value_btc" name="value_btc" class="form-control required" onkeyup="mult(this.value);" data-validation-regex-regex="([^a-z]*[A-Z]*)*" data-validation-containsnumber-regex="([^0-9]*[0-9]+)+" min="50" max="100000" data-validation-containsnumber-message="Min. $50 Max. $100,000" required placeholder="Enter Number of Your Value">
</div>
</div>
<div class="col-sm-4">
<div class="form-group">
<label for="lastName12">Amount in BTC</label>
<input type="text" class="form-control" id="btc_rate" name="btc_rate" readonly="readonly" placeholder="Amount in BTC" >
</div>
</div>
<div class="col-sm-4">
<div class="form-group">
<label for="lastName12">Amount You will Receive (BTC - ₦ NAIRA)</label>
<input type="text" class="form-control" id="receive_btc" name="receive_btc" readonly="readonly" placeholder="Amount in Naira" >
</div>
</div>
</div>
<div class="row" id="B" style="display:none">
<div class="col-sm-4">
<div class="form-group">
<label for="firstName13">Enter Your amount in USD </label>
<input type="text" id="value_eth" name="value_eth" class="form-control required" onkeyup="mult2(this.value);" data-validation-regex-regex="([^a-z]*[A-Z]*)*" data-validation-containsnumber-regex="([^0-9]*[0-9]+)+" min="50" max="100000" data-validation-containsnumber-message="Min. $50 Max. $100,000" required placeholder="Enter Number of Your Value">
</div>
</div>
<div class="col-sm-4">
<div class="form-group">
<label for="lastName12">Amount in ETH</label>
<input type="text" class="form-control" id="eth_rate" name="eth_rate" name="eth_rate" readonly="readonly" placeholder="Amount in BTC" >
</div>
</div>
<div class="col-sm-4">
<div class="form-group">
<label for="lastName12">Amount You will Receive (ETH - ₦ NAIRA)</label>
<input type="text" class="form-control" id="receive_eth" name="receive_eth" readonly="readonly" placeholder="Amount in BTC" >
</div>
</div>
</div>
im using the js below to calculate the field value for btc and how much the client will recieve:
<script>
function mult(value_btc) {
var btc_rate = "<?php echo $btc_rate; ?>";
<!-- END: Theme JS-->
var x, y ;
x = value_btc / btc_rate ;
y = btc_rate * 4 ;
document.getElementById('btc_rate').value = x;
document.getElementById('receive_btc').value = y;
}
</script>
<script>
function mult2(value_eth) {
var eth_rate = "<?php echo $eth_rate; ?>";
var x, y ;
x = value_eth / eth_rate ;
y = eth_rate * 4 ;
document.getElementById('eth_rate').value = x;
document.getElementById('receive_eth').value = y;
}
</script>
the x values work correctly but the y value stops at a limit.
will really appreciate if someone can help out. thanks in advance

Disable textbox inside an AngularJS Dynamic form

I need to disable the textbox inside my angularJS dynamic form after I clicked the button. my code seems to be working fine if I am going to disable textbox outside the dynamic form but when I get the ID of the textbox inside the dynamic form it is not working. What could be the problem.
$scope.copyText = function () {
document.getElementById('copyText').disabled=true;
document.getElementById('bName').disabled=true;
document.getElementById('pName').disabled=true;
// $('#bName').attr('disabled', true);
//alert('#bName');
$scope.LanguageFormData.language = [
{ bName: document.getElementById('brandName').value, pName: document.getElementById('prodName').value, pNameSub: document.getElementById('prodNameSub').value, lFeature: document.getElementById('pfeatureNew').value, lIngredient: document.getElementById('pingredientNew').value, lInstruction: document.getElementById('pinstructionNew').value, languageCat: null }
];
My View looks like this
<div class="col-md-12" class="pull-right" >
<button class="btn btn-primary pull-right" type="button" ng-click="copyText()" id="copyText" value="">COPY</button>
</div>
</div>
<div id="web" ng-repeat="languageItem in LanguageFormData.language">
<div class="row col-xs-12">
<div class="col-xs-6">
<br/><br/>
<div class="form-group">
<label class="col-md-6 control-label">Brand Name: </label>
<div class="col-md-6">
<input type="text" class="form-control" ng-required="true" name="bName" id="bName" class="form-control" ng-model="languageItem.bName" required/>
</div>
</div><br/><br/><br/>
<div class="form-group">
<label class="col-md-6 control-label">Product Name: </label>
<div class="col-md-6">
<input type="text" class="form-control" name="pName" ng-required="true" id="pName" ng-model="languageItem.pName" required/>
</div>
</div><br/><br/><br/>
Why not use ng-disabled. You need to change $scope.disableThis=false; back to false to re-enable the text somewhere else inside the controller code.
$scope.copyText = function () {
$scope.disableThis=true;
$scope.LanguageFormData.language = [
{ bName: document.getElementById('brandName').value, pName: document.getElementById('prodName').value, pNameSub: document.getElementById('prodNameSub').value, lFeature: document.getElementById('pfeatureNew').value, lIngredient: document.getElementById('pingredientNew').value, lInstruction: document.getElementById('pinstructionNew').value, languageCat: null }
];
Suggestions:
I have some doubts on the above code, you can just use the $scope.LanguageFormData.language as is, since you are using ng-model in the input fields, the data of the variable is updated dynamically, you can check this by {{LanguageFormData.language}} printing the output in the HTML
HTML:
<div class="col-md-12" class="pull-right" >
<button class="btn btn-primary pull-right" type="button" ng-click="copyText()" id="copyText" ng-disabled="disableThis" value="">COPY</button>
</div>
</div>
<div id="web" ng-repeat="languageItem in LanguageFormData.language">
<div class="row col-xs-12">
<div class="col-xs-6">
<br/><br/>
<div class="form-group">
<label class="col-md-6 control-label">Brand Name: </label>
<div class="col-md-6">
<input type="text" class="form-control" ng-required="true" name="bName" id="bName" ng-disabled="disableThis" class="form-control" ng-model="languageItem.bName" required/>
</div>
</div><br/><br/><br/>
<div class="form-group">
<label class="col-md-6 control-label">Product Name: </label>
<div class="col-md-6">
<input type="text" class="form-control" name="pName" ng-required="true" id="pName" ng-model="languageItem.pName" ng-disabled="disableThis" required/>
</div>
</div><br/><br/><br/>
Suggestions:
It would be good if you restrict the ID for one particular element alone, its a good practice to follow in general!

Get values from Dynamically Input Fields and Store to Database with PHP

I have form to create an itinerary. I have the add new button to create new fields for each day. My form looks like that:
Js
$(document).ready(function() {
bookIndex = 0;
$('#bookForm')
// Add button click handler
.on('click', '.addButton', function() {
bookIndex++;
var $template = $('#bookTemplate'),
$clone = $template
.clone()
.removeClass('hide')
.removeAttr('id')
.attr('data-book-index', bookIndex)
.insertBefore($template);
// Update the name attributes
$clone
.find('[name="day"]').attr('name', 'day[' + bookIndex + ']').end()
.find('[name="departs_on"]').attr('name', 'departs_on[' + bookIndex + ']').end()
.find('[name="arrives_on"]').attr('name', 'arrives[' + bookIndex + ']').end()
.find('[name="port_code"]').attr('name', 'port_code[' + bookIndex + ']').end()
.find('[name="port_name"]').attr('name', 'port_name[' + bookIndex + ']').end()
.find('[name="location"]').attr('name', 'location[' + bookIndex + ']').end()
.find('[name="latitude"]').attr('name', 'latitude[' + bookIndex + ']').end()
.find('[name="longitude"]').attr('name', 'longitude[' + bookIndex + ']').end();
// Add new fields
// Note that we also pass the validator rules for new field as the third parameter
})
// Remove button click handler
.on('click', '.removeButton', function() {
var $row = $(this).parents('.form-group'),
index = $row.attr('data-book-index');
// Remove fields
$('#bookForm')
// Remove element containing the fields
$row.remove();
});
});
And my HTML:
<form id="bookForm" method="post" class="form-horizontal">
<div class="form-group">
<div class="col-xs-4 col-lg-1">
<label class="col-xs-1 control-label">Day</label>
<input type="text" class="form-control" name="day[]" placeholder="day" />
</div>
<div class="col-xs-4 col-lg-2">
<label class="control-label">Departs</label>
<input type="date" class="form-control" name="departs_on[]" placeholder="departs_on" />
</div>
<div class="col-xs-2 col-lg-2">
<label class="control-label">Arrives On</label>
<input type="date" class="form-control" name="arrives_on[]" placeholder="arrives_on" />
</div>
<div class="col-xs-2 col-lg-1">
<label class="control-label">Port Code</label>
<input type="text" class="form-control" name="port_code[]" placeholder="port_code" />
</div>
<div class="col-xs-2 col-lg-1">
<label class="control-label">Port Name</label>
<input type="text" class="form-control" name="port_name[]" placeholder="port_name" />
</div>
<div class="col-xs-2 col-lg-2">
<label class="control-label">Location</label>
<input type="text" class="form-control" name="location[]" placeholder="location" />
</div>
<div class="col-xs-2 col-lg-1">
<label class="control-label">Latitude</label>
<input type="text" class="form-control" name="latitude[]" placeholder="latitude" />
</div>
<div class="col-xs-2 col-lg-1">
<label class="control-label">Longitude</label>
<input type="text" class="form-control" name="longitude[]" placeholder="longitude" />
</div>
</div>
</form>
I have this hidden form as well for the add new fields
<div class="form-group hide" id="bookTemplate">
<div class="col-xs-4 col-lg-1">
<label class="col-xs-1 control-label">Day</label>
<input type="text" class="form-control" name="day" placeholder="day" />
</div>
<div class="col-xs-4 col-lg-2">
<label class="control-label">Departs</label>
<input type="date" class="form-control" name="departs_on" placeholder="departs_on" />
</div>
<div class="col-xs-2 col-lg-2">
<label class="control-label">Arrives On</label>
<input type="date" class="form-control" name="arrives_on" placeholder="arrives_on" />
</div>
<div class="col-xs-2 col-lg-1">
<label class="control-label">Port Code</label>
<input type="text" class="form-control" name="port_code" placeholder="port_code" />
</div>
<div class="col-xs-2 col-lg-1">
<label class="control-label">Port Name</label>
<input type="text" class="form-control" name="port_name" placeholder="port_name" />
</div>
<div class="col-xs-2 col-lg-2">
<label class="control-label">Location</label>
<input type="text" class="form-control" name="location" placeholder="location" />
</div>
<div class="col-xs-2 col-lg-1">
<label class="control-label">Latitude</label>
<input type="text" class="form-control" name="latitude" placeholder="latitude" />
</div>
<div class="col-xs-2 col-lg-1">
<label class="control-label">Longitude</label>
<input type="text" class="form-control" name="longitude" placeholder="longitude" />
</div>
<div class="col-xs-1 col-lg-1">
<button type="button" class="btn btn-default removeButton"><i class="fa fa-minus"></i></button>
</div>
It working.
I was wondering is there any option to get this as an array and then insert then to database or should I use a loop and run e.g 6 times my db query?
I got lost a little bit here. I tried to create an array but nothing worked.
How to get the values of the inputs for each day and insert into the database with PHP?
In form name attribute build a array like below
name="data[0][day]"
In jquery
name="data[1][day]" // 1 should be replaced with incrementer variable
so you will get each date separately . so you can loop the array and insert the data into mysql .
Example array : This is you will get on server side
array( [0]=>array(
[day]=>value,
[departs_on]=>value,
.......
),
[1]=>array(
[day]=>value,
[departs_on]=>value,
.......
),
.........
)

Issue with jQuery validate not working against element

I am having an issue using jQuery validate against a form in a current project.
I am sure it is a typo I am missing or something small, but can't sem to figure out why it is occurring.
The error I am getting in the console debugger is: Object doesn't support property or method 'validate'
The bundle configuration file:
bundles.Add(new ScriptBundle("~/bundles/jquery").Include(
"~/Scripts/jquery-{version}.js"));
bundles.Add(new ScriptBundle("~/bundles/jqueryval").Include(
"~/Scripts/jquery.validate*"));
bundles.Add(new ScriptBundle("~/bundles/custom").Include(
"~/Scripts/ContactForm.js"));
The code snippets are below:
<form action="#Url.Action("UpdateContactInformation", "ContactController")" method="post" role="form" class="form-horizontal" id="contactForm">
<input type='hidden' name='csrfmiddlewaretoken' value='brGfMU16YyyG2QEcpLqhb3Zh8AvkYkJt' />
<!-- First Name Form Field-->
<div class="form-group required">
<label class="col-md-2 control-label">First Name</label>
<div class="col-md-4">
<input class="form-control" id="id_firstName" maxlength="75" name="txtFirstName" placeholder="First Name" required="required" title="" type="text" />
</div>
</div>
<!-- Last Name Form Field-->
<div class="form-group required">
<label class="col-md-2 control-label">Last Name</label>
<div class="col-md-4">
<input class="form-control" id="id_lastName" maxlength="75" name="txtlastName" placeholder="Last Name" required="required" title="" type="text" />
</div>
</div>
<!-- Title Form Field-->
<div class="form-group required">
<label class="col-md-2 control-label">Title</label>
<div class="col-md-4">
<input class="form-control" id="id_title" maxlength="75" name="txtTitle" placeholder="Title" required="required" title="" type="text" />
</div>
</div>
<!-- Address Form Field-->
<div class="form-group required">
<label class="col-md-2 control-label">Address</label>
<div class="col-md-4">
<input class="form-control" id="id_address" maxlength="75" name="txtAddress" placeholder="Address" required="required" title="" type="text" />
</div>
</div>
<!-- City Form Field-->
<div class="form-group required">
<label class="col-md-2 control-label">City</label>
<div class="col-md-4">
<input class="form-control" id="id_city" maxlength="75" name="txtCity" placeholder="City" required="required" title="" type="text" />
</div>
</div>
<!-- State Form Field-->
<div class="form-group required">
<label class="col-md-2 control-label">State</label>
<div class="col-md-4">
<div class="dropdown">
<button class="btn btn-default dropdown-toggle" type="button" id="dropdownMenuStates" data-toggle="dropdown" aria-haspopup="true" aria-expanded="true">
Select State
<span class="caret"></span>
</button>
<ul class="dropdown-menu" id="statesDropDownMenu" aria-labelledby="dropdownMenuStates">
</ul>
</div>
</div>
</div>
<!-- Zip Form Field-->
<div class="form-group required">
<label class="col-md-2 control-label">ZipCode</label>
<div class="col-md-4">
<input class="form-control" id="id_zipCode" maxlength="75" name="txtZipCode" placeholder="ZipCode" required="required" title="" type="number" />
</div>
</div>
<!-- Email Primary Form Field-->
<div class="form-group required">
<label class="col-md-2 control-label">Email Primary</label>
<div class="col-md-4">
<input class="form-control customEmail" id="id_emailPrimary" maxlength="75" name="txtEmailPrimay" placeholder="Email Primary" required="required" />
</div>
</div>
<!-- Email Secondary (optional) Form Field-->
<div class="form-group">
<label class="col-md-2 control-label">Email (Optional)</label>
<div class="col-md-4">
<input class="form-control" id="id_emailSecond" maxlength="75" name="txtEmailSecond" placeholder="Email (Optional)" title="Email (Optional)" type="email" />
</div>
</div>
<!-- Email Third (optional) Form Field-->
<div class="form-group">
<label class="col-md-2 control-label">Email (Optional)</label>
<div class="col-md-4">
<input class="form-control" id="id_emailThird" maxlength="75" name="txtEmailThird" placeholder="Email (Optional)" title="Email (Optional)" type="email" />
</div>
</div>
<div class="form-group">
<div class="col-sm-offset-2 col-sm-10">
<button type="submit" class="btn btn-primary">
<span class="glyphicon glyphicon-user"></span> Submit Contact Info
</button>
</div>
</div>
#Scripts.Render("~/bundles/jquery")
#Scripts.Render("~/bundles/jqueryval");
#Scripts.Render("~/bundles/custom"); //contains the file I am trying to add $.validate.AddMethod() to
Here is the code for Contact.js
$.validator.addMethod(
"customEmail",
function (value, element) {
var re = new RegExp("/^#{0,2}\w+([-+.']\w+)*#\w+([-.]\w+)*\.\w+([-.]\w+)*#{0,2}​‌‌​​$/");
return this.optional(element) || re.test(value);
},
"Please enter a valid email address."
);
$(document).ready(function () {
console.log("Were here.........");
// populateStatesDropDown();
$('#contactForm').validate({ // initialize the plugin
rules: {
txtZipCode: {
required: true,
numeric: true
},
txtEmailPrimay: {
required: true,
customEmail:true
},
txtEmailSecond:{
required:false,
customEmail:true,
},
txtEmailThird: {
required: false,
customEmail:true
}
}
});
populateStatesList();
});
function populateStatesList() {
var url = "Contact/GetStates"; // Don't hard code your url's!
//$("#province_dll").change(function () {
var $statesDropDownMenu = $("#statesDropDownMenu"); // Use $(this) so you don't traverse the DOM again
var listItems = '';
$.getJSON(url, function (response) {
$statesDropDownMenu.empty(); // remove any existing options
console.log(response);
$.each(response, function (index, item) {
console.log("Now - " + item);
listItems += "<li>" + item + "</li>";
});
$statesDropDownMenu.html(listItems);
});
//});
}
You have an extra comma.
txtEmailSecond:{
required:false,
customEmail:true, // Here
},

JavaScript- how to create dynamically multiple divs with inputs field

I have to create 3 input text boxes for getting user input about names and email addresses.
I have to create it dynamically, i.e. as the user clicks on the email input field a new line of all the three element supposed to be created.
This is the code for one line with the 3 inputs:
<div class='row' id="inputcontainer">
<div class="form-group clearfix" >
<div class="col-md-2 col-md-offset-2">
<div class="form-text-field first-name">
<label>First name</label>
<input type="text" id="firstName10" class="signup-input" name="" placeholder="">
</div>
</div>
<div class="col-md-2">
<div class="form-text-field last-name">
<label>Last name</label>
<input type="text" id="lastName0" class="signup-input" name="" placeholder="optional">
</div>
</div>
<div class="col-md-4">
<div class="form-text-field email">
<div>
<label>Email</label>
<input type="text" data-index="0" id="inputMail0" class="signup-input text-value " name="email[0]" placeholder="e.g. example#url.com"/>
<span class="common-sprite disNone sign-up-cross first"></span>
</div>
</div>
</div>
</div>
</div>
How to create it dynamically ?
I'm using the following code for cloning and it's clone it several times instead 1
maxIndex = 0;
$('form').on('input','.email',function(){
$(this).parent().find('.common-sprite').removeClass('disNone');
var lastmail = $(this); if(($(this).val().length > 0)&&(lastmail.data('index') == maxIndex)) {
var count = $('.row.inputcontainer').length;
console.log(count);
maxIndex++;
var clone = $('#template').clone(true).attr('id', '');
clone.find('.firstName[id=firstName'+(maxIndex-1)+']').attr('id', 'firstName' + maxIndex).attr('name', 'first[' + maxIndex +']').addClass('signup-input firstName').val('');
clone.find('.lastName[id=lastName'+(maxIndex-1)+']').attr('id', 'lastName' + maxIndex).attr('name', 'last[' + maxIndex +']').addClass('signup-input lastName').val('');
clone.find('.email[id=inputMail'+(maxIndex-1)+']').attr('id', 'inputMail' + maxIndex).attr('name', 'email[' + maxIndex +']').data('index', maxIndex).addClass('signup-input text-value email').val('');
$('.inputcontainer').append(clone);
}
something like this? i used .blur() to trigger the dynamic adding so that if you type something in the email input and you click outside of it, then the next 3 lines of information will show up. i also added some classes to help jquery find elements faster and more reliably. i used clone() to recreate the same structure of the 3 lines every time.
$(document).ready(function() {
$('.email').on('blur', function() {
if($(this).val().length > 0) {
var count = $('.row').length;
console.log(count);
var clone = $('#template').clone(true).attr('id', '');
clone.find('.firstName').attr('id', 'firstName' + count).val('');
clone.find('.lastName').attr('id', 'lastName' + count).val('');
clone.find('.email').attr('id', 'inputMail' + count).val('');
$('body').append(clone);
}
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class='row inputcontainer' id="template">
<div class="form-group clearfix" >
<div class="col-md-2 col-md-offset-2">
<div class="form-text-field first-name">
<label>First name</label>
<input type="text" id="firstName0" class="signup-input firstName" name="" placeholder=""/>
</div>
</div>
<div class="col-md-2">
<div class="form-text-field last-name">
<label>Last name</label>
<input type="text" id="lastName0" class="signup-input lastName" name="" placeholder="optional"/>
</div>
</div>
<div class="col-md-4">
<div class="form-text-field email">
<div>
<label>Email</label>
<input type="text" data-index="0" id="inputMail0" class="signup-input text-value email" name="email[0]" placeholder="e.g. example#url.com"/>
<span class="common-sprite disNone sign-up-cross first"></span>
</div>
</div>
</div>
</div>
</div>
hope this helps!
Is this something similar to what you would like?
$(document).on("blur",".add",function()
{
$("#inputcontainer").append("<br />");
$("#inputcontainer").append("First Name <input type='text' class='signup-input' name='' placeholder='' /><br />");
$("#inputcontainer").append("last Name <input type='text' class='signup-input' name='' placeholder='optional' /><br />");
$("#inputcontainer").append("Email Address <input type='text' data-index='0' class='signup-input text-value add' name='email[0]' placeholder='e.g. example#url.com' /><br />");
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class='row' id="inputcontainer">
<div class="form-group clearfix t" >
<div class="col-md-2 col-md-offset-2">
<div class="form-text-field first-name">
<label>First name</label>
<input type="text" id="firstName10" class="signup-input" name="" placeholder="">
</div>
</div>
<div class="col-md-2">
<div class="form-text-field last-name">
<label>Last name</label>
<input type="text" id="lastName0" class="signup-input" name="" placeholder="optional">
</div>
</div>
<div class="col-md-4">
<div class="form-text-field email">
<div>
<label>Email</label>
<input type="text" data-index="0" id="inputMail0" class="signup-input text-value add" name="email[0]" placeholder="e.g. example#url.com"/>
<span class="common-sprite disNone sign-up-cross first"></span>
</div>
</div>
</div>
</div>
</div>
Type into the email textbox then leave to create the new textboxes.

Categories

Resources