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!
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
}
});
Intro
I have a search bar I implemented into my website which searches through member cards to find matching cards. I also used Twitter's typeahead.js for this. The results are updated as you type, so I set an event listener on the input box - $('#members-search .typeahead').on("input", changeFunction); I also needed to set a click event listener on the suggestions, as I did - $('.tt-suggestion').on("click", changeFunction);
Problem
It seems like the suggestion boxes are created on the fly, so you can't set an event listener for all (or even any!) of them at the beginning. My first idea was to fire a function when an element was appended in the containing div. However, you would need an event listener for that, and I couldn't find one. Is there any way to implement this?
Code
The JavaScript:
var substringMatcher = function(strs) {
return function findMatches(q, cb) {
var matches, substringRegex;
// an array that will be populated with substring matches
matches = [];
// regex used to determine if a string contains the substring `q`
substrRegex = new RegExp(q, 'i');
// iterate through the pool of strings and for any string that
// contains the substring `q`, add it to the `matches` array
$.each(strs, function(i, str) {
if (substrRegex.test(str)) {
matches.push(str);
}
});
cb(matches);
};
};
var children = document.getElementById("members-list").children;
var names = [];
var whoIsWho = [];
var selected = [];
var listOfAttributeNames = ["data-member-name", "data-member-username", "data-member-nickname"];
for(var i = 0; i < children.length; i++){
for(var j = 0; j < listOfAttributeNames.length; j++){
var a;
if(a = children[i].getAttribute(listOfAttributeNames[j])){
names.push(a);
whoIsWho.push(children[i]);
}
}
}
$('#members-search .typeahead').typeahead({
hint: true,
highlight: true,
minLength: 1
},
{
name: 'names',
source: substringMatcher(names)
});
var previousValue = "";
function changeFunction(e){
var v;
if($("#members-search .typeahead").val() === ""){
previousValue = "";
}
else if(((v = $('#members-search .typeahead+pre').text())) !== previousValue){
previousValue = v;
}
else if(v !== $("#members-search .typeahead").val()){
previousValue = $("#members-search .typeahead").val();
}
selected = [];
v = $('#members-search .typeahead+pre').text();
for(var i = 0; i < names.length; i++){;
if(!(new RegExp(v, "i").test(names[i])) && !(selected.includes(whoIsWho[i]))){
whoIsWho[i].style.display = "none";
}
else{
selected.push(whoIsWho[i]);
whoIsWho[i].style.display = "block";
}
}
}
$('#members-search .typeahead').on("input", changeFunction);
$('.tt-suggestion').on("click", changeFunction);
The (important) HTML:
<div id="members-search">
<input class="typeahead" type="text" placeholder="Search">
</div>
Alternate, Backup Solutions
I could copy the bloodhound script over to my code and modify where the elements are appended, but I'd rather not, as it uses this weird format of IIFE that I won't take the time to understand. Or is there another solution and this question is part of the X/Y problem?
It turns out I had the wrong approach. I just added an event listener to the current suggestions every time the input value was changed.
$('#members-search .typeahead').on("input", function(){
$('.tt-suggestion').on("click", changeFunction);
});
I am trying to retrieve en array via alert but after every click I get the same value 1 instead of more 1 after each click. I tried both with loop and without. I tried var seats = new Array(); too.
What I am doing wrong?
var seats = [];
function loadSubmitBtn() {
document.getElementById("btnSubmit").addEventListener("click", function () {
showArray();
});
}
function showArray() {
seats.push("1");
var test = "";
for (i = 0; i < seats .length; i++) {
test += seats [i];
}
alert(test);
alert(seats);
}
I was using <input type="submit"> and it is working after I changed it to <input type="button">
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
I have 2 drop downs and I can move the objects from one to another using the buttons. I want to get the updated values after I am done with moving them from one drop down to another. the values in the array is coming out to be null.
How can I get the updated value of all the options in an array. I need to pass the updated values to the controller from one function like function AddFiles(iniIdArray,afterIdArray)
http://jsfiddle.net/678hmujh/1/
var varInitialId = document.getElementById('iniId');
for (i = 0; i < varInitialId.options.length; i++) {
iniIdArray[i] = varInitialId.options[i].value;
}
var varAfterId = document.getElementById('afterId');
for (i = 0; i < varAfterId.options.length; i++) {
afterIdArray[i] = varAfterId.options[i].value;
}
You could use map: http://jsfiddle.net/678hmujh/4/
$('#listButton').on('click', function() {
var first = $('#iniId option').map(function(){ return this.value; });
var second = $('#afterId option').map(function(){ return this.value; });
console.log( first.toArray() );
console.log( second.toArray() );
});
By doing first.toArray() or second.toArray() you can get a basic javascript array of what was built.
$('select#iniId > option').each(function() {
$(this).text(); //is your option text
$(this).val(); //is your option value
});