var selValues = {};
selValues['234'] = $('#asd').val();
selValues['343'] = function () { var el = ''; $('#asd input[#type=checkbox]:checked').each(function() { el += $(this).val() + '|'; }); return el; } };
here's the explanation:
im creating a key-value array where it extracts different values from DOM objects. The last array that you see in the example actually tries to extract checked items in a checkbox list. I tried to delegate the loop and return a delimited string of all checked values, but it's not working.
A mapping is probably a better solution here:
var el = $('#asd input:checkbox:checked').map(function(){
return $(this).val();
}).get().join('|');
If I'm understanding your question correctly, the problem you are running up against is that you are merely storing a function in selValues['343'], not evaluating it.
You could try selValues['343'] = function () { var el = ''; $('#asd input[#type=checkbox]:checked').each(function() { el += $(this).val() + '|'; }); return el; } }(); (notice the parentheses at the end) which should evaluate your function and store the result in selValues['343'].
Seems to work for me: http://jsfiddle.net/HM4zD/
Related
I have a Jquery function that helps with validation over 1 object. I need to expand it so that the function will run over 3 different objects. I am trying to define a function that takes a parameter(whichquote) to insert the appropriate object in the function. Here is my code. What I am doing wrong? I assume I do not have the selector correct as the code works if I put it in.
Original Function that works:
var depends = function() {
var selectorD = $("input[name^='lead[quote_diamonds_attributes]'], select[name^='lead[quote_diamonds_attributes]']");
var vals = '';
selectorD.not(':eq(0)').each(function () {
vals += $(this).val();
});
return vals.length > 0;
};
Function I am trying to create that allows me to use it on other objects. This currently does not work.
var depends = function(whichquote) {
var selectorD = $("input[name^='lead[+ whichquote +]'], select[name^='lead[+ whichquote +]']");**
var vals = '';
selectorD.not(':eq(0)').each(function () {
vals += $(this).val();
});
return vals.length > 0;
};
I think the problem is with my concating in the var selectorD but cannot seem to get the syntax correct.
Your selector isn't actually inputting whichquote because the string concatenation is incorrect.
Try
var selectorD = $("input[name^='lead[" + whichquote + "]'], select[name^='lead[" + whichquote +"]']");
Is there an easy way to fix this code:
title_1 = $(this).closest('tr').find('td').html();
title_2 = $(this).closest('tr').find('td').next().html();
title_3 = $(this).closest('tr').find('td').next().next().html();
question = question.replace(/{title_1}/g, title_1);
question = question.replace(/{title_2}/g, title_2);
question = question.replace(/{title_3}/g, title_3);
So it isn't so dully (repeated) and can cover n occurences of title_ pattern?
I'm a beginner Javascript developer and a complete regular expressions newbie (actually, they scare me! :|), so I'm unable to do this by myself. I've tried to look for an inspiration in different languages, but failed.
You can use a function in the replace, to get the value depending on what you find:
question = question.replace(/{title_(\d+)}/g, $.proxy(function(x, m){
return $(this).closest('tr').find('td:eq('+(m-1)+')').html();
}, this));
Demo: http://jsfiddle.net/n3qrL/
String.prototype.replace() could take a function as second parameter.
var $this = $(this);
question = question.replace(/\{title_(\d+)\}/g, function(match, n) {
return $this.closest('tr').find('td').eq(n - 1).html();
});
Demo Here
Try this ,
Generalized for getting all td tag's text value :
$("table").find("tr").each(function(){
$(this).find("td").each(function(){
alert($(this).html());
var txt=$(this).html();
//var pattern="/{"+txt+"}/g";
//question = question.replace(pattern, txt);
});
});
NB. In your question you have not mentioned the value for 'question' . please define value for 'question'
It seems to me that you want to get the text content of the first three cells of a table row and use it to replace the content of a string, and that this is an element somewhere in the row. So you can do:
var n = 3; // number of cells to get the text of
var textArray = [];
var tr = $(this).closest('tr')[0];
var reString;
for (var i=0; i<n; i++) {
reString = '{title_' + (i+1) + '}';
question = question.replace(reString, tr.cells[i].textContent);
}
If you wish to avoid jQuery's closest, you can use a simple function like:
function upTo(el, tagName) {
tagName = tagName.toLowerCase();
do {
el = el.parentNode;
if (el.tagName && el.tagName.toLowerCase() == tagName) {
return el;
}
} while (el.parentNode)
}
then:
var tr = upTo(this, 'tr');
I have a Array like
text=['2','2<sup>2</sup>','3<sup>10</sup>'.......];
I want result like this
text=['2','22','310'......];
How can i get This using javascript
var optionTxt = (xmlDoc.getElementsByTagName('Option')[i].textContent ? xmlDoc.getElementsByTagName('Option')[i].textContent : xmlDoc.getElementsByTagName('Option')[i].text);
optionList[i] = $.trim(optionTxt);
You can use a .map operation for that and replace any non-digit with nothing using .replace():
text.map(function(item) {
return item.replace(/\D/g, '');
});
Since you're using jQuery you might also use their .map instead to fully benefit from cross (old) browser compatibility:
$.map(text, function(item) {
return item.replace(/\D/g, '');
});
Use .map() and .replace(). Try this:
var text=['2','2<sup>2</sup>','3<sup>10</sup>'];
text = $.map(text,function(i){
return i.replace( /[^\d.]/g,'');
});
console.log(text);
DEMO
Try jQuery html parsing:
var text = ['2', '2<sup>2</sup>', '3<sup>10</sup>'];
var out = [];
jQuery.each(text, function (si, str) {
var concat = '';
jQuery.each(jQuery.parseHTML(str), function (ei, el) {
concat = concat + el.textContent;
});
out.push(concat);
});
check out this fiddle: http://jsfiddle.net/9cV7M/
I have some code I want to put into a JSON object ultimately. But first I want to create a javascript object and within that object add an array of values. Sounds simple enough but my approach seems wrong. First I create a basic object, the set a few fields. Lastly, iterate over a bunch of checkboxes and then, if one is checked at that value to an array.
At the last step I need to add that array to my object (myData) and then JSONify it.
Any ideas how I can do this, seems myData.push(filters); doesn't work...
Note that the object itself is not an array, I want to place an array IN the object.
var myData = new Object();
myData.deviceId = equipId;
myData.dateTo = dateTo
myData.dateFrom = dateFrom;
myData.numResults = $("#numResults").val();
var i=0;
var filters = [];
$('input[type=checkbox]').each(function () {
if (this.checked) {
allData += $(this).val() + ",";
filters[i] = {
filterIds: $(this).val()
};
++i;
}
});
myData.push(filters);
That's not how to add items to an Object, change
myData.push(filters);
to
myData.filters = filters;
Also, maybe change = new Object to = {}. There's no difference, but it's easier to read, because literal notation takes up less space.
Read more about Array.prototype.push
Use push to add elements to the filters array. Use property assignment to add another property to the myData object.
var myData = {
deviceId: equipId,
dateTo: dateTo,
dateFrom: dateFrom,
numResults: $("#numResults").val()
};
var filters = [];
$('input[type=checkbox]').each(function () {
if (this.checked) {
allData += $(this).val() + ",";
filters.push({
filterIds: $(this).val()
});
}
});
myData.filters = filters;
BTW, don't use new Object() to create an object, use {}.
Remove the need for an extra array and i.
var myData = {}
myData.deviceId = equipId;
myData.dateTo = dateTo
myData.dateFrom = dateFrom;
myData.numResults = $("#numResults").val();
myData.filters = [];
$('input[type=checkbox]').each(function () {
if (this.checked) {
allData += $(this).val() + ",";
myData.filters.push({
filterIds: $(this).val()
});
}
});
EDIT 2
Check the fiddle - http://jsfiddle.net/SN5zT/2/
Following is the fiddle for which I am not sure why I am getting undefined in dropdown.
My fiddle - http://jsfiddle.net/z6GDj/
var res = '{"allSportPosition":{"25":"Forwards (Strickers)","27":"Fullbacks (Defenders)","28":"Goalkeeper ","26":"Midfielders"}}';
try {
var sportPositionOptions = '';
var parsedJson = JSON.parse(res);
var allSportPosition = parsedJson.allSportPosition;
var values = new Array();
$.each(allSportPosition, function (index, value) {
values[index] = value;
});
//alert(values.length);
values.sort();
$.each(values, function (atIndex, atValue) {
sportPositionOptions = sportPositionOptions + '<option value="' + atIndex + '">' + atValue + '</option>';
});
$(sportPositionOptions).appendTo("#player");
} catch (e) {
alert("Parsing error:" + e);
}
$.each is automatically sorting keys to 25,26,27,28 for res.
Please explain the reason of this and why I am getting undefined ?
Let me know If i need to explain it more, I will surely do it :)
EDIT
Please explain the reason why it is getting sorted automatically http://jsfiddle.net/SN5zT/
Try
values.push(value);
instead of
values[index] = value;
Fiddle Link
The following script is working, I also figured out where the "undefineds" came from.
http://jsfiddle.net/z6GDj/3/
var res = '{"allSportPosition":{"25":"Forwards (Strickers)","27":"Fullbacks (Defenders)","28":"Goalkeeper ","26":"Midfielders"}}';
try{
var sportPositionOptions = '';
var parsedJson = JSON.parse(res);
var allSportPosition = parsedJson.allSportPosition;
var values = allSportPosition;
//$.each(allSportPosition, function(index, value) {
// values[index] = value;
//});
//alert(values.length);
$.each(values,function(atIndex, atValue){
sportPositionOptions = sportPositionOptions+'<option value="'+atIndex+'">'+atValue+'</option>';
});
$(sportPositionOptions).appendTo("#player");
}
catch(e){
alert("Parsing error:"+ e);
}
The array is sorted automatically, because the keys are set correctly.
see http://www.w3schools.com/js/js_obj_array.asp. "An array can hold
many values under a single name, and you can access the values by
referring to an index number."
Or: Change the index, and you´re changing the order. (index indicates the order).
The undefined values are created by javascript default, check the last answer in here (How to append something to an array?)
"Also note that you don't have to add in order and you can actually
skip values, as in
myArray[myArray.length + 1000] = someValue;
In which case the values in between will have a value of undefined."
Since you are passing an object to each(), jquery passes the key as the index parameter. In your object, the keys are ranged from 25 to 28. Setting the array using the values[25] on an empty array will expand the array to index 25, with the first 25 elements undefined. Using values.push(value) will append the value at the end of the array.
$.each is doing the following assignment that is why you are getting so many undefined
values[25] = "Forwards (Strickers)"
values[26] = "Midfielders"
values[27] = "Fullbacks (Defenders)"
values[28] = "Goalkeeper"
During $.each browsers will automatically sort the keys if the keys are integer, one way to avoid this is use non integer keys
What you need to do is define your options before you sort them , and then append them to your select:
var res = '{"allSportPosition":{"25":"Forwards (Strickers)","27":"Fullbacks (Defenders)","28":"Goalkeeper ","26":"Midfielders"}}';
try {
var sportPositionOptions = '',
parsedJson = JSON.parse(res),
allSportPosition = parsedJson.allSportPosition,
options = new Array();
$.each(allSportPosition, function (index, value) {
options[index] = $('<option></option>', {
value: index,
text: value
});
});
$.each(options, function (index) {
$('#player').append(options[index]);
});
} catch (e) {
alert("Parsing error:" + e);
}
jsfiddle: http://jsfiddle.net/z6GDj/11/