Single Choice Dropdown - javascript

I am building a form to rank series of items. The user will read the item and select in a dropdown the rating from 1 to 20. All 20 items will be displayed at the same time. What is the best way to make sure that the user didn't select the same number for more than one choice? Then I would display an error message, "You've already ranked an item as number 5"
Thanks

Put the items in a list with options to move an element up or down in the list.

I would suggest something like the following function. You may want to add something to revert the selection to some default value if it is a duplicate.
function checkDupe(element) {
var dupe = false;
$("select").each(function() {
if ($(this).attr("id") != $(element).attr("id") && $(this).attr("value") == $(element).attr("value")) {
dupe = true;
alert("You have already ranked an item number " + $(element).attr("value"));
return;
}
});
return dupe;
}
Just add that to the onchange event for all the dropdown lists like this.
<select id="a1" onchange="checkDupe(this)">
It's important to note that each list must have a unique ID.

There is a jquery plug-in for validation, that can help you define rules. It only works on submit, though but it'll still wont send the form and tell you which entry is wrong. Take a look at it, may be it can help you.

Related

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 accumulate a score/value based on the choices selected on a form using jQuery

I wanna to try to researching around on how to achieve this but I am not sure about how to make the solution for this.
Basically I have a form that contains some select list, radio buttons, and checkboxes. Each option on the form has a corresponding numeric value that will be accumulated and displayed to the user when the form gets submitted.
What I am not sure about is how to be able to add or deduct a value if the user chooses to change the a choice on the form.
For example, when a user is on the first dropdown element, and they choose option 2 which has a value of 5 then the current accummulated value us 5. Then on question 2, they choose option 1 which has a value of 2 which makes the accummulated value 7. Then the user changes the answer for question one from option 2 to option one which means 5 will be deducted from the accumulated value and 2 will be added since it is the value for option 1 which changes the accumulated value to 4.
I know the description I mentioned might be all over the place but I hope it makes sense.
I am trying to use jQuery and so far, my approach would be to check if any of the form element's value has changed:
(function($) {
var score = 0;
$(".the-form #step-5 :input").change(function() {
console.log($(this).val());
});
})(jQuery);
But I can't seem to figure out how to get the previous value of the option that was selected if the user changes their answer.
Any suggestion would be appreciated.
Can you recalculate across the whole form each time the user changes any of the elements?
$(".the-form :input").change(calculateChanges);
function calculateChanges() {
// Retrieve the current values of all elements and add them together
}
When a user submits, then start doing the calculations or when a select is changed, i.e. attach it to the event. Score is now a local variable
function calcValue() {
var score = 0;
//select all the elements using example below
$(".the-form :input").each(function( index ) {
//i forgot jQuery exact syntax but $(this).val or //$(this).val()
score += $( this ).val();
});
console.log(score);
}
In this case you can attach it to the submit
function submit() {
var score = calcValue();
}
Or you can put it in a change event of a select
function selectChanged() {
var score = calcValue();
}

Disable toggle switch in Javascript

This script is designed to map the location between two cubicles so that people in large office buildings can figure out where they need to go to get to that other person. I've almost got it...
I have two different dropdown menus I'm working with.
By default, the dots on the page display.
Each dot corresponds to a name on the dropdown list.
When you select the name under the first dropdown, the other dot will disappear, and then if you select the name under the other dropdown, the first one disappears.
What I want to happen is - When both names are selected from the dropdowns, then both dots are showing at the same time.
I can get one or the other, but not both.
Here's the JS I have to toggle between the two...
$('#mapMe').change(function() {
var selectedMeChoice = $('#mapMe option:selected').val();
if (selectedMeChoice == 'ALL'){
$('a.dot').slideDown(1000);
}else{
$('a.dot[mechoice = "'+selectedMeChoice+'"]').slideDown(1000);
$('a.dot[mechoice != "'+selectedMeChoice+'"]').slideUp(1000);
}
});
$('#mapThem').change(function() {
var selectedThemChoice = $('#mapThem option:selected').val();
if (selectedThemChoice == 'ALL'){
$('a.dot').slideDown(1000);
}else{
$('a.dot[themchoice = "'+selectedThemChoice+'"]').slideDown(1000);
$('a.dot[themchoice != "'+selectedThemChoice+'"]').slideUp(1000);
}
});
I think it has something to do with the slideUp/slideDown function, but I can't figure it out...
There's a jsfiddle here.
You aren't distinguishing between "them" and "me" in any way, so you're hiding the other one which should be shown. Try something like this, to only hide the correct dots:
$(".me").removeClass("me");
$('a.dot[mechoice = "'+selectedMeChoice+'"]').addClass("me").slideDown(1000);
$("a.dot").not(".me, .them").slideUp(1000);
http://jsfiddle.net/XvHJS/10/
In this way you will hide only a previous "me" and not hide everything, including an active "them".
$('a.dot[mechoice != "'+selectedMeChoice+'"]').slideUp(1000);
Is also removing those which have no memchoice at all, including those with themchoice.
I would suggest using different classes dotme and dotthem instead.

How can I tell if the checkboxes are checked?

I need to be able to tell if the checkboxes are checked to do some basic validation. Problem: I don't have access to the PHP generating this. There is no class added, or the basic checked=checked that most forms have. What's the easiest way to target the checked boxes?
http://www.inpresence.in/event-registration?ee=4
EDIT: freak out!! here's the code, i just need to target the checked boxes, everything else is working. the :checked method of jquery uses checked=checked within the checkbox, which isn't there.
$(document).ready(function(){
//when the submit button is clicked...
$("input.btn_event_form_submit").click(function(){
//find the value of the drop down with one evening or four evenings
var priceOption = $("#price_option-4").val();
//match a string ending with "one evening" as the first numbers will be randomly generated by php
var oneEvening = /^\d{2}\|One Evening$/.test(priceOption);
//match a string ending with "four evenings" as the first numbers will be randomly generated by php
var fourEvenings = /^\d{2}\|Four Evenings$/.test(priceOption);
//HOW DO I GET THE CHECKED BOXES?!
var checkedBoxCount = $('#dates-1351733097 .valid').is(':checked').length;
//if one evening is selected make sure the checked boxes count does in fact equal one
if(oneEvening && checkedBoxCount != 1){
//if it doesn't alert the user and return false
alert('You must select one date');
return false;
}
//if one evening isn't selected, four is. make sure the count does indeed in 4
else if (fourEvenings && checkedBoxCount != 4){
//if it doesnt alert the user and return to the form
alert('You must select four dates');
return false;
}
//else, everything checks out!
else {
return;
}
});
});
Using this JavaScript code you can check if a checkbox is checked:
var isChecked = document.getElementById("my-checkbox").checked;
Or using jQuery:
var isChecked = $('#my-checkbox').is(':checked');
EDIT: Try this and tell me if it works:
var checkedBoxCount = $('#dates-1351733097 .valid:checked').length;
Have you tried using jquery to resolve this?
http://jquery-howto.blogspot.co.uk/2008/12/how-to-check-if-checkbox-is-checked.html
$('#edit-checkbox-id').is(':checked');
use the jquery :checked selector. http://api.jquery.com/checked-selector/
This will give you a boolean in javascript of what you want:
document.getElementById("Nov.12-4_1").checked
You can view source and find the elements to view whatever id's they have.
Other answers: the OP didn't specify that he wanted a jquery answer. If he hasn't used jquery for anything up to this point. I think adding it just for this would be a tad overkill.

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