I've got a simple array that I want to loop through and search for whatever a user has typed into a text box. Here is what I have got. Bare in mind I am very new to JavaScript:
function recipeInfo(name, ingredients, url) {
this.name = name;
this.ingredients = ingredients;
this.url = url;
}
var vIngredients = new Array();
vIngredients[0] = new recipeInfo("Ackee Pasta", "ackee", "ackpast.html");
vIngredients[1] = new recipeInfo("Ackee and Saltfish", "ackee saltfish", "acksalt.html");
vIngredients[2] = new recipeInfo("Jerk Chicken", "jerk", "jerkchick.html");
// do the lookup
function getData(form) {
// make a copy of the text box contents
var inputText = form.Input.value
// loop through all entries of vIngredients array
for (var i = 0; i < vIngredients.length; i++) {
var list = $("#search-results");
// compare results
if (inputText == vIngredients[i].ingredients) {
console.log(vIngredients[i].name);
//add to the list the search result plus list item tags
list.append (
$("<li class='arrow'><a href='#' >" + vIngredients[i].name + "</a></li>" )
);
}
else {
// advise user
var list = $("#search-results");
// empty list then tell user nothing is found
list.empty();
list.append (
$("<li>No matches found for '" + inputText + "'</li>")
);
}
}
}
</script>
<form name="search" id="search" action="">
<ul class="rounded">
<li><input type="search" name="Input" placeholder="Search..." onkeydown="if (event.keyCode == 13) getData(this.form)"></li>
</ul>
<ul class="edgetoedge" id="results">
<li class="sep">Results</li>
</ul>
<ul class="edgetoedge" id="search-results">
</ul>
</form>
Here are the problems I'm having:
My search only looks for exact matches. In my example, the "ingredients" property will have more than 1 word in it, so I want to be able to search for any of those words instead of exactly what is in the array
If someone searches, the list just keeps appending to the existing list. How can I erase the contents of the before every search?
Lastly, my feedback for the user if no match is found always is shown instead of results, regardless if there are results or not. Commenting that section out makes the search work as normal but alas without the feedback if there is no match.
Thanks!
For #1, you want to see if the text in array slot contains the typed word as a substring. Do it like this:
// compare results
if (vIngredients[i].ingredients.indexOf(inputText) != -1) {
For #2, list.empty() should do it. You have that in your "else" block for the case when no results were found.
For #3 how do you know that results are actually being found? Does "inputText == vIngredients[i].ingredients" ever evaluate to "true"? Does console.log(vIngredients[i].name); log as you'd expect it to?
If you're new to javascript, you may not know about breakpoint debuggers in various browser developer tools. These are invaluable .
Related
I have found some code for a chat system. I am going to be using it as a child-friendly (so I can't be blamed for anything) global chat. The way the code works is by checking the input to see if it contains any word from an array, if it does then the program will display something to a <ol> tag, for me to see if it works. Otherwise is does nothing.
JQUERY
var banned_words = {
'songs': ['hello', 'sorry', 'blame'],
'music': ['tempo', 'blues', 'rhythm']
};
function contains(words) {
return function(word) {
return (words.indexOf(word) > -1);
};
};
function getTags(input, banned_words) {
var words = input.match(/\w+/g);
return Object.keys(banned_words).reduce(function(tags, classification) {
var keywords = banned_words[classification];
if (words.some(contains(keywords)))
tags.push(classification);
return tags;
}, []);
};
// watch textarea for release of key press
$('#sendie').keyup(function(e) {
$('#tags').empty();
var tags = getTags($(this).val().toLowerCase(), banned_words);
var children = tags.forEach(function(tag) {
$('#tags').append($('<li>').text(tag));
});
if (e.keyCode == 13) {
var text = $(this).val();
var maxLength = $(this).attr("maxlength");
var length = text.length;
// send
if (length <= maxLength + 1) {
chat.send(text, name);
$(this).val("");
} else {
$(this).val(text.substring(0, maxLength));
}
}
});
HTML
<form id="send-message-area">
<p style="text-align:center">Your message: </p>
<input id="sendie" maxlength = '100' />
</form>
<ol id="tags">
</ol>
But, what I'm also wanting to do is check if the input value contains phrases from the array so I can ban phrases that are too sensitive for children. How can I add this in, or is there another more efficient way to check the input?
UPDATE
I have already tried to place the phrase directly into the banned_words (I changed them as this post would get flagged for inappropriate language) and using the hexadecimal character for the space-bar. None of these worked.
You can try either of the following since the space is also a known charachter:
test 1:
Just put your phrase between quotes such as 'cry baby','red apple' etc.
sometimes it does not work, you can try
test 2:
replace the space with the hexidecimal character \x20 such as 'cry\x20baby','red\x20apple'
I hope one or both of these works for you.
I have done some more research and have found a cool plugin for JQuery. It's called jQuery.profanityFilter. It uses a json file filled with sensative words.
Link to github download: https://github.com/ChaseFlorell/jQuery.ProfanityFilter
I have a list of products, each individual product has a checkbox value with the products id e.g. "321". When the products checkbox is checked (can be more than 1 selected) i require the value to be collected. Each product will also have a input text field for defining the Qty e.g "23" and i also require this Qty value to be collected. The Qty text input should only be collected if the checkbox is checked and the qty text value is greater than 1. The plan is to collect all these objects, put them in to a loop and finally turn them in to a string where i can then display the results.
So far i have managed to collect the checkbox values and put these into a string but i'm not sure how to collect the additional text Qty input values without breaking it. My understanding is that document.getElementsByTagName('input') is capable of collecting both input types as its basically looking for input tags, so i just need to work out how to collect and loop through both the checkboxes and the text inputs.
It was suggested that i use 2 if statements to accomplish this but i'm new to learning javascript so i'm not entirely sure how to go about it. I did try adding the if statement directly below the first (like you would in php) but this just seemed to break it completely so i assume that is wrong.
Here is my working code so far that collects the checkbox values and puts them in a string. If you select the checkbox and press the button the values are returned as a string. Please note nothing is currently appended to qty= because i dont know how to collect and loop the text input (this is what i need help with).
How can i collect the additional qty input value and append this number to qty=
// function will loop through all input tags and create
// url string from checked checkboxes
function checkbox_test() {
var counter = 0, // counter for checked checkboxes
i = 0, // loop variable
url = '/urlcheckout/add?product=', // final url string
// get a collection of objects with the specified 'input' TAGNAME
input_obj = document.getElementsByTagName('input');
// loop through all collected objects
for (i = 0; i < input_obj.length; i++) {
// if input object is checkbox and checkbox is checked then ...
if (input_obj[i].type === 'checkbox' && input_obj[i].checked) {
// ... increase counter and concatenate checkbox value to the url string
counter++;
url = url + input_obj[i].value + '&qty=' + '|';
}
}
// display url string or message if there is no checked checkboxes
if (counter > 0) {
// remove first "&" from the generated url string
url = url.substr(1);
// display final url string
alert(url);
}
else {
alert('There is no checked checkbox');
}
}
<ul>
<li>
<form>
<input type="checkbox" id="checked-product" name="checked-product" value="311">Add To Cart
<div class="quantity">
<input type="text" name="qty" id="qty" maxlength="12" value="1" class="input-text qty"/>
</div>
</form>
</li>
<li>
<form>
<input type="checkbox" id="checked-product" name="checked-product" value="321">Add To Cart
<div class="quantity">
<input type="text" name="qty" id="qty" maxlength="12" value="10" class="input-text qty"/>
</div>
</form>
</li>
<li>
<form>
<input type="checkbox" id="checked-product" name="checked-product" value="98">Add To Cart
<div class="quantity">
<input type="text" name="qty" id="qty" maxlength="12" value="5" class="input-text qty"/>
</div>
</form>
</li>
</ul>
<button type="button" onclick="javascript:checkbox_test()">Add selected to cart</button>
My answer has two parts: Part 1 is a fairly direct answer to your question, and Part 2 is a recommendation for a better way to do this that's maybe more robust and reliable.
Part 1 - Fairly Direct Answer
Instead of a second if to check for the text inputs, you can use a switch, like so:
var boxWasChecked = false;
// loop through all collected objects
for (i = 0; i < input_obj.length; i++) {
// if input object is checkbox and checkbox is checked then ...
switch(input_obj[i].type) {
case 'checkbox':
if (input_obj[i].checked) {
// ... increase counter and concatenate checkbox value to the url string
counter++;
boxWasChecked = true;
url = url + input_obj[i].value + ',qty=';
} else {
boxWasChecked = false;
}
break;
case 'text':
if (boxWasChecked) {
url = url + input_obj[i].value + '|';
boxWasChecked = false;
}
break;
}
}
Here's a fiddle showing it working that way.
Note that I added variable boxWasChecked so you know whether a Qty textbox's corresponding checkbox has been checked.
Also, I wasn't sure exactly how you wanted the final query string formatted, so I set it up as one parameter named product whose value is a pipe- and comma-separated string that you can parse to extract the values. So the url will look like this:
urlcheckout/add?product=321,qty=10|98,qty=5
That seemed better than having a bunch of parameters with the same names, although you can tweak the string building code as you see fit, obviously.
Part 2 - Recommendation for Better Way
All of that isn't a great way to do this, though, as it's highly dependent on the element positions in the DOM, so adding elements or moving them around could break things. A more robust way would be to establish a definitive link between each checkbox and its corresponding Qty textbox--for example, adding an attribute like data-product-id to each Qty textbox and setting its value to the corresponding checkbox's value.
Here's a fiddle showing that more robust way.
You'll see in there that I used getElementsByName() rather than getElementsByTagName(), using the name attributes that you had already included on the inputs:
checkboxes = document.getElementsByName('checked-product'),
qtyBoxes = document.getElementsByName('qty'),
First, I gather the checkboxes and use an object to keep track of which ones have been checked:
var checkedBoxes = {};
// loop through the checkboxes and find the checked ones
for (i = 0; i < checkboxes.length; i++) {
if (checkboxes[i].checked) {
counter++;
checkedBoxes[checkboxes[i].value] = 1; // update later w/ real qty
}
}
Then I gather the Qty textboxes and, using the value of each one's data-product-id attribute (which I had to add to the markup), determine if its checkbox is checked:
// now get the entered Qtys for each checked box
for (i = 0; i < qtyBoxes.length; i++) {
pid = qtyBoxes[i].getAttribute('data-product-id');
if (checkedBoxes.hasOwnProperty(pid)) {
checkedBoxes[pid] = qtyBoxes[i].value;
}
}
Finally, I build the url using the checkedBoxes object:
// now build our url
Object.keys(checkedBoxes).forEach(function(k) {
url += [
k,
',qty=',
checkedBoxes[k],
'|'
].join('');
});
(Note that this way does not preserve the order of the items, though, so if your query string needs to list the items in the order in which they're displayed on the page, you'll need to use an array rather than an object.)
There are lots of ways to achieve what you're trying to do. Your original way will work, but hopefully this alternative way gives you an idea of how you might be able to achieve it more cleanly and reliably.
Check the below simplified version.
document.querySelector("#submitOrder").addEventListener('click', function(){
var checkStatus = document.querySelectorAll('#basket li'),
urls = [];
Array.prototype.forEach.call(checkStatus, function(item){
var details = item.childNodes,
urlTemplate = '/urlcheckout/add?product=',
url = urlTemplate += details[0].value + '&qty=' + details[1].value;
urls.push(url)
});
console.log(urls);
})
ul{ margin:0; padding:0}
<ul id="basket">
<li class="products"><input type="checkbox" value = "311" name="item"><input type="text"></li>
<li><input type="checkbox" value = "312" name="item"><input type="text"></li>
<li><input type="checkbox" value = "313" name="item"><input type="text"></li>
</ul>
<button id="submitOrder">Submit</button>
I'm making a meal planning / grocery list application with JavaScript and jQuery. Basically, this is how it works:
The user adds recipes through a form. The user enters the name of the recipe as well as the ingredients associated with that recipe.
When submitted, each recipe is stored in a <dl id="recipeList"> element. The name of the recipe is stored as a <dt class="recipe"> and each ingredient is stored as a <dd class="ingredient">.
For each day of the week, the user may click on a "Plan a Meal" anchor. This brings up a copy of the #recipeList. When the user clicks on a <dt>, a class="meal" is applied to it and the rest of the list is removed.
The next step is for the user to click on the "Generate Grocery List" anchor. When the user does this, JavaScript should loop through each .meal and create an array, #mealsArray. JavaScript should then loop through each class="recipe" and check to see if the .innerHTML of it matches an item in the #mealsArray. It does this just fine, but the problem is after a match is found, it should get the children of the class="recipe" (i.e., the <dt class="ingredient">) and push them into #groceriesArray.
JavaScript will not find the children of the <dt class="recipe">. I have tried numerous ways of coding this, such as:
this.children
this.childNodes
this.children()
this.children("dt")
this.children(".ingredient")
this.contents()
this.find(".ingredient")
It usually finds something strange like [Object HTMLElement] or returns an error message like Type Error: this.children() is not a function.
It seems like this so be so simple, but I have no idea what to do. I will provide my code below — apologies for how sloppy it is.
Here is the HTML:
<form id="addRecipeForm">
<label>Name</label><input type="text" id="recipeName">
<label>Ingredients</label><input type="text" class="recipeIngredients">
<label>Ingredients</label><input type="text" class="recipeIngredients">
<label>Ingredients</label><input type="text" class="recipeIngredients">
<button id="recipeButton">Add Recipe</button>
</form>
<dl id="recipeList"></dl>
<div>
<h3>Sunday</h3>
Plan a Meal
</div>
<div>
<h3>Monday</h3>
Plan a Meal
</div>
<!-- And so on, until Saturday -->
Generate Grocery List
<ul id="groceryList"></ul>
Here is the JavaScript:
var recipeList = $("#recipeList");
var recipeIngredients = $(".recipeIngredients");
var planAnchor = $(".planAnchor");
var groceryListAnchor = $("#groceryListAnchor");
var groceryList = $("#groceryList");
////////// ADD A RECIPE //////////
$("#recipeButton").click(function(e) {
e.preventDefault();
var recipeName = $("#recipeName").val();
var recipeIngredients = $(".recipeIngredients");
recipeList.append("<dt class='recipe'></dt>");
recipeList.children("dt").last().text(recipeName);
for (i = 0; i < recipeIngredients.length ; i++) {
$("<dd class='ingredient'></dd>").text(recipeIngredients[i].value).appendTo(recipeList);
};
});
////////// PLAN A MEAL //////////
planAnchor.click(function(e) {
e.preventDefault();
var dayInPlanning = $(this).parent("div");
var availableRecipes = recipeList.clone();
availableRecipes.children("dd").remove();
availableRecipes.attr("id", "availableRecipes");
$(this).parent("div").append(availableRecipes);
$(this).remove();
availableRecipes.children("dt").click(function(e) {
e.preventDefault();
var selectedRecipe = $(this);
var para = $("<p class='meal'></p>");
para.appendTo(dayInPlanning);
para.text(selectedRecipe.text());
availableRecipes.remove();
});
////////// GENERATE GROCERY LIST //////////
///////// THIS IS WHERE THE PROBLEM LIES //////////
groceryListAnchor.click(function(e) {
e.preventDefault();
var mealsArray = [];
var groceriesArray = [];
// Create an array of .meal elements
$(".meal").each(function() {
mealsArray.push(this.innerHTML);
});
console.log("mealsArray is " + mealsArray);
$(".recipe").each(function() {
console.log("Checking " + this.innerHTML);
// Match the innerHTML of each .recipe to the items in the mealsArray
if ($.inArray(this.innerHTML, mealsArray) > -1) {
console.log("We found " + this.innerHTML + " in the array!");
// Get the children of that recipe, and place them in groceriesArray
// *** Not Working ***
groceriesArray.push(this.children.innerHTML)
} else {};
});
console.log("The grocery list is " + groceriesArray);
});
To explain this simply. They're two types of elements jQuery Elements and JavaScript Elements. this is a JavaScript element. jQuery functions only work with jQuery Elements. So to make it work, use:
$(this).myjQueryFunction();
so for you:
$(this).children();
In depth
When creating jQuery elements using $(), it does a few things. jQuery uses Sizzle for selecting elements. If what's passed into $() is already an element. It doesn't do anything. Of it is, it will turn it into an element. Depending on which of the two jQuery uses. It will return an element. This is a regular JavaScript element but what makes it so special? The jQuery functions can only be run after $. The reason is how you create chained-JavaScript functions using prototype:
//Kind of how it's created
$.prototype.children = function () {
//jQuery's code to get children
}
This is making it so children() can only be run off of $.
Can you try cast this Dom Element as a jQuery Element:
//so instead of this.children() use
$(this).children()
and in this case if you want HTML it will be
$(this).children().html()
but it will get you first child HTML only, you can try the followng to get for all:
html_contents = ""
$.each($(this).children(), function(){
html_contents+=$(this).html();
});
This post was on the right track, but I need one step further; my input names potentially have non-sequential index values assigned to them.
Background: Instead of a long series of checkboxes, I have a routine that builds a list from selecting values in a dropbox. This helps reduce real estate on the screen. So as the user selects values from the drop down, the script tries to make sure the selection does not already exist, and if it does, don't add it a second time.
The list generated looks like this:
<div id="Access:search_div">
<ul class="options">
<li onclick="removeRoleOptions(this,'Access:search_div');"><input type="hidden" name="Access:search[7]" value="1" />Standard</li>
<li onclick="removeRoleOptions(this,'Access:search_div');"><input type="hidden" name="Access:search[8]" value="1" />Premium</li>
<li onclick="removeRoleOptions(this,'Access:search_div');"><input type="hidden" name="Access:search[10]" value="1" />Lifetime</li>
<li onclick="removeRoleOptions(this,'Access:search_div');"><input type="hidden" name="Access:search[14]" value="1" />SysOp</li>
</ul>
</div>
I see plenty of examples of how to find the value, but it's just a Boolean, so if it's in the list, it will always be 1. What I need is to search the name and see what index value is attached. So for the above code, I want to compare the value of the item selected from the drop down against 7, 8, 10, and 14.
Here is the important part of the code I have so far:
function addRoleOptions(select, variable, output) {
var display=document.getElementById(output);
var option = select.options[select.selectedIndex];
var ul = display.getElementsByTagName('ul')[0];
if (!ul) {
ul = document.createElement("ul");
ul.setAttribute('class', 'options');
display.innerHTML = '';
display.appendChild(ul);
}
var choices = ul.getElementsByTagName('input');
for (var i = 0; i < choices.length; i++) {
if (choices[i].value == option.value) {
return;
}
}
option.value holds the number I'm comparing against.
So my question is, how do I parse out the value within the [] of the name to compare against the value being sent?
I am not so sure about the requirement, but then you can try using regex to extract the index from the name.
(choices[i].name).match(/[0-9]+/g) will give you the value between the []
and then you can use that value to the operation you need to do
var s = "Access:search[6543]";
var num = s.match(/\d+/)
How to iterate over enumerated Check List (check boxes) using JQuery?
Hello there, I have the following check list (containing two check boxes which have two different e-mail addresses in them):
<div id="emailCheckListId" class="checkList">
<ul id="emailCheckListId_ul">
<li>
<label for="mycomponent.emailCheckList_0" class="checkListLabel">
<input type="checkbox"
value="johndoe1#example.com"
id="mycomponent.emailCheckList_0"
name="mycomponent.emailCheckList"/>
johndoe1#example.com
</label>
</li>
<li>
<label for="mycomponent.emailCheckList_1" class="checkListLabel">
<input type="checkbox"
value="johndoe2#example.com"
id="mycomponent.emailCheckList_1"
name="mycomponent.emailCheckList"/>
johndoe2#example.com
</label>
</li>
</ul>
Am able to use a JavaScript event listener to populate / remove from a text field, every time a user clicks on an individual check box using this:
// Event listener which picks individual contacts
// and populates input field.
$('#emailCheckListId_ul input:checkbox').change(function() {
// Declare array
var emails = [];
// Iterate through each array and put email addresses into array
$('#emailCheckListId_ul input:checkbox:checked').each(function() {
emails.push($(this).val());
});
// Assign variable as To: text field by obtaining element's id.
var textField = document.getElementById("mycomponent.textfield");
// Add / Remove array from text field
textField.value = emails;
});
However, I now have an enumerated check list... Just need to append / concatenate the index number (which I stored in an hidden field and can always obtain the
correct one), but can't seem to see how to pass in the second iterator's input:checkbox:checked.
Here's the HTML source of the checked list:
<div id="mycomponent.comment0.replyToRecipientsCheckList"
class="checkList"
onclick="selectIndividualRecipients()">
<ul id="mycomponentcomment0.replyToRecipientsCheckList_ul">
<li>
<label for="mycomponent.comment0.replyToRecipientsCheckList_0"
class="checkListLabel">
<input type="checkbox"
value="johndoe1#example.com"
id="mycomponent.comment0.replyToRecipientsCheckList_0"
name="mycomponent.comment0.replyToRecipientsCheckList"/>
johndoe1#example.com
</label>
</li>
<li>
<label for="mycomponent.comment0.replyToRecipientsCheckList_1"
class="checkListLabel">
<input type="checkbox"
value="johndoe2#example.com"
id="mycomponent.comment0.replyToRecipientsCheckList_1"
name="mycomponent.comment0.replyToRecipientsCheckList"/>
johndoe2#example.com
</label>
</li>
</ul>
</div>
JavaScript:
// Uses an event listener which picks individual contacts
// and populates input field.
function selectIndividualRecipients() {
var checkListPrefix = 'mycomponent.comment';
var index = document.getElementById("commentHiddenField").value;
var checkListPostfix = '.replyToRecipientsCheckList_ul';
var event = checkListPrefix + index + checkListPostfix;
$(event).change(function() {
// Declare array
var emails = [];
// Iterate through each array and put email addresses into array
// THIS DOESN'T SEEM TO BE WORKING:
var test = '#' + event.attr('id') + 'input:check:checked';
$(test).each(function() {
alert('inside iterator');
alert('this.val: ' + $(this).val());
emails.push($(this).val());
alert('emails = ' + emails);
});
// Assign variable to Reply To: text field by obtaining element's id.
var textField = document.getElementById(indexedReplyTextField);
// Add / Remove array from text field
textField.value = emails;
}
The browser says that ($test).each() throws an exception which is not caught and this is not allowed...
What am I possibly doing wrong?
Have you tried changing your var test declaration as follows?
var test = '#' + event.attr('id') + ' input:checkbox:checked';
Notice the space before input and checkbox instead of check.
There may be an easier method:
$('div.checkList').delegate('input', 'change', function() {
textField.value = $('div.checkList ul li input:checked').map(function() {
return $(this).val();
}).get().join('; ');
});