Different output for blank input in search function - javascript

I've written a small function for a search bar. Currently if the input doesn't match anything in my array, the function returns the last object in said array (which i made to be empty). I want to change it so that if the input is blank, the function returns "No Result" or something like that. Any ideas why this code isn't working as intended?
let websitePages =
'{"website_pages":[' +
'{"name":"Hamza", "path":"/hamza/"},' +
'{"name":"Jakub", "path":"/jakub/"},' +
'{"name":"Kevin", "path":"/kevin/"},' +
'{"name":"Sreeja", "path":"/sreeja/"},' +
'{"name":"Tristan", "path":"/tristan/"},' +
'{"name":"Math", "path":"/math/"},' +
'{"name":"History", "path":"/history/"},' +
'{"name":"Science", "path":"/sci/"},' +
'{"name":"Literature", "path":"/lit/"},' +
'{"name":"Periodic Table", "path":"/periodictable/"},' +
'{"name":"API Collection", "path":"/api_collection/"},' +
'{"name":"CRUD", "path":"/crud/"},' +
'{"name":"Async CRUD", "path":"/crud_api/"},' +
'{"name":"Database Search", "path":"/crud/search/"},' +
'{"name":"Search (Database)", "path":"/crud/search/"},' +
'{"name":"", "path":"//"}]}'; // this object is empty in case the user inputs a blank, so that the previous result is removed and no link is returned
function SearchMain() {
list = JSON.parse(websitePages);
input = document.getElementById("SearchInput");
filter = input.value.toUpperCase(); // the user's input is changed to uppercase so that the search is not case-sensitive
for (i = 0; i < websitePages.length; i++) {
// this section goes through the items in my array and checks if the user's input is the same as any object name
if (
filter ===
list.website_pages[i].name.toUpperCase().substring(0, filter.length)
) {
//using substrings allows users to only input part of the page name instead of the whole thing
link = list.website_pages[i].path;
document.getElementById("searchResult").innerHTML =
list.website_pages[i].name;
document.getElementById("searchResult").href = link;
} else if (filter === null) {
document.getElementById("searchResult").innerHTML = "No Results";
document.getElementById("searchResult").href = "";
}
}
}

For loop condition should be i < list.website_pages.length, also you should handle two error scenarios. One is input is empty and the search didnot find any valid match. I have updated them in the below fiddle.
Working Fiddle
let websitePages = '{"website_pages":[' +
'{"name":"Hamza", "path":"/hamza/"},' +
'{"name":"Jakub", "path":"/jakub/"},' +
'{"name":"Kevin", "path":"/kevin/"},' +
'{"name":"Sreeja", "path":"/sreeja/"},' +
'{"name":"Tristan", "path":"/tristan/"},' +
'{"name":"Math", "path":"/math/"},' +
'{"name":"History", "path":"/history/"},' +
'{"name":"Science", "path":"/sci/"},' +
'{"name":"Literature", "path":"/lit/"},' +
'{"name":"Periodic Table", "path":"/periodictable/"},' +
'{"name":"API Collection", "path":"/api_collection/"},' +
'{"name":"CRUD", "path":"/crud/"},' +
'{"name":"Async CRUD", "path":"/crud_api/"},' +
'{"name":"Database Search", "path":"/crud/search/"},' +
'{"name":"Search (Database)", "path":"/crud/search/"},' +
'{"name":"", "path":"//"}]}'; // this object is empty in case the user inputs a blank, so that the previous result is removed and no link is returned
function SearchMain() {
list = JSON.parse(websitePages);
input = document.getElementById('SearchInput');
filter = input.value.toUpperCase(); // the user's input is changed to uppercase so that the search is not case-sensitive
let isFound = false;
for (i = 0; i < list.website_pages.length; i++) { // this section goes through the items in my array and checks if the user's input is the same as any object name
if (filter === list.website_pages[i].name.toUpperCase().substring(0, filter.length)) { //using substrings allows users to only input part of the page name instead of the whole thing
link = list.website_pages[i].path;
document.getElementById('searchResult').innerHTML = list.website_pages[i].name;
document.getElementById('searchResult').href = link;
isFound = true;
}
}
if (!filter || !isFound) {
document.getElementById('searchResult').innerHTML = "No Results"
document.getElementById('searchResult').href = ""
}
}
<input type="text" id="SearchInput" />
<button onclick="SearchMain()">SearchMain</button>
<a id="searchResult"></a>
Simplified solution.
Avoid using for loop and make use of Array.find to find the matching node from the list.
Working Fiddle
let websitePages = '{"website_pages":[' +
'{"name":"Hamza", "path":"/hamza/"},' +
'{"name":"Jakub", "path":"/jakub/"},' +
'{"name":"Kevin", "path":"/kevin/"},' +
'{"name":"Sreeja", "path":"/sreeja/"},' +
'{"name":"Tristan", "path":"/tristan/"},' +
'{"name":"Math", "path":"/math/"},' +
'{"name":"History", "path":"/history/"},' +
'{"name":"Science", "path":"/sci/"},' +
'{"name":"Literature", "path":"/lit/"},' +
'{"name":"Periodic Table", "path":"/periodictable/"},' +
'{"name":"API Collection", "path":"/api_collection/"},' +
'{"name":"CRUD", "path":"/crud/"},' +
'{"name":"Async CRUD", "path":"/crud_api/"},' +
'{"name":"Database Search", "path":"/crud/search/"},' +
'{"name":"Search (Database)", "path":"/crud/search/"},' +
'{"name":"", "path":"//"}]}'; // this object is empty in case the user inputs a blank, so that the previous result is removed and no link is returned
function SearchMain() {
list = JSON.parse(websitePages);
input = document.getElementById('SearchInput');
filter = input.value.toUpperCase(); // the user's input is changed to uppercase so that the search is not case-sensitive
const matchingNode = filter ? list.website_pages.find(node => filter === node.name.toUpperCase().substring(0, filter.length)) : null;
if (matchingNode) {
document.getElementById('searchResult').innerHTML = matchingNode.name;
document.getElementById('searchResult').href = matchingNode.path;
}
else {
document.getElementById('searchResult').innerHTML = "No Results"
document.getElementById('searchResult').href = ""
}
}
<input type="text" id="SearchInput" />
<button onclick="SearchMain()">SearchMain</button>
<a id="searchResult"></a>

