How to use checkbox with nested ng-repeat in angularjs - javascript

Hello everyone i have faced some problem in case of nested checkbox uses. In my problem i m stuck on to how to use IncludeAll on click checkbox. If checkbox value is true then it's give me a value of that. if IncludeAll checkbox is true then all checkbox will be selected and show the value of all in Array. and if one of the checkbox is false then IncludeAll checkbox false..But in Case the other checkbox will be selected.
This is my Fiddle Link : http://jsfiddle.net/0x4396pu/1/
Here is my Html Code:
<form action="#" ng-controller='MyCtrl'>
<div class="control-group" ng-repeat="story in stories">
<br>
<input type="checkbox" ng-model="story.selectionAll">
<label class="control-label">IncludeAll {{story}}</label>
<div class="controls">
<label class="checkbox inline" ng-repeat="browser in browsers">
<input type="checkbox" value="{{browser}}"
ng-model="selection[story].browsers[browser]"
ng-checked="story.selectionAll">
{{browser}}
</label>
</div>
</div>
</div>
<pre>{{selection | json }}</pre>
</form>
Here is my Controller file :
function MyCtrl($scope) {
$scope.stories = ['1', '2', '3'];
$scope.browsers = ['IE', 'Chrome', 'Firefox','Safari','Opera'];
$scope.selection = {};
angular.forEach($scope.stories, function(story) {
$scope.selection[story] = {
browsers: {},
};
});
}
Thanks in Advance.

I am answer my own Question. But anyway Here is Answer how to select Checkbox in Nested ng-repeat.i think It's Help you Thanks.
Http Plunkr LInk http://plnkr.co/edit/OQxi53xtVKOgToPhzDUZ?p=preview
Here is Html Code:
<!DOCTYPE html>
<html ng-app="myApp">
<head>
<link rel="stylesheet" href="style.css">
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.3.4
/angular.min.js">
</script>
<script src="script.js"></script>
</head>
<body>
<form action="#" ng-controller='detailContrller'>
<div class="control-group" ng-repeat="story in stories"> <br>
<h4> Enter Data </h4>
Name : <input type="text" data-ng-model="selection[story].Name1"
placeholder="Enter Name"> <br>
Address : <input type="text" data-ng-model="selection[story].Name2"
placeholder="Enter Address"> <br>
City : <input type="text" data-ng-model="selection[story].Name3"
placeholder="Enter City"> <br>
Phone : <input type="text" data-ng-model="selection[story].Name4"
placeholder="Enter Phone "> <br>
State : <input type="text" data-ng-model="selection[story].Name5"
placeholder="Enter State"> <br>
<input type="checkbox" ng-model="selection[story].all"
ng-change="updateAll(story)">
<label class="control-label">IncludeAll {{story}}</label>
<div class="controls">
<label class="checkbox inline" ng-repeat="browser in browsers">
<input type="checkbox" value="{{browser}}"
ng-model="selection[story].browsers[browser]"
ng-change="checkChange(browser)"
> {{browser}}
</label>
</div>
</div>
<button type="button" data-ng-click="save()">Save</button>
<pre>{{selection | json}}</pre>
</form>
</body>
</html>
Here is my Controller
var app = angular.module("myApp",[]);
app.controller('detailContrller', function($scope){
$scope.stories = [];
$scope.browsers = ['IE', 'Chrome', 'Firefox','Safari','Opera'];
$scope.selection = {};
$scope.details = {};
var checked;
$scope.updateAll = function (story) {
checked = $scope.selection[story].all;
$scope.browsers.forEach(function (browser) {
$scope.selection[story].browsers[browser] = checked;
});
};
for(var i = 0; i< 3; i++) {
$scope.stories.push(i+1);
}
$scope.checkChange = function (browser) {
for(var i =0; i< $scope.stories.length; i++){
if(!$scope.stories[i].selected){
checked = false
return false;
}
}
}
angular.forEach($scope.stories, function(storgy) {
$scope.selection[storgy] = {
browsers: {}
};
});
$scope.save = function () {
console.log($scope.selection);
}
})

