Student search project jquery / javascript - javascript

I am doing a project that requires me to add a search bar to a page that has a list of students names and email addresses and once the form is submitted only show students who have the characters typed in the search bar either on email address or student name.
So far I have the search bar appended and have started a function that listens for the click event on the button and adds the value from the input to a variable.
I thought I could do an if statement that checks if the list item contains the input variable I created and just add a class that I can then do another if statement later to hide or show based on what class it contains.
$(document).ready(function() {
//set number of students to show on each page
var inputValue;
var showStudents = 10;
//append search bar to the page
$(".page-header").append('<div class="student-search"><input placeholder="Search for students..."><button>Search</button></div>');
//add pagination to the page
$(".page").append('<div class="pagination"><ul></ul></div>');
//make page display 10 students at a time
//make search input only show students that contain that letter.
//use contains to add an ID?/class? to the student list item that matches the value in the input field.
//display the students that have said ID/class and hide the others.
$("button").click(function() {
//store the value of the input search into a variable
inputValue = $("input").val();
console.log(inputValue);
//filter the list items by the input value and add CSS
if ('.student-details h3:contains(inputValue)') {
$('.student-details h3').addClass('showstudent')
}
});
});
Obviously my issue is that once I write this it adds the class to all .student-details h3 items, not just the ones that contain the inputValue, and I cannot use "this" because it just adds the class to the button. Is this the best way to code this? Should I just convert my students list to an array and have the value of the input search the array and return the results into a new array? I am sort of lost here! Thanks for any help.

