Select multiple items with javascript / asp.net - javascript

This is what I have so far I have a view that displays date that I have not reported a time for.
My idea is to tick the dates I want to report a time, so I can report time for multiple dates, and if I did check a date I do not want to report for I just uncheck that box.
I have that working, (kinda) The problem is if i want to select a date, i'll always have to select the first in the list before I can check any other date.
Like this:
That works great as long as I always choose the first date in the list.
But that is not what I am looking for, I want the option so I can report any data without having to check the first date first.
This would not work because I did not check the first date:
This is my script:
var dateArr=new Array();
function SetDate(dt) {
if(document.getElementById("isoDate").checked) {
if(dateArr.indexOf(dt)<0){ //Check if date is already added. if not add it to array.
dateArr.push(dt);
}
else{
var index=dateArr.indexOf(dt);
if (index > -1) {
dateArr.splice(index, 1);//Remove from array if checkbox uncheck
}
}
$('#date').val(dateArr.join(" ")); //Add space separated string to the #date element.
}
}
And this is my view where I get the dates:
#foreach (var date in ViewBag.MissingDays)
{
var isoDate = date.ToString("yyMMdd");
<div class="col-md-1">
<input type="checkbox" id="isoDate" name="isoDate" value="#isoDate"onclick="javascript:SetDate('#isoDate');" />
#isoDate
</div>
}

There are some observations regarding your code, like is not a good practice to have multiple items with the same id(i could actualy say that is a bad practice, i am talking about the checkboxes, the same name should be enough) or lines like:
if(document.getElementById("isoDate").checked)
that ruins everything(this i think it is the real source of your problem since the result is the first element and not being checked will step to else)
Seeing that you use jquery, here you have a small sample of how this should look like.

Related

How do I keep a previous value in a textbox when using a checkbox to add information to the textbox?