Your "include all" checkbox is trying to set .selectionAll property on a String (story in stories gives you a String).
You can't use ng-checked to somehow "work together" with ng-model. If you want your "include all" checkbox to select all subordinate checkboxes and vice versa, you'll need to watch the changes and provide some logic connecting the two things in your controller.
For example, if you want change of the "include all" checkbox value to influence other checkboxes, you'd have to do something like
<input type="checkbox" ng-model="selection[story].all" ng-change="updateAll(story)">
and in your controller
$scope.updateAll = function (story) {
var checked = $scope.selection[story].all;
$scope.browsers.forEach(function (browser) {
$scope.selection[story].browsers[browser] = checked;
});
};
and handle changes of the individual checkboxes in a similar fashion.

Related

Javascript document.getElementById function not returning checkbox value to HTML form

I have been searching for an answer everywhere but just can not find what I need.
I have a webpage that has an HTML table on the left column and an HTML form on the right column. When I click on a row in the table on the left I want it to display the values in the form on the right.
I have this working perfectly for the text fields on the form, but not for the two checkboxes. My javascript will return either true or false or checked and unchecked to the document.getElementById within the script itself by using alert(); but I have no idea what it needs to allow the checkboxes to display these values. I thought the document.getElementById would return the values but it seems it does not.
I have tried all kinds of conveluted ways to get this to work but can not seem to get the correct code needed.
I am new to all this so there is most likely something really simple I am missing.
This is the HTML form code:
<div class="column right">
<table>
<tr></tr>
<tr>
<div class="lockinv">
<form autocomplete="off" name="lockform" class="keyassign" action="includes/lockinventory.inc.php"
method="post">
<label id="inventory" for="locknum">Lock Number</label>
<input id="invlocknum" type="text" name="locknum" value="" required>
<label id="inventory" for="locktype">Lock Type</label>
<input id="invlocktype" type="text" name="locktype" value="" required>
<label id="inventory" for="keycode">Key Code</label>
<input id="invkeycode" type="text" name="keycode" value="" required>
<label id="inventory" for="lockengraved">Lock Engraved</label>
<input id="invlockengraved" type="hidden" name="lockengraved" value="0">
<input id="invlockengraved" type="checkbox" name="lockengraved" value="1">
<label id="inventory" for="lockmastered">Lock Mastered</label>
<input id="invlockmastered" type="hidden" name="lockmastered" value="0">
<input id="invlockmastered" type="checkbox" name="lockmastered" value="1">
<label id="inventory" for="locknote">Lock Note</label>
<textarea id="inventorynote" name="locknote" rows="5" cols="60"></textarea>
<div class="wheel">
<?php
if (isset($_GET["error"])) {
if($_GET["error"] == "lockexists") {
echo "<p>Lock Already In Inventory!</p>";
}
else if ($_GET["error"] == "lockexistsfailed") {
echo "<p>Lock Already In Inventory!</p>";
}
}
?>
</div>
<input id="bt6" type="submit" name="submit" value="Save">
<button id="bt6" type="reset" name="button">Cancel</button>
</form>
</div>
</tr>
</table>
</div>
This is my JavaScript code:
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js" type="text/javascript"></script>
<script language="javascript"></script>
<script>
$(function () {
$('#lockTable td').click(function () {
var currentRow = $(this).closest("tr");
var locknum = currentRow.find("td:eq(0)").text();
var locktype = currentRow.find("td:eq(1)").text();
var keycode = currentRow.find("td:eq(2)").text();
var engraved = currentRow.find("td:eq(3)").find(":checkbox");
var mastered = currentRow.find("td:eq(4)").find(":checkbox");
var locknote = currentRow.find("td:eq(5)").text();
var lockengraved = engraved.prop("checked");
if (lockengraved === true) {
$grved = "checked";
} else {
$grved = "unchecked";
}
var lockmastered = mastered.prop("checked");
if (lockmastered === true) {
$msted = "checked";
} else {
$msted = "unchecked";
}
document.getElementById('invlocknum').value = locknum;
document.getElementById('invlocktype').value = locktype;
document.getElementById('invkeycode').value = keycode;
document.getElementById("invlockengraved").value = $grved;
document.getElementById('invlockmastered').value = $msted;
document.getElementById('inventorynote').value = locknote;
alert(document.getElementById("invlockengraved").value);
alert(document.getElementById("invlockmastered").value);
});
});
</script>
<p id="invlocknum"></p>
<p id="invlocktype"></p>
<p id="invkeycode"></p>
<p id="invlockengraved"></p>
<p id="invlockmastered"></p>
<p id="invlocknote"></p>
<p id="info"></p>
<p id="result"></p>
I found the answer to my issue. I had to modify my if statement in the Javascript to the following. Works the way I want it to. Thanks to all that helped.
var lockengraved = engraved.prop("checked");
if (lockengraved === true) {
document.getElementById("invlockengraved").checked = lockengraved;
}else if (lockengraved === false) {
document.getElementById("invlockengraved").checked = lockengraved;
}