You can try this approach:
$('.student-details h3').each(function() {
if ($(this).text() == inputValue) {
$(this).addClass('showstudent');
}
}

Related

How can I modify a list item after I created it with jQuery?

This is my todo list what I made.
(To make my code more readable I tried to comment. I hope it worked.)
If you try my demo, you can add li items with the "add" button. And the li items has 2 more buttons.
I want to create a modify button to users with can modifying their list items. I have no idea what I can to do for this with jQuery.
Second problem is that list buttons don't work perfectly well. Because if I use once a delete button it change the done button to delete an item. But if I dont use the delete button, the done button is working well.
I dont know why, maybe the same class name is the problem?
Here is my demo in JS Bin:https://jsbin.com/natiziqawa/edit?html,js,output
$(document).ready(function(){
$("#add").click(function(){
// Created list elements and their's buttons
var list_item =document.createElement("li");
var remove_button=document.createElement("button");
var done_button=document.createElement("button");
// append the buttons some string to caption buttons
$(remove_button).append("Delete");
$(done_button).append("Done");
// added class name the items to to distinguish them
$(list_item).addClass("item")
$(remove_button).addClass("delete");
$(done_button).addClass("done");
// filled the created items with the input values
var list_text =$("#input").val();
var time=$("#time").val();
// filled the list item with their's buttons and class names and input values
$(list_item).append(time," : ",list_text,done_button,remove_button);
// finally fill the ul with list items but first check out what is written in the input
if(input.value==""){
alert("Please enter an activity")
}
// If the input has some value can go
else{
$("ul").append(list_item);
// after clicked, clear the input field
$("#input").val("");
// list item's buttons
$(".done").click(function(){
$(list_item).click(function(){
$(this).css("color","white")
$(this).css("text-decoration","line-through")
});
});
$(".delete").click(function(){
$(list_item).click(function(){
$(this).remove()
});
});
}
});// main function close
}); // document ready close
The idea behind my solution is to use the contenteditable attribute for the added fields. To do this, you need to dynamically wrap the first two fields in an additional div, as shown here:
$(list_item).append('<div class="edit_item" contenteditable="true">'+time+'</div>'," : ",'<div class="edit_item" contenteditable="true">'+list_text+'</div>',done_button,remove_button);
You will need to replace this code with your existing one. For a better understanding, this code is located in the comment: "// filled the list item with their's buttons and class names and input values"
Also, you need to add this rule to the css to align the fields:
.edit_item {
display: inline-block;
}
And regarding the second question:
You had a targeting problem. You must refer to the current list_item using the closest() method.
For mark:
$(".done").click(function(){
$(this).closest(list_item).css("color","white")
$(this).closest(list_item).css("text-decoration","line-through");
});
For removing:
$(".delete").click(function(){
$(this).closest(list_item).remove();
});

Is there a way to automatticaly reload the page when an <option> from a <select> list is pressed?

In a webpage, I have a select HTML list from which the user can select an item and change its price. I put the select and, below, an input text box. Its default value needs to be the current price of the element, so the user can see it and change it. However, when I change the selected item in the dropdown menu, the input text box continues to show the last item's price. I think that by refreshing the page the moment the user clicks the option in the dropdown, this will be fixed, but I don't know how. I hope the doubt was clear enough please tell me if you don't understand something. I would appreciate all your help!!
I was waiting for you to show some code, but you didn't, so according to your problem you don't need to reload the page, you need to handle the events properly, that's all, so I made this example for you, I have already said that you can use location.reload and other stuff, but that was because then I haven't read the body of your question just yet and I was just answering according to the title of the question, anyway here is the example, I have added some comments to make it clear for you to understand the code
// an example of some products and the price of each one
var products = {"ring": 2.54, "watch": 4.99, "necklace": 3.21},
// get the `<select>` dom element
productsList = document.querySelector("#products-container select"),
// get the `<input type="text">` dom element
productPrice =document.querySelector("#products-container input");
// set the value of the price input to the first product's price
productPrice.value = Object.values(products)[0];
// loop over the products and create an option for each one
for(var product in products) {
productsList.innerHTML += `<option value="${product}">${product}</option>`;
}
// when the user chooses a product we show its price on the price input
productsList.onchange = function() {
productPrice.value = products[this.value];
}
// when the user changes the price of an element we save that into our object of elements
productPrice.onchange = function() {
products[productsList.value] = this.value;
}
<div id="products-container">
<select>
</select>
<input type="text">
</div>

How to limit user input in a datalist?

I'm trying to make a webpage that contains a list of flights which can be filtered by destination, origin, price, etc. To do this, I've put each flight into a div with its properties as its classes. For example, a flight with its destination as America, its departure time at 2:40pm, and a price of $300 would be notated as
<div class = flight America 240PM 300> *Insert descriptive text here* </div>
However, I realized that by doing it this way, a person would be able to filter the flights by placing "America" in the price input section, as there's no way to differentiate between the price class and the destination class. Thus, I wanted to know how to limit the user's input in each input section. I've been attempting to implement this using a datalist with freeform text still available so the user won't have to scroll down endlessly in order to the find the specific airline or destination they want to filter by, but this allows them to input entirely custom filters (as seen in https://jsfiddle.net/5mwo6agb/3/). How do I limit the user input to only the choices available in the datalist, while still allowing them to type in the textbox in order to filter their choices?
(Also, if the way I'm going about this is entirely wrong, feel free to inform me as I'm still a pretty big newbie to javascript and html).
Ciao, you could use onchange event on input to verify that the user insert a value that is contained in your options in this way:
<input type="text" list = "combo-airlines" id="airline" placeholder="Select an Airline" name = "airline" style = "font-size:20px;" onchange="get_data(this)"/>
Then the get_data function will be:
get_data = function(elem) {
var options = document.getElementById('combo-airlines').getElementsByTagName('option');
var optionVals = [],
i = 0;
for (i; i < options.length; i += 1) {
optionVals.push(options[i].value);
}
if (optionVals.indexOf(elem.value) > -1) {
console.log(elem.value);
}
else {
console.log("wrong answer")
}
}
Here your fiddle modified.

Populating two separate input fields with unique text values passed in by multiple buttons using javascript

Working on a small personal project with jQuery and JavaScript. This is a one page app on a static website.
The game (if you can call it that) asks the user to select 2 characters from the selection area and pressing enter transfers the input to the "battle-area" where when you hit the "fight" button random numbers are subtracted form the characters hitpoints as attack dmg.
I am stuck on the selection part. I need two separate input fields populated with unique names. I am able to write text into the field and transfer it but I want the input fields to be populated by clicking on the individual pictures on the screen. My code seems to populate both fields at once. I can hardcode two buttons to each populate one input field, the problem is that I have about 15 image buttons and I need to be able to click either of those to populate the fields.
function selectFighter(name) {
var x = name;
var input = $('#fighter1_name').val();
$('#fighter1_name').val(x);
if ($('#fighter1_name').val() != "") {
$('#fighter2_name').val(x);
}
}
I have tried to add a condition that checks the first input field for a value and if it is NOT empty, to instead write the input into the second field. But that is causing one button click to populate both fields. I need one button click to populate one field, and then when I click another button to populate the other, empty field.
I am passing in a name with an onclick event: onclick="selectFighter('bob');"
Problem is when I click the image, both fields are populated with the same name. I want to be able to click an image to populate one input field, and then click a different image and put that name in the input field.
This should do the trick. We're checking if the first field has a value - if so, we populate the second one - otherwise the first one.
function selectFighter(name) {
if ($('#fighter1_name').val()) {
$('#fighter2_name').val(name);
} else {
$('#fighter1_name').val(name);
}
}
Add a class to the elements you click, and an ID, and remove all inline javascript.
Then add a script tag with the event handler targeting the elements
$('.toBeClicked').on('click', function() {
var x = $(this).data('name'); // note that "name" is not a good name for a variable
var f1 = $('#fighter1_name');
var f2 = $('#fighter2_name');
f1.val() === "" ? f1.val(x) : f2.val(x);
});
$('#clear').on('click', function() { $('input[id^=fighter]').val("") })
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button class="toBeClicked" data-name="bob">Bob</button>
<button class="toBeClicked" data-name="jon">Jon</button>
<button class="toBeClicked" data-name="ann">Ann</button>
<br><br>
Fighter 1 <input id="fighter1_name"><br>
Fighter 2 <input id="fighter2_name">
<br><br>
<button id="clear">Clear</button>

How to pass a list of object to childwindow

I am working on a Struts 2 application .I have a JSP page in which i am iterating the object- list in a table with least information from the object, in each row i have a checkbox, by checking the checkbox and clicking on a print button i need to print all the information of that selected rows.
so i called a java script function with respect to the print button and collected all the unique ids associated with the rows and set it to a hidden field, then i opened a popup child window like: window.open("/../../printInfo.jsp","Browse",...).
in the child window i got the hidden field value using opener.document.getElementById(...)
but i am not getting the object list which i need to iterate in the child window with all its information(selected rows only). is there any way to get all the object list in the popup window without calling the action in the window.open() method.
or is there any other way to accomplish the task quickly.
any help/code/suggestion/comment will appreciated.
Thanks.
the java script code: not answer just code snipt-
function printAll(){
var checkBoxLength = document.getElementsByName('ids');
var checkedIds = "";
for(var i = 0;i<checkBoxLength.length;i++){
if(checkBoxLength[i].checked){
checkedIds += i+",";
}
}
//all the selected checkboxe ids
checkedIds = checkedIds.substring(0,checkedIds.length-1);
if(checkedIds.length <=0){
alert("Please select atleast one row to print.");
return false;
}
//value set to hidden field so that it can access to popup window
document.getElementById("checkedIdField").value = checkedIds;
//trying to assign a list to hidden field but getting error
document.getElementById("medicationList").value = <s:property value="medicalRecordClient.patientMedicationEntries"/>;
childWindow = window.open("/cascade/pages/jsp/medicalrecord/print_medication_detail.jsp","Browse","left=200,top=200,width=700,height=530,toolbar=0,resizable=0");
}

Categories