I am trying to loop through an array of elements and then validate each instance of each element. This is how I am doing it:
var elements = ["h1","h2","h3","h4","p","strong","label","span","a"];
function targetZWS(){
for (var i = 0; i < elements.length; i++) {
var item = $(".page-content "+elements[i]);
$(item).each(function() {
checkElement(this);
});
}
}
This throws a warning that I am creating a function inside a loop, how do I avoid this?
You are trying too hard :) JQuery allows you to enter multiple options in a single selector.
function targetZWS(){
$("h1,h2,h3,h4,p,strong,label,span,a").each(function() {
checkElement(this);
});
}
}
http://api.jquery.com/multiple-selector/
Use .each() to loop through the array as:
$(function() {
var elements = ["h1","h2","h3","h4","p","strong","label","span","a"];
$.each(elements, function(index, value) {
alert(value);
var sel = ".page-content" + value
var item = $("sel");
$(item).each(function() {
checkElement(this);
});
})
})
DEMO
Related
How can I pass values from an array from one event click to another with jQuery?
Here is an example of I want to do: the first click event adds or remove values from the array if the input checkbox is selected or not. In the second click I want to loop trough all the elements of this array.
var array=[];
$( "input" ).on( "click", function() {
var $input=$(this)
if($input.is(":checked")){
array.push($(this).val()); //append check box value to array if is selected
}
else{
array.pop($(this).val()); // remove check box value to array if is not selected
}
})
$('#cmd').click(function() {
for (i of array) {
console.log(array[i]); // loop trough all elements in array
...
});
Your code looks ok except two things. First for for (i of array). Using of will return actual value as i, but you are using value as index in array[i].
If you want use index then use for (let i = 0; i < array.length; i++) instead.
You can also use Array.prototype.forEach() but you can't break out of it's loop https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/forEach
Second thing is that .pop() doesn't support parameter. Use code below instead of .pop()
var index = array.indexOf($input.val());
if (index > -1) {
array.splice(index, 1);
}
If your event handlers are in different scope and #cmd handler can't see the array. You might use this little bit bad solution for sharing the array between scopes :)
$("input").on( "click", function() {
var array = $("#cmd").data("arr") || [];
var $input= $(this);
var value = $input.val();
if($input.is(":checked")){
array.push(value); /
} else {
var index = array.indexOf(value);
if (index > -1) {
array.splice(index, 1);
}
}
$("#cmd").data("arr", array);
});
$('#cmd').click(function() {
var array = $(this).data("arr") || [];
for (let value of array) {
console.log(value); // loop trough all elements in array
}
});
I want to find all elements inside #Grid, then inside a first "TR" tag they should have attribute role="row" and attribute role="columnheader".
I've got it and it works fine.
Example:
var elements = $("#Grid").find("tr").attr("role","row").first().find("th").attr("role", "columnheader");
What I want to do is to filter it only to elements which meet the condition: offsetWidth < scrollWidth
I tried like below, but this is the incorrect result:
var elements = $("#Grid").find("tr").attr("role", "row").first().find("th").attr("role", "columnheader");
var filtered = elements.filter(function () {
return $(this).offsetWidth < $(this).scrollWidth;
});
I can use this function as well, but I don't really know how to combine it in jQuery:
function isEllipsisActive(e) {
return (e.offsetWidth < e.scrollWidth);
}
Should work:
var filtered = elements.filter(function () {
return this.offsetWidth < this.scrollWidth;
});
Don't use $(this), use the element variable existing in the filter function.
var filtered = elements.toArray().filter(function (e) {
return e.offsetWidth < e.scrollWidth;
});
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).
Array value validation error the option else statement is not working
I need to check whether the value are existing or not in array using jquery
$(document).ready(function (){
$('.txtbox').focusout(function () {
var bind = [10];
var data = $(this).val();
for (var j = 0; j < 10; j++) {
if (bind[j] == data) {
alert("This Name Is Already Exist");
$(this).val("");
$(this).focus();
}
else {
bind[j] = data;
}
}
});
});
Html Code:
<input type="text" class = "txtbox" id="0"/>
<input type="text" class = "txtbox" id="1"/>
<input type="text" class = "txtbox" id="2"/>
You have just one element in data and in second iteration bind[j] == data will through exception as there is still one element in array and you are trying to access second element as j=1 point to second element of array. This results in exception. You better using indexOf to find element in array. Also declare array outside event handler to make it global so that it holds data until next focusout call.
Live Demo
$(document).ready(function (){
var bind = [];
var j = 0;
$('.txtbox').focusout(function () {
var data = $(this).val();
if (bind.indexOf(data) != -1) {
alert("This Name Is Already Exist");
$(this).val("");
$(this).focus();
}
else {
bind[j++] = data;
}
});
});
var bind = [10]; doesn't create an Array of Size 10 ...instead an Array containing only one element.Hence you cannot apply a loop of 10 iterations to that array!
I have 3 HTML combo/drop down boxes. All of them have a distinct name and id.
On a particular event I want to get the value of all three of them.
Can any one give me a code snippet for that?
using jQuery:
$("#dropdownID").val();
I'd try to set them up next to each other in your HTML and then iterate through them using jQuery's built-in each() method. You'd set up your elements like this:
<div id="dropdownBoxes">
<select id="firstElement">
<option>cool</option>
<option>neat</option>
</select>
<select id="secondElement">
<option>fun</option>
<option>awesome</option>
</select>
<select id="thirdElement">
<option>great</option>
<option>synonym</option>
</select>
</div>
<input type="button" id="theTrigger">Push me!</input>
Then, in your script:
var dropdownValues;
$("#theTrigger").click(function(){
dropdownValues.length=0;
$("#dropdownBoxes select").each(function(){
dropdownValues.push($(this).val());
});
});
To do this not using jQuery:
function getSelectValues() {
var values = [];
for (var i = 0; i < arguments.length; i++) {
var select = document.getElementById(arguments[i]);
if (select) {
values[i] = select.options[select.selectedIndex].value;
} else {
values[i] = null;
}
}
return values;
}
This function returns an array of values that correspond to the ids you pass into the function, as follows:
var selectValues = getSelectValues('id1', 'id2', 'id3');
If a <select> with one of your specified ids does not exist the array contains null for the value for that position.
There are a couple of other ways to do this, you could pass the function an array of id values: getSelectValues([ 'id1', 'id2', 'id3' ]), in which case the function would be changed:
function getSelectValues(ids) {
var values = [];
for (var i = 0; i < ids.length; i++) {
// ...
You could also pass the function a map of ids and populate the values:
var myMap = { 'id1': null, 'id2': null, 'id3': null };
getSelectValues(myMap);
// myMap['id1'] contains the value for id1, etc
This would change the function to be:
function getSelectValues(map) {
for (var id in map) {
var select = document.getElementById(id);
if (select) {
map[id] = select.options[select.selectedIndex].value;
} else {
map[id] = null;
}
}
}
Use a framework like jQuery mentioned above or just do it the old school way. document.getElementById('dropdownId').value .