Change a string in the middle of the sentence with JS

I'm trying to make a little application that allows me to select between some checkboxes with lang codes and then with a click in a button, open new tabs with the URL with the lang-code changed.
URL FORMAT: https://example.com/en-us/example.html
What i want to change is the en-us. I have several issues here:
I know how to search a string, but there is a way to replace it avoiding a LOT of if statements? Because the web could have en-US code or maybe ko-KR or es-ES and so on.
I want to open a new tab for each checkbox(checked) with the selected lang-code.
So, there is a simple way to do this?
HTML:
<!DOCTYPE HTML>
<html>
<head>
<link rel="stylesheet" type="text/css" href="css/style.css">
</head>
<body>
<div class="container">
<div class="info-container">
<p>URL:</p>
<input type="text" id="URL">
<input type="button" id="opentab-button" value="Go!">
</div>
<div class="langcode-container">
<input type="checkbox" name="lang-check" value="ko-kr"> KOR<br>
<input type="checkbox" value="lang-check" value="nl-NL"> NLD<br>
<input type="checkbox" value="lang-check"> PTB<br>
<input type="checkbox" value="lang-check"> PTG<br>
<input type="checkbox" value="lang-check"> CHT<br>
</div>
</div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script src="js/index.js"></script>
</body>
</html>
JavaScript:
document.getElementById("opentab-button").addEventListener("click", openTabs);
function openTabs() {
var str = document.getElementById("URL").value;
var checkQua = $(":checkbox:checked").length;
for (i = 1; i <= checkQua; i++) {
var res = str.replace("en-us", "ko-kr");
window.open(res,'_blank');
}
}
I know how to search a string, but there is a way to replace it avoiding a LOT of if statements? Because the web could have en-US code or maybe ko-KR or es-ES and so on.
Keep the replacement values in the checkboxes' value attributes, as you've already done with your first two <input>s. Then, instead of str.replace("en-us", "ko-kr"), do str.replace("en-us", checkbox.value).
document.getElementById("opentab-button").addEventListener("click", openTabs);
function openTabs() {
var str = document.getElementById("URL").value;
var checkQua = document.querySelectorAll('input[name=lang-check]:checked');
checkQua.forEach(function(checkbox) {
var res = str.replace('en-us', checkbox.value);
console.log('Opening', res);
window.open(res, '_blank');
});
}
<div class="info-container">
<p>URL:</p>
<input type="text" id="URL" value="https://example.com/en-us/example.html">
<input type="button" id="opentab-button" value="Go!">
</div>
<div class="langcode-container">
<input type="checkbox" name="lang-check" value="ko-KR"> KOR<br>
<input type="checkbox" name="lang-check" value="nl-NL"> NLD<br>
<input type="checkbox" name="lang-check" value="pt-BR"> PTB<br>
<input type="checkbox" name="lang-check" value="pt-PT"> PTG<br>
<input type="checkbox" name="lang-check" value="ch-CH"> CHT<br>
</div>
Note that the above doesn't actually open any windows because Stack Overflow has disabled popups in snippets. (Take a look at your console to see the permission errors.)
I think this can help you
$(function(){
$("#opentab-button").on("click", openTabs);
function openTabs() {
var str = document.getElementById("URL").value;
var data = getLocation(str);
// passing by each checkbox
$("[type='checkbox']:checked").each(function(){
var path = data.pathname.split('/');
// Replacing the second item (the language) for the value in the checkbox
path.splice(1,1,$(this).val());
// Replacing the old path of url by the new path
var newPath = data.full.replace(data.pathname,path.join('/'));
//window.open(newPath,'_blank');
alert(newPath);
});
}
function getLocation(url) {
var reURLInformation = new RegExp([
// protocol
'^(https?:)//',
// host (hostname and port)
'(([^:/?#]*)(?::([0-9]+))?)',
// pathname
'(/[^?#]*)',
// search
'(\\?[^#]*|)',
// hash
'(#.*|)$'
].join(''));
var match = url.match(reURLInformation);
return match && {
full: url,
protocol: match[1],
host: match[2],
hostname: match[3],
port: match[4],
pathname: match[5],
search: match[6],
hash: match[7]
}
}
});
<div class="container">
<div class="info-container">
<p>URL:</p>
<input type="text" id="URL">
<input type="button" id="opentab-button" value="Go!">
</div>
<div class="langcode-container">
<input type="checkbox" value="ko-kr"> KOR<br>
<input type="checkbox" value="nl-NL"> NLD<br>
<input type="checkbox" value="lang-check"> PTB<br>
<input type="checkbox" value="lang-check"> PTG<br>
<input type="checkbox" value="lang-check"> CHT<br>
</div>
</div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
var str = document.getElementById("URL").value
var res = str.replace(str.split("/")[3],"whateveryouwant")
window.open(res,'_blank');

