How to limit user input in a datalist? - javascript

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.

Related

How to get input text value and push it into array in jQuery?

I have a checkbox function that when user checked on one of the specified value it will display an input text that will ask user to input a number and there will be another input text based on the number that user has put.
This is the example output
if user enter 2, there will be 2 input text will appear.
Now I have problem with pushing the tier name into my temp array. Below is what I have tried. But I'm still not getting any value inside my temp.
< script >
let temp = [];
$(document).ready(function() {
$("#staff_tier").change(function() {
let m = $(this).val();
$('#tier').html('');
var tier_num = 1;
for (var i = 0; i < parseInt(m); i++) {
$('#tier').append(`<label><b><span style="color:#e60000;">*</span><i> Tier (${tier_num++})</i></b></label><br>
<div class="input-group-prepend">
<input class="from-control" type="text" placeholder="" id="tier_name" required >
</div>
`);
temp.push($('#tier_name').val());
}
console.log(temp);
});
}); <
/script>
What I'm trying to achieve is I want the input value got push into my temp. How do I fix this problem ?
There are a few things that you got wrong:
You're having a loop, but you always print an input field with the same id: <input id="tier_name">
You listen for a change on #staff_tier, but then you simply print some html code that is static. You need (after fixing #1) to add pieces (input fields), that also have listeners so that when they change - you get their value
After having separate inputs with listeners, you can have a global place where you store their values.
At this point, it would be much easier of you add any tiny reactive library (no need for React or anything huge). Search online, but any of the smaller ones would do the trick: Sinuous, Reef or even Preact.

Auto update form fields as completing

In my web app, when a user selects an item in a dropdown box, the next dropdown box is updated with conditional options. I have created a script to allow for templates of the fields, but the second dropdown box does not update to allow me to assign a value to it.
Example: www.mywebsite.com?template=newcust
In the header I have:
if (isset($_GET['template'])) {
$templ = $_GET['template'];
if ($templ == "newcust") {
$autoname = "New Customer";
$c1f = "city"; //"join_date"
$c1w = 1; //1=is equal to, 2=is not equal to, 3=is great than, 4=is less than
}
So in this example, 1 would load with "city", while 2 would need to display just the valid fields (is equal to, is not equal 2) and select "is equal to" by default. But if "join date" is put into $c1f, then all 4 options would need to be available.
When doing this manually it works fine, I'm trying to get this to auto-update the fields when the user selects to start off with a template.
I hope this gives enough background info. Let me know if I need to share anything else.
Thanks

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>

Student search project jquery / 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');
}
}

Removing an <option> from a <select> tag according to previously selected <option> tag? (POLL Example)for

I have 50 rows of data and i want users to give them points by 1 to 50. I put dropdown boxes near them with options 1/50. But all i want is when a user selects 15(for example) for a row, 15 will be deleted from all other select tags of other rows. I am not as good as you in JavaScript. How can i accomplish this?
Hi casablanca i couldnt make he script you sent work. I need it to work on just one select tag so i give select tag an ID and an ID for the form too. I edit the scripts getElementsByTagName with getElementsByTagID (select tag's ID) to effect only one select tag. But the function doesnt triggered?
This might not be a very good idea, because it is very difficult for the user to modify choices -- for example, if I want to give 15 to a different option, I need to change the old one to something else and then change the new one to 15. Also, once all points have been assigned, it's impossible to make any changes because all options are gone.
A better idea would be to let the user do whatever he/she wants and then validate the form in the end. You could do that like this:
function validate() {
var used = []; // This array stores already used options
var rows = document.getElementById('myForm').getElementsByTagName('select');
for (var i = 0; i < rows.length; i++) {
var points = rows[i].value;
if (used[points]) {
// This value was already used
alert('Please choose a different value.');
rows[i].focus();
return false;
} else {
// This value was not used before; mark it as used now
used[points] = true;
}
}
return true;
}
And call this function in the onsubmit handler of your form:
<form id="myForm" onsubmit="return validate();">
EDIT1: id -> class
give each option the class of the number it is
<option class="15">15</option>
<option class="16">16</option>
etc.
Then jquery can remove() an item by class
$('.15').remove();
obviously have to do an on change and get the value just set. "remove()" is nice in this instance because I believe it will yank every instance of that class.
EDIT3: upon further consideration the above method would be further complicated by the need to not remove the "selected" option. Not going to figure out the exact method but I think changing the class from "15" to "selected15" with a $(this).append() or something of the sort before calling the remove would get the job done fairly safely.
EDIT2:
As noted by casblanca below this is not an ideal user interface at all for this type of input. You may want to look into this: http://www.utdallas.edu/~jrb048000/ListReorder/
Allows user to drag and drop items in a list to reorder them. Much more natural.

Categories