Named Array Keys using .map() and .get() - javascript

I need to output inputs and their values into a div. However, because I need to match the correct labels to the correct inputs, and some fields allow null values, I'm running into matching issues. Using the following code to pull each label/input into an array, and then output:
var inputArr = $('input, select').map(function(){
return "<p>" + $(this).val() + "</p>";
}).get()
var labelArr = $('label').map(function(){
return "<p>" + $(this).text() + "</p>";
}).get()
function setValuesForConfirm() {
//Clear Div Contents
$("#test-output-1, #test-output").html('');
for (var i = 0; i < labelArr.length; i++) {
$("#test-output-1").append(labelArr[i]);
}
for (var i = 0; i < inputArr.length; i++) {
$("#test-output").append(inputArr[i]);
}
}
So if any of the input's are blank, the fields do not match the labels.
My question is, can I name the array keys to the field name or ID in JS using the .map() function as I am currently?
JSFiddle Here

You could create an object using the inputs:
var formObj={};
$('input, select').each(function(){
formObj[this.name]={val: this.value, labelText: $(this).prev('label').text()};
});
then when loop over object can throw together html
$.each(formObj, function(key, item){
var labelHtml='<p>'+item.labelText+'</p>';
var inputHtml='<p>Name: '+ key+', value: '+item.val+'</p>';
/* do something with html*/
})

While what you have seems to work okay to me, .map creates an array and you can only have numeric ordinal keys in arrays in JavaScript, so you would need an object.
var inputArr = {};
$('input, select').each(function(){
inputArr[$(this).attr('name')] = "<p>" + $(this).val() + "</p>";
});
http://jsfiddle.net/Mz9Vy/1/

Related

how to give $('inputs') each function as to store data as key value pair in asp.net