Make checkboxes required AngularJS

I have a form where users have to answer questions through checkboxes. There are quite few checkboxes and I'm using AngularJS in the form to validate it. A basic validation is that all the required fields are filled.
Below is my example code:
<input type="checkbox" name="skills"> IT
<input type="checkbox" name="skills"> Design
<input type="checkbox" name="skills"> Photoshop
<input type="checkbox" name="skills"> Writing
Now I want the checkboxes to be required so from the "skills" checkboxes the user atleast checks 1 box.
I've tried putting the required tag but it didn't seem to work.
Im using AngularJS to validate my form like so
<button ng-disabled="myForm.$invalid">Submit</button>
Any idea how I can fix this? If you can working fiddle that would great.
If you want to validate using ng-disabled="myForm.$invalid"
var app = angular.module('myModule', []);
app.controller("myController", function ($scope) {
$scope.choices = [{"name":"IT"},{"name":"Design"},{"name":"Technology"}];
$scope.checkBoxArray = [];
$scope.validate = function (value) {
if ($scope.checkBoxArray.indexOf(value) == -1){
$scope.checkBoxArray.push(value);
}
else {
$scope.checkBoxArray.splice($scope.checkBoxArray.indexOf(value), 1);
}
}
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<html ng-app="myModule">
<body ng-controller="myController">
<ng-form name="myForm">
<span ng-repeat="choice in choices">
<input type="checkbox" name="skills" ng-required="checkBoxArray.length==0" ng-model="choice.checked" ng-change="validate(choice.name)">
{{choice.name}}
</span>
</ng-form>
<button ng-disabled="myForm.$invalid">Submit</button>
</body>
</html>
Try this working demo :
var myApp = angular.module('myApp',[]);
myApp.controller('MyCtrl',function($scope) {
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="myApp" ng-controller="MyCtrl">
<form name="checkBoxForm">
<input type="checkbox" name="skills" ng-model="IT">IT
<input type="checkbox" name="skills" ng-model="Design">Design
<input type="checkbox" name="skills" ng-model="Photoshop">Photoshop
<input type="checkbox" name="skills" ng-model="Writing">Writing
<button ng-disabled="!IT&&!Design&&!Photoshop&&!Writing">Submit</button>
</form>
</div>
You can use a array to do this:
var myApp = angular.module('myApp',[]);
myApp.controller('MyCtrl',function($scope) {
$scope.collection=[{
"Name": "IT"},
{
"Name": "Design"},
{
"Name": "Photoshop"},
{
"Name": "Writing"}];
$scope.disableButton = true;
$scope.doTheThings = function (item)
{
if (item.checked)
$scope.disableButton = true;
else
$scope.disableButton = false;
}
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="myApp" ng-controller="MyCtrl">
<ul>
<li ng-repeat="item in collection">
<input type="checkbox" name="skills" ng-model="item.checked" ng-click="doTheThings(item)"> {{item.Name}}
</li>
</ul>
<button ng-disabled="disableButton"> Submit </button>
</form>
</div>

How to fill div with values from form?

I have a html form with such structure:
...
<select name="Employee">
<option>a</option>
<option>b</option>
</select>
<input type="checkbox" name="email" value="Yes" unchecked>Include Email Contact
<input type="checkbox" name="phone" value="Yes" unchecked>Include Phone Contact
Job Title: <input type="Text" name="jobTitle" size="20"><br>
<input type="Button" value="Generate" onclick="show()" id="refresh">
...
And a div:
<div class="data">
<div class="ft_name"></div>
<div class="ft_pos"></div>
<div class="ft_tbl_meta">E-Mail:</div>
<div class="ft_tbl_data"></div>
<div class="ft_tbl_meta">Phone:</div>
<div class="ft_tbl_data"></div>
</div>
How can I show my values in div section by pressing the button without reloading the entire page?
I know Javascript a bit, but unfortunately, didn't find the answer yet.
Thank you in advance!
Here is one solution, using unobtrusive vanilla javascript.
The function showData() runs when the button is clicked.
Then, the function showData():
gets the Boolean value of each checkbox (either true if checked or false if unchecked)
rewrites the Boolean value as a string (a value of true becomes 'Yes' and a value of false becomes 'No')
rewrites the relevant data field, including the string.
function showData() {
var emailValue = document.querySelector('input[value="email"]').checked;
var phoneValue = document.querySelector('input[value="phone"]').checked;
var data = document.getElementsByClassName('data')[0];
var dataFields = data.getElementsByTagName('div');
if (emailValue === true) {emailValue = 'Yes';} else {emailValue = 'No';}
if (phoneValue === true) {phoneValue = 'Yes';} else {phoneValue = 'No';}
for (var i = 0; i < dataFields.length; i++) {
switch (i) {
case (0) : dataFields[i].textContent = 'E-Mail: ' + emailValue; break;
case (1) : dataFields[i].textContent = 'Phone: ' + phoneValue; break;
}
}
}
var button = document.querySelector('input[type="button"]');
button.addEventListener('click',showData,false);
form, .data, label, input[type="button"] {
display: block;
}
form, .data {
float: left;
width: 200px;
}
input[type="button"] {
margin-top: 24px;
}
<form>
<label><input type="checkbox" name="contact" value="email" unchecked>Include Email Contact</label>
<label><input type="checkbox" name="contact" value="phone" unchecked>Include Phone Contact</label>
<input type="Button" value="Generate">
</form>
<div class="data">
<div class="ft_tbl_meta">E-Mail:</div>
<div class="ft_tbl_meta">Phone:</div>
</div>
set some IDs for your divs you wish to take/assign values from/to and put this code
IncludeEmailCheckBox is for your "include Email" checkbox
EmailToDiv is for your div to get the email
EmailFromDiv is for your input for Email
IncludePhoneCheckBox is for your "include Phone" checkbox
PhoneToDiv is for your div to get the Phone
PhoneFromDiv is for your input for Phone
function show(){
if (document.getElementById("IncludeEmailCheckBox").checked){
document.getElementById("EmailToDiv").innerHTML = document.getElementById("EmailFromDiv").innerHTML ;}
if (document.getElementById("IncludePhoneCheckBox").checked){
document.getElementById("PhoneToDiv").innerHTML = document.getElementById("PhoneFromDiv").innerHTML ;}
return false;
}
Remember to change IDs as nessesary
Get elements of class by calling document.getElementsByClassName(class_name)
Example javascript code below
<HTML>
<HEAD>
<SCRIPT LANGUAGE="JavaScript">
function testResults (form) {
var x = document.getElementsByClassName("ft_name");
x[0].innerHTML = form.name.value;
x = document.getElementsByClassName("ft_tbl_meta");
x[0].innerHTML = form.email.value; // name email is one provided in form
// Do same for all other classes
}
</SCRIPT>
</HEAD>
<BODY>
<FORM NAME="myform" ACTION="" METHOD="GET">Enter something in the box: <BR>
<input type="checkbox" name="email" value="Yes" unchecked>Include
Email Contact
<input type="checkbox" name="phone" value="Yes" unchecked>Include Phone Contact
Job Title: <input type="Text" name="jobTitle" size="20"><br>
<input type="Button" value="Generate" onclick="show(this.form)" id="refresh">
<INPUT TYPE="button" NAME="button" Value="Click" onClick="testResults(this.form)">
</FORM>
</BODY>
</HTML>
here is your view (I updated) using Jquery:
<div class="data">
<div class="ft_name"></div>
<div class="ft_pos"></div>
<div class="ft_tbl_meta">E-Mail:<span id="email_here"></span></div>
<div class="ft_tbl_data"></div>
<div class="ft_tbl_meta">Phone:<span id="phone_here"></span></div>
<div class="ft_tbl_data"></div>
</div>
Now fetching and printing values:
var Employee = $( "select[name=Employee]" ).val();
$('.ft_name').html(Employee);
var email = $( "input[name=email]" ).val();
$('#email_here').html(email);
var phone = $( "input[name=phone]" ).val();
$('#phone_here').html(phone);
var jobTitle = $( "input[name=jobTitle]" ).val();
$('.ft_pos').html(jobTitle);

How to serialize checkbox value through searilizedarray()?

My question is how to serialize checkbox value and textbox value together in one array through searilizedarray()...
now i am getting something like this
[{"name":"text_input","value":"kalpit"},
{"name":"wpc_chkbox[]","value":"Option one"},
{"name":"wpc_chkbox[]","value":"Option two"},
{"name":"wpc_chkboxasdf[]","value":"Option one"},
{"name":"wpc_chkboxasdf[]","value":"Option two"},
{"name":"wpc_inline_chkbox[]","value":"1"},
{"name":"wpc_inline_chkbox[]","value":"2"},
{"name":"wpc_inline_chkbox[]","value":"3"},
{"name":"wpc_radios","value":"Option one"}]
but it should be like
[{"name":"text_input","value":"kalpit"},
{"name":"wpc_chkbox[]","value":"[Option one,Option Two]"},
{"name":"wpc_chkboxasdf[]","value":"[Option one,Option Two]"},
{"name":"wpc_inline_chkbox[]","value":"[1,2,3]"},
{"name":"wpc_radios","value":"Option one"}]
i am using var form = $('.wpc_contact').serializeArray(); to get form data
this is my html sample which I am generating dynamically using drag and drop future..
<form method="POST" name="1" class="form-horizontal wpc_contact" novalidate="novalidate">
<fieldset>
<div id="legend" class="">
<legend class="">Demo</legend>
<div id="alert-message" class="alert hidden" style="color: red;"></div>
</div>
<div class="control-group">
<label class="control-label">Checkboxes</label>
<div class="controls" name="wpc_chkbox" req="yes">
<input type="checkbox" value="Option one" id="wpc_chkbox_0" name="wpc_chkbox[]" req="yes"> Option one
<input type="checkbox" value="Option two" id="wpc_chkbox_1" name="wpc_chkbox[]" req="yes"> Option two
</div>
</div>
<div class="control-group">
<div class="controls" name="wpc_inline_chkbox" req="yes">
<input type="checkbox" value="1" name="wpc_inline_chkbox[]" id="wpc_inline_chkbox_0" req="yes"> 1
<input type="checkbox" value="2" name="wpc_inline_chkbox[]" id="wpc_inline_chkbox_1" req="yes"> 2
<input type="checkbox" value="3" name="wpc_inline_chkbox[]" id="wpc_inline_chkbox_2" req="yes"> 3
</div>
</div>
<div class="control-group">
<div class="controls">
<button class="btn btn-success">Button</button>
</div>
</div>
</fieldset>
</form>
Thanks in advance
Try this:
var cacheObject = {};//tmp cache for form elements name/values pairs
var serArr = $('.wpc_contact').serializeArray();
//set values of elements to cacheObject
$.each(serArr, function (arrayIndex,obj) {
if (cacheObject[obj.name]) {
cacheObject[obj.name].push(obj.value);
} else {
cacheObject[obj.name] = [obj.value];
}
});
//create new serialized array
var newSerArr = [];
$.each(cacheObject, function (key, value) {
var obj = {};
obj[key] = value;
newSerArr.push(obj);
});
console.log(newSerArr);//looks like serializeArray
This one makes a different array and elements of same name are grouped together.
var form_data = $(".wpc_contact").serializeArray();
var form_array = {}; //final array where all the values will be stored
$.each(form_data, function(i, element) {
if(jQuery('input[name="'+element.name+'"]:checked').length>0)
{
replaced = element.name.replace('[]',''); //removing [] from the input name
form_array[replaced]={};
jQuery('input[name="'+element.name+'"]:checked').each(function(j,ind){
form_array[replaced][j] = jQuery(this).val();
});
}
else
{
form_array[element.name] = element.value;
}
});
console.log(form_array);
You can access as:
alert(form_array['wpc_chkbox'][0]); //no '[]' in the key

Categories