I am trying to write a search fnction for an address book which loops through the array of contacts and shows them in a popup. It first worked fine finding and showing the found contacts. After adding the else statement, only "none found" runs. I've tried switching the order and negating the first statement, but that does not work.
$(document).ready(function(){
newSearch.click(function(){
const inputValue = $('#searchcontacts').val();
for(let i = 0; i < contactList.length; i++){
if(inputValue.toUpperCase() === contactList[i].firstName.toUpperCase()){
resultsContent.text(contactList[i].firstName +
" " + contactList[i].lastName +
" " + contactList[i].phoneNumber +
" " + contactList[i].addressText);
} else {
}
};
resultsContent.text('None found')
});
});
You have always set the resultsContent.text('None found') after for loop is executed.
So even if a contact found and that contact is set to the resultsContent, it will be replaced by the resultsContent.text('None found') line
Following code snippet will do the job for you. But I have seen another issue with this code that only the last found contact will be shown in the resultsContent element since you have not accumulated the found results. If you need to show all the contacts you need to accumulate all of them and show
newSearch.click(function(){
const inputValue = $('#searchcontacts').val();
var hasContacts = false;
for(let i = 0; i < contactList.length; i++){
if(inputValue.toUpperCase() === contactList[i].firstName.toUpperCase()){
resultsContent.text(contactList[i].firstName +
" " + contactList[i].lastName +
" " + contactList[i].phoneNumber +
" " + contactList[i].addressText);
hasContacts = true;
} else {
}
};
if( !hasContacts) {
resultsContent.text('None found');
}
});
Related
I am using an ecommerce system where I dont have access to HTML code or anything but I can add custom JS code to alter some things and CSS.
I need to edit the shipping info text which is right to Doba dodania text.
My issue is that the event fires only once and not on every select change event.
Can someone help me why it is firing only once? It was needed to add SetTimeOut too.
Please check the page and console logs here:
https://www.privlacuj.sk/Hacik-Offset-Light-Class-AT-21-cena-za-1ks-d2336_1013278452.htm
My code is:
<script type="text/javascript">
function change_doba_dodania() {
var c757_counter = document.querySelectorAll(".c757").length;
var variant = document.querySelectorAll(".c755.variant").length;
var out_of_stock = document.querySelectorAll(".c757.out-of-stock").length;
console.log(c757_counter);
console.log(variant);
console.log(out_of_stock);
if (out_of_stock > 0) {
console.log("Nincs raktaron");
}
if ( ( c757_counter >= 2 ) && ( out_of_stock == 0 ) ){
var dd_text = document.getElementsByClassName("c757")[1].innerHTML;
console.log(dd_text);
var dd_text_array = dd_text.split(" ");
var dd_final = dd_text_array.filter(String);
console.log(dd_final);
if (dd_final[2] == "zajtra") {
document.getElementsByClassName("c757")[1].innerHTML = dd_final[6] + " " + dd_final[7] + " " + dd_final[8] + " " + dd_final[9] + " " + dd_final[10] + " a Vaša zásielka bude expedovaná už " + dd_final[2];
} else {
document.getElementsByClassName("c757")[1].innerHTML = dd_final[6] + " " + dd_final[7] + " " + dd_final[8] + " - " + dd_final[9] + " a Vaša zásielka bude expedovaná už " + dd_final[2];
}
}
}
window.addEventListener('DOMContentLoaded', (event) => {
change_doba_dodania();
});
var variant = document.querySelectorAll(".c755.variant").length;
if (variant > 0){
document.querySelector('.c757 select').addEventListener('change', function()
{setTimeout(change_doba_dodania, 1500)});
document.querySelector('.c757 select').addEventListener('change',() =>
setTimeout(console.log, 1000, "Changed")
)
}
If i got your question, your problem is querySelector.
querySelector only selects the first element with the given class name. If you want to select all the elements with the given class name, you should use querySelectorAll.
document.querySelectorAll(".c757 select").forEach(select => {
select.addEventListener(...)
})
below is the js code for wikipedia search project. I am getting infinite for loop even though it had condition to stop repeating the loop. I am stuck in this problem.
$(document).ready(function() {
$('.enter').click(function() {
var srcv = $('#search').val(); //variable get the input value
//statement to check empty input
if (srcv == "") {
alert("enter something to search");
}
else {
$.getJSON('https://en.wikipedia.org/w/api.php?action=opensearch&search=' + srcv + '&format=json&limit=20&callback=?', function(json) {
$('.content').html("<p> <a href ='" + json[3][0] + "'target='_blank'>" + json[1][0] + "</a><br>" + json[2][0] + "</p>");
/*for loop to display the content of the json object*/
for (i = 1; i < 20; i++) {
$('p').append("<p><a href ='" + json[3][i] + "'target='_blank'>" + json[1][i] + "</a>" + json[2][i] + "</p>");
}
});
}
});
});
You are appending to each and every one of <p> in page.
Since your for loop appends even more <p> (and you possibly have a high number of <p> elements in your page beforehand) you overflow your call stack.
You probably wanted to append to a specific <p>. Try giving an id to your selector.
from what i can see in the url you need to do the following:
loop over the terms found and select the link based on the index of the element, chose a single element .contentto append the data not a set of elements p, this will increase the number of duplicated results
$.getJSON('https://en.wikipedia.org/w/api.php?action=opensearch&search='+srcv+'&format=json&limit=20&callback=?', function(json){
$.each(json[1],function(i,v){
$('.content').append("<p><a href ='"+json[2][i]+"'target='_blank'>"+json[0]+"</a>"+v+"</p>");
});
});
see demo: https://jsfiddle.net/x79zzp5a/
Try this
$(document).ready(function() {
$('.enter').click(function() {
var srcv = $('#search').val(); //variable get the input value
//statement to check empty input
if (srcv == "") {
alert("enter something to search");
}
else {
$.getJSON('https://en.wikipedia.org/w/api.php?action=opensearch&search=' + srcv + '&format=json&limit=20&callback=?', function(json) {
$('.content').html("<p> <a href ='" + json[3][0] + "'target='_blank'>" + json[1][0] + "</a><br>" + json[2][0] + "</p>");
/*for loop to display the content of the json object*/
var i = 1;
for (i; i < 20; i++) {
$('p').append("<p><a href ='" + json[3][i] + "'target='_blank'>" + json[1][i] + "</a>" + json[2][i] + "</p>");
}
});
}
});
});
net mvc application and I am trying to do some validation when someone clicks a button. Here is the code.
function productVerify() {
var intQty = $("#txtQty").val();
var strItemName = $("#item_Name").val();
var strItemDescription = $("#item_Description").val();
var intItemID = $("#item_ID").val();
var intItemPrice = $("#item_Price").val();
var strImgUrl = $("item_ImgUrl").val();
var intQty = $("#txtQty").val();
if (intQty < 1) {
alert("You cannot put an item quantity of 0 in your cart");
return false;
}
else {
//post into cart
alert(strItemName + " " + strItemDescription + " " + intItemID + " " + intItemPrice + " " + strImgUrl + " " + intQty + " " + "I got this far.....! good job")
}
}
this works in jsfiddle but for some reason it does not fully work in my mvc application. it does work on the first if because if I put a 0 in my text box I get the first alert, but nothing happens on the else inside my mvc application. This one part seems so easy, but it is killing me any help would be appreciated.
make sure you using a number in your if statement
//if !num
if (parseInt(intQty) == NaN) {
alert("Please enter a number");
return false;
} else {
//if < 1
if (parseInt(intQty) < 1) {
alert("You cannot put an item quantity of 0 in your cart");
return false;
//if >= 1
} else {
//do something
}
}
I am currently converting my friends website, as it's not "mobile friendly" by changing his current frontend into a bootstrap front end.
I've been working on a test site which is just a sub-domain on the same server.
This is the old website: http://bit.ly/1hurTNB
This is the new website: http://bit.ly/1hus0IV
But I've encountered a problem with the shopping cart page.
The shopping cart no longer recalculates its total when I press the recalculate button. It works fine on the old website. I dont know what I've changed to break it?
I've debugged the JavaScript using Chrome Dev Tools (F12) and line no 150 of order.php has this error:
Uncaught TypeError: Cannot read property 'value' of undefined
And this is the line of offending code:
if (document.forms[1].elements["qty" + count].value == "" ||
document.forms[1].elements["qty" + count].value == 0) {
document.forms[1].elements["qty" + count].value = 0;
showInCart = false;
}
I don't understand why I am getting this error? Googling around gives vague answers. Which is why I am here on StackOverflow.
BTW if you want to recreate my problem you'll need to:
go to the homepage
choose a product category from the grid of pictures e.g. "get costume ideas..."
add an item to the basket.
once the page posts to Order.php Change its Quantity.
click the recalculate button.
Why is the Javascript no longer picking up the values from the quantity fields???
Any help is greatly appreciated.
Here is the function in its entirety:
<script type="text/javascript">
function recalculateTotal(){
var lineTotal = 0;
var subTotal = 0;
var total = 0;
var hiddenStuff = "";
var count;
var i;
var orderURL="register.php?orderDetails=";
items = new Array(<?=$itemList?>);
for (i in items){
var cNum = 0;
var pNum = 0;
var qNum = 0;
count = items[i];
cNum = (count * 4) + 1;
var showInCart = true;
// the next line is broken!
if (document.forms[1].elements["qty" + count].value == "" || document.forms[1].elements["qty" + count].value == 0){
document.forms[1].elements["qty" + count].value = 0;
showInCart = false;
}
lineTotal = document.forms[1].elements["qty" + count].value * document.forms[1].elements["price" + count].value;
document.getElementById("lTotal" + count).innerHTML = formatCurrency(lineTotal);
subTotal += lineTotal;
if (hiddenStuff == ""){
hiddenStuff = hiddenStuff + showInCart + ":" + document.forms[1].elements["productId" + count].value + ':' + document.forms[1].elements["qty" + count].value;
}else{
hiddenStuff = hiddenStuff + ":" + showInCart + ":" + document.forms[1].elements["productId" + count].value + ':' + document.forms[1].elements["qty" + count].value;
}
}
document.getElementById("subTotal").innerHTML = formatCurrency(subTotal);
for (var j in delivery_prices){
if (subTotal >= delivery_prices[j].total_amount_start && subTotal <= delivery_prices[j].total_amount_end){
document.getElementById('delivery').innerHTML = delivery_prices[j].delivery_price;
total = subTotal + delivery_prices[j].delivery_price;
}
}
document.getElementById("total").innerHTML = formatCurrency(total);
document.forms[1].elements["orderDetails"].value = hiddenStuff;
orderURL = orderURL + hiddenStuff;
var myrequest = $.ajax({
url: orderURL,
type: "get",
});
myrequest.done(function (response){
updateBasket();
});
}
</script>
Thanks very much.
This error arises when the elements are not either declared or not loaded on the DOM. You can do these things to solve this problem :
1.Wrap every thing inside a function and attach it to the window.onload. Like this :
<script type = "text/javascript">
function foo(){
.....//Your JavaScript code here
}
window.onload = foo;
</script>
Check whether all the elements are present in the HTML page or not.
I am not sure that this is the problem, but I think its worth mentioning. Change the line no.150 to :
if (document.forms[0].elements["qty" + count].value == "" ||
document.forms[0].elements["qty" + count].value == 0) {
document.forms[0].elements["qty" + count].value = 0;
showInCart = false;
}
In the above code snippet I've changed the occurrence of 1 with 0. Because JavaScript starts counting from 0 not 1. So if you want to access the content of first form then use this point otherwise ignore this point.
You'll solve the problem changing
document.forms[1] into document.forms[0]
The problem is that the position of the form has changed. Put forms[0] and it will work.
Aitor
The problem is that document.forms[1] points to the form that has no qty0 element. Actually it points to your "search form". "Order form" has 0 index in the array provided by document.forms selection.
The form selection made with document.forms has ascending order. In resulted zero-based array, "0" index will point to first form, "1" index to second etc. On your old website, "search form" is rendered before "order form". That is why it works there, in its turn, on your new site the forms are switched so indexes should be changed too.
You already have a variable that you can use.
Replace :
if (document.forms[1].elements["qty" + count].value == "" ||
document.forms[1].elements["qty" + count].value == 0) {
document.forms[1].elements["qty" + count].value = 0;
showInCart = false;
}
By :
if (document.forms[1].elements["qty" + i].value == "" ||
document.forms[1].elements["qty" + i].value == 0) {
document.forms[1].elements["qty" + i].value = 0;
showInCart = false;
}
I have a bit of code that searches the current information shown on the page from a input source, which is an XML loaded in. This then shows how many times the word has been found, it should then display the lines where the word was found although currently it is showing all the lines. The code is
function searchResults(query) {
var temp = "\\b" + query + "\\b";
var regex_query = new RegExp(temp, "gi");
var currentLine;
var num_matching_lines = 0;
$("#mainOutput").empty();
$("LINE", g_playDOM).each(
function() {
currentLine = $(this).text();
matchesLine = currentLine.replace(regex_query,
'<span class="query_match">' + query + '</span>');
if (currentLine.search(regex_query) > 0)
num_matching_lines++;
$("#mainOutput").append("<p>" + matchesLine + "</p>");
});
$("#sideInfo").append(
"<p>Found " + query + " in " + num_matching_lines + " lines</p>");
}
$(document).ready(function() {
loadPlay();
$("#term_search").focus(function(event) {
$(this).val("");
});
$("#term_search").keypress(function(event) {
if (event.keyCode == 13)
searchResults($("#term_search").val());
});
$('#term-search-btn').click(function() {
searchResults($("#term_search").val());
});
});
</script>
Currently the number of lines the word is on is being shown correctly.
If you want a line of code to be executed within a conditional, then you need to place curly braces around it. Otherwise, only the very next action item will be executed. In your case, increase the count of the number of lines that match.
Your subsequent action item, appending the found line into the DOM is executed on every branch because the if statement has already done its job. Offending lines below:
if ( currentLine.search(regex_query) > 0 ) num_matching_lines++;
$("#mainOutput").append("<p>" + matchesLine + "</p>");
Fixed:
if ( currentLine.search(regex_query) > 0 ) {
num_matching_lines++;
$("#mainOutput").append("<p>" + matchesLine + "</p>");
}