Related

In JavaScript, once the user submit a value, how do I keep input value printed?

I am trying to accomplish the following tasks shown in the image attached.
As you can see, there are 5 submissions, how can I accomplish to keep all 5 submissions printed on the page? So far, I can only keep 1 submission, but as soon as I submit another one, it replaces it.
This is my code.
var i = ",";
var listItem = " ";
var count = 0;
document.getElementById("sButton").addEventListener("click", processInput, false);
function processInput() {
if (listItem = document.getElementById("inputText").value) {
var inputValue = document.getElementById("inputText").value;
document.getElementById("label").innerHTML = inputValue + ",";
}
else {
(document.getElementById("label").innerHTML = " ");
}
if (count++ == 4) {
document.getElementById("message").innerHTML = "Gracias por sus
sugerencias."
}
}```
[Here, right below the textbox, it's showing 5 items/inputs that were submitted. How do I keep those and not lose them when another input is submitted?][1][1]: https://i.stack.imgur.com/4zRuT.png
You need the keep the existing value by concatenating with previous. Don't write it to innerHTML but concat it with previous value. Please override following code snippit.
if (listItem = document.getElementById("inputText").value) {
var inputValue = document.getElementById("inputText").value;
document.getElementById("label").innerHTML += inputValue + ",";
} else {
(document.getElementById("label").innerHTML = "");
}
if (count++ == 4) {
document.getElementById("message").innerHTML = "Gracias por sus
sugerencias.
"
}
Track the values in an array, separate from the HTML. When an item is added, push it into the values array and then update the displayed text:
// the text input
const input = document.querySelector('input');
// an array to keep track of the values
const values = [];
// form submission handler that pushes the new value into the values array
function handleSubmit(e) {
// prevent actual form submission
e.stopPropagation();
e.preventDefault();
// append the new value
if (input.value.trim().length) {
values.push( input.value );
}
// reset the input
input.value = '';
// update the display
updateDisplay(values);
}
// update the display from the given values
function updateDisplay (values) {
// find the container for the display list
const list = document.getElementById('list');
// render the new text
list.innerText = values.join(', ');
const count = document.getElementById('count');
count.innerText = values.length > 4
? 'Gracias por sus sugerencias.'
: `You have ${values.length} values!`;
}
<div id="list">
</div>
<form onsubmit="handleSubmit(event)">
<input />
<button>Add a value</button>
</form>
<div id="count"></div>

JQuery ID + count

When I dynamically create checkbox and div, I want to have different id for each of them (like id_1, id_2...).
The first value of my array is erased by the next value.
Currently, I create checkbox for each value I have in my array:
var containerCheckbox = $('#listCheckboxCategories');
// var listCheckboxCategories = $('#listCheckboxCategories');
var CheckboxCreate = '<input id="catCheckbox" type="checkbox" name="categoriesCheckbox" required/>';
var categoriesName = '<span id="catName"/>';
if (tileConfig.isThereFilterRadios == "Yes" && res !== undefined) {
$('#ShowCategories').show();
$('#containerCategories').show();
$.each(res.list, function(index, cat) {
//ToDo: inserer cat.name dans le span
// categoriesName.html(cat.name)
containerCheckbox.append(CheckboxCreate, categoriesName);
$("#catName").html(cat.name);
});
}
Can someone help me ?
You could create a function to return the checkbox element, that way you could pass a variable into the function (eg index) to add to the html to make each id unique
for example
createCheckbox = function (index) {
return '<input id="catCheckbox_' + index + '" type="checkbox" name="categoriesCheckbox" required/>';
}
var containerCheckbox = $('#listCheckboxCategories');
var categoriesName = '<span id="catName"/>';
if (tileConfig.isThereFilterRadios == "Yes" && res !== undefined) {
$('#ShowCategories').show();
$('#containerCategories').show();
$.each(res.list, function(index, cat) {
containerCheckbox.append(createCheckbox(index), categoriesName);
$("#catName").html(cat.name);
});
}

check if word already exists in the array [duplicate]

This question already has answers here:
Check if string inside an array javascript
(2 answers)
Closed 5 years ago.
I'm trying to check if the inputted word is already inside of my array. SO for example, if someone enters 'cat' more than once an error message will display saying "cat has already been entered". I've tried a few different combinations of code but nothing I do seems to work. The findword function is what I have so far. Can someone take a look at my code and explain why its not working and provide a possible fix.
On another note, why doesn't the "word: empty" message pop up when the input field has been left blank?.
<body>
<input type="text" id=input></input>
<button onclick="addword()" class="button" type = "button">Add word</button><br><br>
<button onclick="start()" class="button" type = "button">Process word</button><br><br>
<p id="ErrorOutput"></p>
<p id="output"></p>
<p id="nameExists"></p>
</body>
.
var array = [];
return = document.getElementById("input").value;
function start() {
var word = "word List";
var i = array.length
if (word.trim() === "") {
word = "word: Empty"
}
document.getElementById('ErrorOutput').innerHTML = word
while (i--) {
document.getElementById('output').innerHTML = array[i] + "<br/>" + document.getElementById('output').innerHTML;
}
var longestWord = {
longword: '',len: 0};
array.forEach(w => {
if (longestWord.len < w.length) {
longestWord.text = w;
longestWord.len = w.length;
}
});
document.getElementById('ErrorOutput').innerHTML = "The longest name in the array is " + longestWord.len + " characters";
}
function addword() {
return = document.getElementById('input').value;
array.push(return);
}
function findword() {
var nameExists = array.indexOf(
return) < 0 ?
'The number ' +
return +' does not exist in the array': 'The number ' +
return +' exists in the array'
document.getElementById('nameExists').textContent = nameExists
}
You can use array.indexOf(word) (command for your situation) to find the position of the word.
If the position is -1 the word is not inside the array.
More information on W3

Use an array in this function to display values of chechboxes checked

This function replicates the user experience of a Select/MultiSelect dropdown element - displaying the values of checkboxes checked in a container (adds/removes them when they're checked/unchecked), and if more than 3 items have been checked it displays the # selected instead of the values selected.
It's a combination of 2 functions and they're not playing well together when items are unchecked (i.e. it's removing the values but not the commas, doesn't work correctly when more than 3 items have been selected, etc.)
I think it would be much better if I used an array to store the values, adding/removing values from the array when items are checked/unchecked, and I know how do to in PHP but not in Javascript. This code should create the array, but I can't figure out how to integrate it into my code.
$('input:checkbox[name="color[]"]:checked').each(function () {
selectedColors.push($(this).val());
});
Existing Code:
JS
$(".dropdown_container ul li").click(function () {
var text = $(this.children[0]).find("input").val();
var text_edited = text.replace(/_/g, " ");
var currentHtml = $(".dropdown_box span").html();
var positionLocation = currentHtml.indexOf(text_edited);
var numberChecked = $('input[name="color[]"]:checked').length;
if (positionLocation < 1) {
if (numberChecked <= 3) {
$(".dropdown_box span").html(currentHtml.replace('Colors', ''));
$(".dropdown_box span").append(', ' + text_edited);
} else {
$(".dropdown_box span").html(currentHtml.replace(currentHtml, numberChecked + " Selected"));
}
} else {
(currentHtmlRevised = currentHtml.replace(text_edited, ""));
$(".dropdown_box span").html(currentHtmlRevised.replace(currentHtml));
}
});
HTML
<div class="dropdown_box"><span>Colors</span></div>
<div class="dropdown_container">
<ul id="select_colors">
<li>
<label><a href="#"><div style="background-color: #ff8c00" class="color" onclick="toggle_colorbox_alt(this);"><div class=CheckMark>✓</div>
<input type="checkbox" name="color[]" value="Black" class="cbx"/>
</div>Black</a></label>
</li>
<!-- More List Items --!>
</ul>
</div>
Easiest to just replace the entire content each time. Also use the change event instead of the click event.
$(".dropdown_container input").change(function () {
var checked = $(".dropdown_container input:checked");
var span = $(".dropdown_box span");
if (checked.length > 3) {
span.html("" + checked.length + " selected");
}
else {
span.html(checked.map(function () { return $(this).val().replace("_"," "); }).get().join(", "));
}
});
Example: http://jsfiddle.net/bman654/FCVjj/
try this:
$('.cbx').change(function(){
var cbx = $('.cbx:checked');
var str = '';
if (cbx.length<=3 && cbx.length!=0){
for (var i=0;i<cbx.length;i++){
if (i>0) str += ', ';
str += cbx[i].value;
}
} else if (cbx.length==0){
str = 'Colors';
} else {
str = cbx.length;
}
$('.dropdown_box span').html(str);
});

Check if Number entered is correct By ID - JavaScript

Would like to know how to check true and false and in return give error message if checked and the number is incorrect..
<input name="student1" type="text" size="1" id="studentgrade1"/>
<input name="student2" type="text" size="1" id="studentgrade2"/>
<input name="student3" type="text" size="1" id="studentgrade3"/>
so here we have 3 inputbox , now i would like to check the result by entering number into those inputbox.
studentgrade1 = 78
studentgrade2 = 49
studentgrade3 = 90
<< Using JavaScript >>
So If User entered wrong number e.g "4" into inputbox of (studentgrade1) display error..
same for otherinputbox and if entered correct number display message and says.. correct.
http://jsfiddle.net/JxfcH/5/
OK your question is kinda unclear but i am assuming u want to show error
if the input to the text-box is not equal to some prerequisite value.
here is the modified checkGrade function
function checkgrade() {
var stud1 = document.getElementById("studentgrade1");
VAR errText = "";
if (stud1.exists() && (parseInt(stud1.value) == 78){return true;}
else{errText += "stud1 error";}
//do similiar processing for stud2 and stud 3.
alert(errText);
}
See demo →
I think this is what you're looking for, though I would recommend delimiting your "answer sheet" variable with commas and then using split(',') to make the array:
// answers
var result ="756789";
// turn result into array
var aResult = [];
for (var i = 0, il = result.length; i < il; i+=2) {
aResult.push(result[i]+result[i+1]);
}
function checkgrade() {
var tInput,
msg = '';
for (var i = 0, il = aResult.length; i < il; i++) {
tInput = document.getElementById('studentgrade'+(i+1));
msg += 'Grade ' + (i+1) + ' ' +
(tInput && tInput.value == aResult[i] ? '' : 'in') +
'correct!<br>';
}
document.getElementById('messageDiv').innerHTML = msg;
}
See demo →
Try this http://jsfiddle.net/JxfcH/11/
function checkgrade() {
var stud1 = document.getElementById("studentgrade1");
var stud2 = document.getElementById("studentgrade2");
var stud3 = document.getElementById("studentgrade3");
if (((parseInt(stud1.value) == 78)) && ((parseInt(stud2.value) == 49)) && ((parseInt(stud3.value) == 90)))
{
alert("correct");
}
else
{
alert("error correct those values");
}
}

Categories