Making a json file with an array of values to a key - javascript

I have many checkboxes in the html page. I have to send the json data to the server with an array of id's of all the checkboxes that are checked and also the label for these checkboxes.
I was thinking of using jquery with .each() function to check if a checkbox is checked and if it checked add it to the array.
The json file i am looking for is like this
{"checkbox id" : [1, 2, 3], "checkbox label" : ["check1", "check2", "check3"]}

If you want to keep the json structure, you can do the following:
var ids = [];
var labels = [];
$('input[type="checkbox"]').each(function () {
if ($(this).is(':checked')) {
var current_id = $(this).attr('id');
ids.push(current_id);
var current_label = $("label[for='" + $(this).attr('id') + "']").text();
labels.push(current_label);
}
});
var checkboxes = {
"checkbox_id": ids,
"checkbox_label": labels
};
var s_checkboxes = JSON.stringify(checkboxes);
Notice that you can't create a json file in the browser. You will have to do that in the server-side, once the data has been sent.

you can just use the jquery :checked selector to get all the checkboxes that are checked..
var checkedCheckBoxes = $( "input:checked" )
jQuery checked selector

Assuming this HTML:
<label for="checkBox">Label</label>
<input id="checkBox" type="checkbox" />
I would suggest this form of json:
var arr = [];
$('input[type="checkbox"]:checked').each(function() {
var that = $(this);
var id = that.attr('id');
var label = $('label[for="' + id + '"]').text();
var obj = {
id: id,
label: label
}
arr.push(obj);
});
And you would come up with this:
arr = [{id:"1",label:"labelOne"},{ ... }];