$("#btnSubmit").click($('#form1 input'), function() {
var data = new Object();
for (var i =1; i < form1.length-1; i++) {
data[i] = form1[i].name + ":" + form1[i].value ;
}
document.write(JSON.stringify(data));
How to avoid view state and how to get string json output?
$("#btnSubmit").click($('#form1 input'), function() {
var data = [];
for (var prop in form1) {
data.push(form1[prop]);
}
document.write(data);
});
jsfiddle
An easy way to select only desired input elements is, to put a class on them then select elements based on that class. $('#form1 input.post').each(...)
Another way is to select all input elements and keep a not selector for those which you want to exclude.
To parse array back from json string you can use $.parseJSON(jsonString)
You can see the sample fiddle here.

how to delete specific value from array jquery

Hello I can't find out how to delete a specific value from string when clicking on an element with the string value. its for my todo list.
if (window.localStorage.fullName !== undefined) {
alert('Your browser does not support localStorage');
} else {
$(function () {
console.log('localSorage compitability detected. proceeding...');
global vars & functions
var tdli = [];
add list items
$('#tdladd').click(function () {
$('.todolist ul ul').append("<li class='tdli'>" + $('#tdlinput').val() + "</li>");
tdli.push($('#tdlinput').val());
$('#tdlinput').val('');
var array = tdli + "";
localStorage.setItem('tdlis', array);
console.log(array);
$('#todolist').hide().fadeIn('fast');
});
remove list items
$('li').click(function () {
var itemtoRemove = $(this);
tdli.splice($.inArray(itemtoRemove, tdli), 1);
console.log(tdli);
});
$('#clearall').click(function () {
localStorage.clear();
location.reload();
});
load list items
var tdlitems = localStorage.getItem('tdlis');
var array = tdlitems.split(',');
tdli.push(array);
for (var i = 0; i < array.length; i++) {
array[i] + "<br>";
$('.todolist ul ul').append("<li>" + array[i] + "</li>");
};
console.log(array);
});
}
Assuming that tdli is a jQuery wrapped set (which itself is an array-like-object), it will have DOM nodes stored instead of another jQuery objects. That means, just go like
var itemtoRemove = this;
and you should be fine.
After you posted your complete code, we can see you're actually pushing string values into your tdli Array, but you try to .splice() objects respectively DOM nodes, which of course doesn't make any sense at all (comparing apples to oranges).

jQuery .each: Do not add comma in last field

I want to get values of all fields in a variable separated by a comma. For example: 1,2,3
The following code will work fine, but it only adds the comma at end of the last value also. How can I remove that?
fields = $('.wrap').find('.text');
var data = '';
fields.each(function() {
var value = $(this).val();
if ( value != '' ) {
data += ' ' + value + ',';
}
});
alert(data);
JSFiddle:
http://jsfiddle.net/cn5Gt/
I always use arrays for these kind of things:
var fields = $('.wrap').find(".text[value!='']");
var data = [];
fields.each(function() {
data.push($(this).val());
});
alert(data.join(','));
You can push elements on array than just use join() method.
fields = $('.wrap').find('.text');
var data = [];
fields.each(function() {
var value = $(this).val();
if ( value != '' ) {
data.push(value);
}
});
alert(data.join());
Try the code below, using the i which is the loop index and test against the length of the jQuery object.
fields = $('.wrap').find('.text');
var length = fields.length;
var data = '';
fields.each(function(i) {
var value = $(this).val();
if ( value != '' ) {
if(i === length-1) { //The last one
data += ' ' + value;
} else {
data += ' ' + value + ',';
}
}
});
Updated fiddle
You could just remove the final character afterwards?
data = data.substr(0, data.length - 1);
http://jsfiddle.net/cn5Gt/3/
Simplest of all:just replace your last line with the below line
alert(data.slice(0,-1));//where data is string
http://jsfiddle.net/cn5Gt/7/
DOC MDN : slice
How about something like this:
var data = $('.wrap').find('.text')
.map(function(i,el){ return el.value || null; })
.get().join(", ");
Demo: http://jsfiddle.net/cn5Gt/11/
jQuery's .map() method will "Pass each element in the current matched set through a function, producing a new jQuery object containing the return values." You can still include your if ( value != '' ) { test in the callback function because if your function returns null or undefined then .map() will not use that particular value. (I've used || null above as a shortcut to an if/else structure.)
Call .get() (or .toArray()) on the result and you'll have an actual array, which means you can then use the Array .join() method to form a string with the values comma separated.
If you need to do other processing on each item besides just getting the value you could stick with the .each() loop and add the values to an array that you then join after the loop (like some of the other answers), or just use the string .slice() method to remove the trailing comma and space characters.
Try this:
Using the length function to determine the position of the each
var fields = $('.wrap').find('.text');
var len = fields.length;
var data = '';
fields.each(function(index, element) {
var value = $(this).val();
if ( value != '' ) {
data += ' ' + value;
if (index != len - 1) {
data += ',';
}
}
});
alert(data);

get name and id of all text box's in HTML body using java script

Is it possible to get name and id of all text boxes in HTML body using JavaScript. If it is possible please give me a example or method.
You need to learn about document.getElementsByTagName and a for loop
If you want to use jQuery, learn about the element selector, .each(), and .prop()
Untested version
var textboxes = document.getElementsByTagName("INPUT");
for (var i=0;i<textboxes.length;i++)
{
var textbox = textboxes[i];
if (textbox.type.toLowerCase() == "text")
{
alert("Hurray, I found a text box. Name and Id are: " + textbox.name + ", " textbox.id);
}
}
Or using jQuery
$("input[type='text']").each(function() {
alert("Hurray, I found a text box. Name and Id are : " + $(this).attr("name") + ", " + $(this).attr("id"));
});
So you would get all the necessary input fields. For this demo I'll keep at regular input fields. You can expand this example for radio buttons with the same name or select boxes.
It stores all the properties in an object literal {} and outputs the object to demonstrate.
var arr = document.getElementsByTagName("input"),
i = 0,
len = arr.length,
obj = {},
inp,
output = document.getElementById("output");
// store attributes name and id
for (;i<len;i++){
inp = arr[i];
obj[inp.id] = inp.name;
}
// output obj properties and values
for (var prop in obj){
if (obj.hasOwnProperty(prop)){
output.innerHTML += prop + ": " + obj[prop];
}
}
Also note that looping over array-like objects (storage of properties) and looping over object literals (output) is a bit different.
Is this something you had in mind?
DEMO: http://jsfiddle.net/tive/4JrUf/
Using this:
$('#yourid').attr('name')
$('#yourid').attr('id')

Use "event's" output as a variable

I have a problem to manipulate checkbox values. The ‘change’ event on checkboxes returns an object, in my case:
{"val1":"member","val2":"book","val3":"journal","val4":"new_member","val5":"cds"}
The above object needed to be transformed in order the search engine to consume it like:
{ member,book,journal,new_member,cds}
I have done that with the below code block:
var formcheckbox = this.getFormcheckbox();
formcheckbox.on('change', function(checkbox, value){
var arr=[];
for (var i in value) {
arr.push(value[i])
};
var wrd = new Array(arr);
var joinwrd = wrd.join(",");
var filter = '{' + joinwrd + '}';
//console.log(filter);
//Ext.Msg.alert('Output', '{' + joinwrd + '}');
});
The problem is that I want to the “change” event’s output (“var filter” that is producing the: { member,book,journal,new_member,cds}) to use it elsewhere. I tried to make the whole event a variable (var output = “the change event”) but it doesn’t work.
Maybe it is a silly question but I am a newbie and I need a little help.
Thank you in advance,
Tom
Just pass filter to the function that will use it. You'd have to call it from inside the change handler anyway if you wanted something to happen:
formcheckbox.on('change', function(cb, value){
//...
var filter = "{" + arr.join(",") + "}";
useFilter(filter);
});
function useFilter(filter){
// use the `filter` var here
}
You could make filter a global variable and use it where ever you need it.
// global variable for the search filter
var filter = null;
var formcheckbox = this.getFormcheckbox();
formcheckbox.on('change', function(checkbox, value){
var arr = [],
i,
max;
// the order of the keys isn't guaranteed to be the same in a for(... in ...) loop
// if the order matters (as it looks like) better get them one by one by there names
for (i = 0, max = 5; i <= max; i++) {
arr.push(value["val" + i]);
}
// save the value in a global variable
filter = "{" + arr.join(",") + "}";
console.log(filter);
});

Categories