Okay, so I created this form that I use for work and it works pretty well considering my skill level is most definitely not professional. I learned HTML and JavaScript for a couple years in high school and have been self-taught on a lot of things since. Here's what I'm trying to do:
I have my form set up so that if I select an item from a drop-down menu and click a checkbox, the canned response I created is generated in the textbox. However, if I wrote anything in the textbox in advance, it gets wiped out. Now, the way I learned how to do this was based off of self-taught stuff I found online, so this is an example of what I have for the function that gets my canned responses:
function FillDetails29(f) {
if(f.checkbox29.checked == true) {
f.TEXT.value = ('' + f.trans.value + '')
} else {
f.TEXT.value = "";
}
}
I know that having
} else {
f.TEXT.value = "";
is going to wipe out anything that was there before or after if I uncheck the checkbox.
My question is what should I be doing to maintain my previous value when I uncheck the box? Example being:
Previous value to using the checkbox: Andrea looked good in that sweater.
Using the checkbox: Andrea looked good in that sweater. I wonder if there are any more at the store?
Unchecking the checkbox: Andrea looked good in that sweater.
I've done a lot of searching to see if there's something out there that can solve my problem but I'm afraid I'm not phrasing it right when I google it. Can anyone help me or point me in the right direction for this? I know that you guys don't want to just solve it for me and that I should be able to present some kind of example of what I've done to fix the problem but I've tried so many things that haven't worked that it would take too long to list them all without causing some kind of confusion. Even if you just have a website that you know of with an example of this that you can provide me, I'd be very grateful. Thank you!
Edit 1: To clarify, my original setup actually contains 3 forms. One form is for data entry where I input caller information and the checkbox for that spits out the entered data into a singular line of details for when I copy and paste into another program.
The second form is where I have quite a few checkboxes that I use because each section of the form requires separate canned responses. I work for a health insurance company on the phones with doctors offices (and soon I'll be talking to members as well) and I created the form to shorten the amount of time it takes for me to document information. So I have checkboxes that generate data for specific benefits, eligibility, authorizations, transferring the call, etc.
I have a lot of checkboxes to contend with. About 32, by my count. More, if I need to add them. Most of these checkboxes are connected with drop-down menus with the necessary canned response for it. Some of them are connected to their own textbox where I need to enter some kind of pre-determined data, such as a date of birth or a doctor's name. Those are not the focus, though. Once I enter data or select an option from the drop-down and click the corresponding checkbox, the data from that selected option appears in a main text area so that I can copy and paste the response to the work program.
The third form is one that's generated for claims information and has 10 checkboxes on it.
So, if you require more examples of what I'm referring to, I can provide them but it will take a few minutes for me to scrub the work related data that out of the canned responses I created.
Edit 2: The response I got from Epascarello was extremely helpful and I've been trying to experiment with different ways to keep the previous value at the start of the new text being inserted from the checkbox with no luck in getting what I'm looking for, though something unexpected has happened when I start with an empty box and select an option after I altered the code he suggested to this:
function FillDetails29(f) {
const elem = f.TEXT;
if (!elem.dataset.prevValue) elem.dataset.prevValue = elem.value;
const updatedValue = f.checkbox29.checked ? f.trans.value : (elem.dataset.prevValue || '') + (f.trans.value);
elem.value = updatedValue;
}
What started to happen is that if the box was blank previously and I selected an option, the option would generate. Then, if I unchecked the box, the option would remain. If I selected a new option, the new option generates. If I then unchecked the box, the first option and the second option would be there.
Example:
First option selected: Andrea looked great in that sweater.
Second option selected: I wonder if it's on sale now?
When unchecked, first option remains until second option is checked. When second option is unchecked, this is what results (from the same drop-down and checkbox): Andrea looked great in that sweater. I wonder if it's on sale now?
Now, I added the same kind of element to another checkbox item in the same area resulting in the code looking like this for that section:
function FillDetails28(f) {
const elem = f.TEXT;
if (!elem.dataset.prevValue) elem.dataset.prevValue = elem.value;
const updatedValue = f.checkbox28.checked ? f.dental.value : (elem.dataset.prevValue || '') + (f.dental.value);
elem.value = updatedValue;
}
function FillDetails29(f) {
const elem = f.TEXT;
if (!elem.dataset.prevValue) elem.dataset.prevValue = elem.value;
const updatedValue = f.checkbox29.checked ? f.trans.value : (elem.dataset.prevValue || '') + (f.trans.value);
elem.value = updatedValue;
}
And if I do something similar there, checking box 28 and then checking box 29, only whatever was most recently checked will materialize there. However, once everything is unchecked, each selected option will appear in the text box.
Example:
Checkbox 28 selected: Steven doesn't look good today.
Text area shows: Steven doesn't look good today.
Checkbox 29 selected: Andrea looks good in that sweater.
Text area shows: Andrea looks good in that sweater.
Checkbox 28 unselected with 29 still selected, text area shows: Steven doesn't look good today. Steven doesn't look good today.
Checkbox 28 and 29 now unselected, text area shows: Steven doesn't look good today. Andrea looks good in that sweater.
How should I be fashioning this so that those two options materialize one after another when the boxes are checked rather than when they're unchecked?
You can store the value into a data variable and reference it.
function FillDetails29(f) {
const elem = f.TEXT;
if (!elem.dataset.prevValue) elem.dataset.prevValue = elem.value;
const updatedValue = f.checkbox29.checked ? f.trans.value : (elem.dataset.prevValue || '');
elem.value = updatedValue;
}

Angular multi-select dropdown and lodash countby

I am kinda drawing a blank on this one facet, and I can't seem to quite figure it out.
So I have a simple HTML select => option element which is populated from the back-end (not really relevant tho)
My question is this:
Let's say I have a pre-made object such as this:
{
keyName1: 450,
keyName2: 800,
keyName3: 300
}
What I want to do is to check if the key name matches a name of an option value in my multi-select dropdown (the values come from an array, using 'ng-repeat' on the option), and if the option value matches the key, add the number value to some sort of increment variable, so I can display the total number of 'keyNames' found.
For example - if a user selects 'keyName1' the incrementer value will total 450. If a user selects 'keyName1' and 'keyName2' the incrementer value will total 1,250.
I am lost on how to accomplish this - right now it is reading only the very first item in the dropdown.
Here is the code doing that:
_.forEach($scope.widget.instance.settings.serviceContractTypes, function (type) {
// if item in array matches what is selected in multi-select option
if(type === $('#contractType:selected').text().trim()) {
// do stuff
}
});
Hope this all made sense, and thanks very much for any direction you might offer...
(does not have to utilize lodash, I'm just used to using it)
jQuery's :selected selector only works for HTML options:
"The :selected selector works for elements. It does not work for checkboxes or radio inputs; use :checked for them."
(https://api.jquery.com/selected-selector/)
You say "I have a simple HTML select => option element which is populated from the back-end (not really relevant tho)"
This could be relevant. By default, an HTML option tag does not support multiple selections; it has to explicitly be created as a select multiple in order to support that. Can you share the HTML code for the option to make it clear whether that's a problem or this is a red herring?
Also, can you echo $scope.widget.instance.settings.serviceContractTypes and share to make sure it's actually matching what's available in the text of the options?
ADDENDUM - Wait, I think I figured it out!
The $('#contractType:selected') selects all the selected options in #contractType and concatenates them. Then $('#contractType:selected').text().trim() trims this down to the first word, which is just the first selected option. You should do something like $('#contractType:selected').text().split(" ") and then check if each type is in the resulting list.

Select field populated with multiple entries after one checkbox change

I have something in my mind, but I have no idea how to get it done, so I hope I can get some advise here.
I'm working on an activity registration app (using Laravel), where every activity will be registered. Very important is that we need to record who was invited and who actually attended. I already have this part running. My issue is more on the practical side.
I use jQuery Select2 for the multiple select fields for invitees and attendees. Imagine now that there's a group of users that need to be invited or attend virtually all activities, while the invitation or attendance of others depends on the type of activity. Using Select2, I can only select users one at a time and that sucks if you need to do that for, say, 50 users for virtually every activity.
What is the best way to have a "group" that can be selected, which selection fills in all the names of those in the group in the select field? Or is there a better way to get this done?
I'm seeing something in my head, where there are checkboxes next to the select field, representing the groups. When you tick a checkbox of a group, the select field is populated with all users who are part of that group.
I have no idea ow this can be done. I looked around and every search brings up select boxes populating select boxes. None handle checkboxes.
Any advise on how to get this done?
My PHP/MySql is intermediate, Javascript/Ajax is very basic.
One strategy would be to build a control (checkbox element) that will set or toggle the selection of your group of users whenever it's clicked. Say we have the following markup:
<select class="my-big-group-select" multiple="multiple">
<!-- assorted options here -->
</select>
<label>
<input type="checkbox" class="toggle-default-group" />
Use my default big group of users
</label>
The Select2 API allows you programmatic control over the component it generates.
You can read more about it here: https://select2.github.io/examples.html#programmatic
Here's one way to leverage this knowledge using jQuery with Select2:
<script>
var groupSelect = $('.my-big-group-select').select2();
var groupToggle = $('.toggle-default-group');
var myBigGroup = ["Aaron", "Beth", "Cindy"]; // assorted option values
groupToggle.on("click", function() {
if ($(this).is(':checked')) {
groupSelect.val(myBigGroup).trigger('change');
} else {
var currentlySelected = groupSelect.val();
if (currentlySelected) {
var filteredSelections = currentlySelected.filter(function(key) {
return myBigGroup.indexOf(key) < 0;
});
groupSelect.val(filteredSelections).trigger('change');
}
}
});
</script>
Here's a CodePen that shows it all in action: http://codepen.io/anon/pen/qNQKOd
Of course you can build on this to make additional enhancements (the ability to select multiple groups, for example).
As an alternative, you may consider other code libraries like Bootstrap Multiselect: https://davidstutz.github.io/bootstrap-multiselect/
Hope this points you in the right direction!

Select2 type to select

I'm trying to use select2 to have a multi-select dropdown list of states, but something is wrong.
Normally, when you type an option out, it's highlighted so that you can hit enter and select it. It underlines the option, but does not highlight it, so if I type "alabama" but hit enter, it will select "arkansas".
I'm using the latest version (3.5.1)
HTML
<label class="control-label" for="states">States:</label>
<input id="states" name="states" />
<input class="btn btn-primary" type="submit" value="Submit Search" />
JavaScript:
$("#states").select2({
width: 'resolve',
maximumSelectionSize: 5,
ajax: {
dataType:"json",
url:"getStates.cfm",
results: function(data) {
return {results:data};
}
},
multiple:true
});
Am I missing some sort of parameter? I could have sworn this was working fine the last time I used it. No console errors, and it click selects perfectly.
Note that the github page works just like I want (when you type, it selects the first option that matches)
In Select2 3.x, the highlighted result in the dropdown will always be the first result during searches. This will be changing in Select2 4.x, so the selected option will be selected if it is present.
You are looking for the results to be sorted differently. By default, Select2 orders options by the order that they have within the DOM, not by how relevant they are. The documentation provides an example of how to customize the sorting of results using the sortResults option.
Keep in mind that it is more efficient to sort the results on the server side when using AJAX, which is why Select2 does not do any further sorting. This would explain why "Arkansas" is being returned when searching for "Alabama".
I had the same problem. And solution was found when i found that every time i type into search box, each time it calls query function. That's it. So all i required to do fill results only if it matches at least one character in anyone of the text of the available options. The following way :
query : function(opts){
var res = [];
var fulloptions = ArrayFoundUponYourAjaxOrAnyStaticOptions;
var stripDiacritics = Select2.util.stripDiacritics;
for(var z=0,len=fulloptions.length;z<len;z++){
if(stripDiacritics(fulloptions[z].text.toUpperCase()).
indexOf(stripDiacritics(opts.term.toUpperCase())) >= 0){
res.push(fulloptions[z]);
}
}
opts.callback({ results : res }); // res is your filtered/matching rows out of which first one will get auto hightlighted
}

Creating a javascript that creates a dynamic total depending on radio box checked in html form

Dearest stackoverflow friends,
I am creating an online html form and have created a javascript function to dynamically (not completely sure I'm using this word correctly) display the total due in membership fees at the bottom of the form as options are selected. The total fee depends on one's membership type, country, and method of payment. It worked perfectly when all I was calculating was the membership type and postage according to country (I used drop down forms for these two options). Now I'd like to add the third term to the equation (the method of payment - one has a choice of cheque or paypal) but I can't get it to work. I'm using radio buttons this time.
My totalling function is this (without "+ getPaypalfee()" it works just fine):
function getAmountDue()
{
var amountDue = getMembershipPrice() + getExtraPostagePrice() + getPaypalfee();
document.getElementById('amountDue').innerHTML ="Amount Due: $"+amountDue;
}
The javascript I wrote to return the paypal fee is this (it's become very convoluted and I'm not sure where I've gone wrong and how to restart!):
var paymentmethod_Fee = new Array();
paymentmethod_Fee["cheque"]=0;
paymentmethod_Fee["paypal"]=2;
function getPaypalfee()
{
var paypalFee=0;
for (var i=0; i < document.membershipform.payment_method.length; i++)
{
if (document.membershipform.payment_method[i].checked)
{
var selectedPaymentmethod = document.membershipform.payment_method[i].value;
}
}
paypalFee = paymentmethod_Fee[selectedPaymentmethod.value];
return paypalFee;
}
The html for the radio buttons looks like this:
<p>I will make payment via: <BR>
<input type="radio" id="payment_method" name="payment_method" value="cheque" checked="yes" onchange="getAmountDue()">Cheque
<input type="radio" id="payment_method" name="payment_method" value="paypal" onchange="getAmountDue()">Paypal (Add $2)
Any insights into the flaw in my logic is greatly appreciated! I'm a javascript novice and radio buttons seem to be my nemesis (I'd like to learn how to use them rather than replace them with a drop-down menu or something I know how to do already).
Thank you!
Arrays shouldn't be used to create mappings between items. What you're looking for is an object:
var fees = {
cheque: 0,
paypal: 2
};
As for your error, it's this line right here:
paypalFee = paymentmethod_Fee[selectedPaymentmethod.value];
paymentmethod_Fee is already a string. It doesn't have a value attribute.
Don't use more than one element with the same id. Doing so creates glitches. OVER 9000 glitches. So, don't use duplicate ids. Just don't. It is a maxim of web development. It will serve you well. Follow it to the letter. Or, you will have glitches. I am sure you don't want glitches. Rid yourself of glitches. Don't use duplicate ids.
(preceding paragraph tl;dr: Always have unique ids, or you get glitches.)
You should wrap your radio buttons in a div with id payment_methods. Then, use document.getElementById("payment_methods").childNodes[i] to access each successive button.
(By the way, two radio buttons with the same name are mutually exclusive, so the buttons should have identical names but different ids.)
You are using checked correctly. It's just how you're accessing elements that's causing glitches.
Hope this gets rid of your glitches.

Categories

Resources