If you are looking for a way to format your JSON, I'd put all the information on the checked boxes inside an array looking like this:
{
"checked_boxes" :
[{"id": "1", "label": "checkbox1"},
{"id": "2", "label": "checkbox2"},
{"id": "3", "label": "checkbox3"]
}

Related

Type to search from input box

I have a form where a user can choose their Occupation. The list of occupations are in a seperate .js file like so:
var occupationSelect = "<select id='occupationSelect' onchange='selectChange()' ><option value=''></option><option value='v10173' >AA Patrolman</option><option value='v10174' >Abattoir Inspector</option>
Now in my form I want the input box (as the occupation list is very long) , for the user to type A, B etc and then the relevant occupations come up. Something like the following jsfiddle
Similar JS Fiddle
This fiddle is fine if I put all the Occupations into an array.
However the options in my .js file have values attached for use later in the web application (eg. option value='v10173')
What is the best option to get the Occupation by typing but also to make sure the value is attached.
Edited the js fiddle:
<input name="car" list="anrede" />
<input name="car-val" hidden />
<ul id="anrede"></ul>
var mycars2 = [
['Herr', 'herr'],
['thomas', 'v2345'],
];
var list = $('#anrede');
listHtml = '';
mycars2.forEach(function(item){
var option = '<li data-val="' + item[1] + '">' + item[0] + '</li>';
listHtml += option;
});
list.html(listHtml);
$('#anrede li').on('click', function(){
$('input[name="car"]').val($(this).html());
$('input[name="car-val"]').val($(this).attr('data-val'));
});
This needs jquery, and the names/values are stored in pairs inside the list.
A hidden input is used for the value.
I would suggest using data-value attribute for the "value" of selected item and array of objects, like so:
var mycars = [
{
title: 'Herr',
value: 'Herr Value'
},
{
title: 'Frau',
value: 'Frau Value'
}
];
var list = document.getElementById('anrede');
var input = document.getElementById('carList');
mycars.forEach(function(item) {
var option = document.createElement('option');
option.value = item.title;
option.dataset.value = item.value;
list.appendChild(option);
});
input.onchange = function() {
alert(document.querySelector('option[value="' + this.value + '"]').dataset.value)
}
here is the jsfiddle - https://jsfiddle.net/0jvt05L0/302/

Post data to 2 dimensional array javascript

I have source, like this :
<label>Name:</label>
<input type="text" name="text1"/>
<label>Weight:</label>
<input type="text" name="text2"/>
<button onclick="myfunction">Add</button>
<p id="demo"></p>
<script>
var array = new Array();
function myFunction() {
var text1 = document.getElementById("text1").value;
var text2 = document.getElementById("text2").value;
if(text1 == "" || text2 == ""){
alert("Empty!!");
}else{
array = {'data' : [{"Text1" : text1, "Text2" : text2}]}
}
}
</script>
My question is, how do i post value each of text to 2 dimensional array in java script? technically, we can post value to 2D array again and again, so the array will looks like:
var data = {{text1,text2},....,{text-n,text-n+1}}
Then figure it out in table based on 2D array. I have tried, but still not work. I'm not proficient with javascript. Really need help..
You can push a new element to your array every time the button is clicked. The use this array.
var array = [];
function change() {
var text1 = document.getElementById("text1").value;
var text2 = document.getElementById("text2").value;
if (text1 == "" || text2 == "") {
alert("Empty!!");
return;
}
array.push({
'data': {
"Text1": text1,
"Text2": text2
}
});
console.log(array);
}
Also, you are trying to get element by Id but no Id is assigned to input elements. I corrected that in the this Fiddle. This is working, take a look.
You need to use Jquery for this
var array = {
'x': { a: 'aaa', c: 'xxx' },
'y': { b: 'bbb', d: 'yyy' }
};
Use Jquery here
$.post( '/herp.php', array, function(d) {
// process response here
});
Put your input in a form, then use serializeArray in jquery.

HTML5 Local Storage store form data for select box where multiple values are selected

I have a form which saves a users preferance in local storage, it can be seen in this fiddle or below.
With what I have so far there are 2 main problems.
On clicking the save button you are meant to empty the myStorage then append what you have just selected in there, so they can see the live result of what they have clicked. It only remembers if you re-run the fiddle.
My biggest problem is that what I have is great for select fields with one option but in this case the user can select multiple, so what do I need to add to it so that the user can save multiple values to local storage so next time they load the page there multiple selections will be saved?
<form name="Filter">
<select multiple="1" id="filter">
<option value="111">Andrew</option>
<option value="222">Bill</option>
<option value="333">Charles</option>
<option value="444">Dikembe</option>
<option value="555">Edward</option>
</select>
</form>
<div id="store">click to store</div>
<br>
<h3>People I have stored</h3>
<div id="myStorage"></div>
JS
var iSelectedTitle = localStorage.getItem('title');
var iSelectedVal = localStorage.getItem('value');
console.log("iSelectedTitle: " + iSelectedTitle);
console.log("iSelectedVal: " + iSelectedVal);
$("#filter option").each(function () {
if ($(this).val() == iSelectedVal) {
$(this).attr("selected", "selected");
}
});
$("#store").click(function () {
var mytitle = $("#filter option:selected").text();
var storedTitle = localStorage.setItem("title", mytitle);
console.log("mytitle: " + mytitle);
console.log("storedTitle: " + storedTitle);
var myValue = $("#filter option:selected").val();
var storedValue = localStorage.setItem("value", myValue);
console.log("myValue: " + myValue);
console.log("storedValue: " + storedValue);
if (iSelectedTitle != "undefined") {
$('#myStorage').empty().append(iSelectedTitle);
}
});
if (iSelectedTitle != "undefined") {
$('#myStorage').append(iSelectedTitle + ' - <a target= "_blank "href="http://www.example.com/' + iSelectedVal + '">View profile</a>');
}
You can add multiple options to an array using map of jQuery :
var optArray = $("#filter option:selected").map(function () {
return {
"title": this.innerHTML,
"value": this.value
}
}).get();
This will give you a nice array like this :
[
{ "title": "Andrew", "value": "111" },
{ "title": "Bill", "value": "222" },
{ "title": "Charles", "value": "333" }
]
For adding to localStorage :
$("#store").click(function () {
//get the selected options in the form of an array
var optArray = $("#filter option:selected").map(function () {
return {
"title": this.innerHTML,
"value": this.value
}
}).get();
console.log(optArray);
//set that to localStorage
localStorage["optArray"] = JSON.stringify(optArray);
//refresh myStorage
getFromStore();
});
For refreshing the myStorage container with your newly added people, you'll have to call this handler as the last event inside the `click event (above).
var getFromStore = function () {
//check if store values are null, if null, make store =[]
var store = [undefined, null].indexOf(localStorage["optArray"]) != -1 ? [] : JSON.parse(localStorage["optArray"]);
console.log(store);
//empty container before u put values
$('#myStorage').html('');
//check if store is empty
if (store.length != 0) {
//loop over store if it aint empty and append the content into myStorage div
for (var k in store) {
var str = '<div>' + store[k]["title"] + ' - <a target= "_blank" href="http://www.example.com/' + store[k]["value"] + '">View profile</a></div>';
console.log(store[k]);
$('#myStorage').append(str);
}
} else {
//do this if no data is found in localStorage
$("#myStorage").html("No people found in store");
}
}
Then, in DOM ready, call getFromStore to refresh myContainer on load of the page:
$(function() {
getFromStore();
})
Demo : http://jsfiddle.net/hungerpain/hqVGS/9/
EDIT
To select the checkboxes by default, add the folowing line in the getFromStore function :
$("[value=" + store[k]["value"] + "]","#filter").prop("selected", true); //find the option with the corresponding value and select it
Updated demo : http://jsfiddle.net/hungerpain/hqVGS/10/
You could save multiple values in an array,
var myValuesArr = ['one','two','three'];
The array would need to be serialized before it is saved to localStorage
var serialVals = JSON.stringify(myValuesArr);
localStorage.setItem('numbers',serialVals);
Likewise, the stored data will have to be unserialized after it is read back
var serialVals = localStorage.getItem('numbers');
var myValuesArr = JSON.parse(serialVals);

How to get value of an HTML element nested inside other HTML elemnts?

I have HTML elements as shown below
<div id="container">
<div>
<span>
<input type="text" id="item1" value="AA"/>
</span>
</div>
<div>
<span>
<input type="text" id="item2" value="BB"/>
</span>
</div>
<div>
<span>
<input type="text" id="item3" value="CC"/>
</span>
</div>
</div>
I need to extract array of values like [AA,BB,CC] and IDs like [1,2,3] -from item1,item2,item3 using JavaScript and Jquery .How to do the same?
Try
var idarray = [];
var valuearray = [];
$("#container input").each(function(){
var $this = $(this);
idarray.push($this.attr("id").substring(4));
valuearray.push($this.val());
});
console.log(idarray);
console.log(valuearray);
Demo: Fiddle
var arr = $('#container').find('input').map(function(){
return $(this).val();
}).get();
var ids = $('#container').find('input').map(function(){
return $(this).attr('id').replace('item','');
}).get();
http://jsfiddle.net/mohammadAdil/Qhm5J/1/
var ids = $("input[id^='item']").map(function(i,e){
return e.id;
});
var values = $("input[id^='item']").map(function(i,e){
return $(e).val();
});
console.log(ids);
console.log(values);
Working Example: http://jsfiddle.net/RLsCX/
Please refer
http://jsfiddle.net/2dJAN/8/
var ids = []
var values = []
$('#container input[type=text]').each(function() {
ids.push($(this).attr('id'));
values.push($(this).val())
})
alert(ids)
alert(values)
var arrId = [], arrVal = [];
$("input[type='text']").each(function(){//find input text
if(this.id && this.id.indexOf("item")===0){//check id starts with item
arrId.push(this.id.replace("item",""));//push id
arrVal.push(this.value);//push value
}
});
http://jsfiddle.net/jGNy7/
Try this:
$(document).ready(function() {
var valuesArray = []
, idsArray = [];
$('#container').children().each(function() {
valuesArray.push($(this).children().children().val());
idsArray.push($(this).children().children().prop('id').substr(4));
});
alert(valuesArray);
alert(idsArray);
});
Try this:
var vals = [];
var ids = [];
$("#container input").each(function(){
vals.push($(this).val());
ids.push($(this).attr("id").replace("item", ""));
});
Here is the jsfiddle:
Loop the inputs, pull the values, parse the item value. Something like this:
var ids = [];
var values = [];
$("input").each(function(){
var input = $(this);
var value = input.val();
var id = input.attr("id").replace("item", "");
ids.push(id);
values.push(value);
});
Here is a working example (warning: two alert popups)
Notice the the input value is obtained using input.val(), this will ensure that the value retrieved is the current value as entered by the user. If you wanted the attribute value (which will not be changed simply by the user typing something else) you could use input.attr("value") instead
If you have other input elements on the page that you do not want to include then you need to be more specific with you selector. For example, if all the desired input elements are with the id="container" element, then you can use this instead:
$("#container input").each(...

How to serialize multiple checkbox values by jQuery?

I modified the simple example of jQuery.post as
$("#searchForm").submit(function(event) {
event.preventDefault();
var $form = $( this ),
term = $( "input[name^=tick]:checked" ).serialize(),
url = $form.attr( 'action' );
$.post( url, { ticks: term, id: '55' },
function( data ) {
$( "#result" ).empty().append( data );
}
);
});
This works for single checkbox with val() but not for multiple checkboxes in
<input type="checkbox" name="tick" value="'.$value.'" />
since serialize() should generateticks: termto be used astermin$.post`.
How can I make the serialize() to generate appropriate data for $.post
NOTE: I do not want to serialize the entire form but only checked values of checkbox INPUT.
Simple value collector :)
HTML
<input type="checkbox" class="selector" value="{value}"/>
JS
var checked='';
$('.selector:checked').each(function(){
checked=checked+','+$(this).val();
});
PHP
$ids=explode(',',substr($_GET['param_with_checked_values'],1));
You could use .serializeArray()
Ref: http://api.jquery.com/serializeArray/
In html code change name="tick" in name="tick[]" and you can use simply $(this).serialize(); to post all checked values.
You can still use .serializeArray and use it in .post() like this:
var postData = {};
var form = $('#formId').serializeArray();
for (var i = 0; i < form.length; i++) {
if (form[i]['name'].endsWith('[]')) {
var name = form[i]['name'];
name = name.substring(0, name.length - 2);
if (!(name in postData)) {
postData[name] = [];
}
postData[name].push(form[i]['value']);
} else {
postData[form[i]['name']] = form[i]['value'];
}
}
$.post('/endpoint', postData, function(response) {
}, 'json');
postData will contain all form elements except the disabled ones. All checkbox values will be passed as an array just like when doing a normal form submission.
let $form = $(".js-my-form");
let $disabled = $form.find(':input:disabled').removeAttr('disabled');
let formData = {};
$.each($form.serializeArray(), function (index, fieldData) {
if (fieldData.name.endsWith('[]')) {
let name = fieldData.name.substring(0, fieldData.name.length - 2);
if (!(name in formData)) {
formData[name] = [];
}
formData[name].push(fieldData.value);
} else {
formData[fieldData.name] = fieldData.value;
}
});
$disabled.attr('disabled', 'disabled');
console.log(formData);
Its a variation of Stanimir Stoyanov answer with possibility to serialize disabled fields.
term = $("#input[name^=tick]:checked").map(function () {
return this.value;
}).get();
term.join();

Categories