Javascript : find first unchecked box and retrieve information from row - javascript

So I am trying to find a way to extract data from the first row where the checkbox from the first column is unchecked. I know this may sound like a true beginner question but I couldn't manage to find how to do it despite searching for quite a few hours.
Here a step-by-step of my goal to clarify :
Find the first checkbox which is unchecked;
Retrieve information from another column (inner html) but from the corresponding row and an attribute ("name") of the checkbox;
Without opening it on-screen, use the attribute of the checkbox (partial URL) to open completed URL and retrieve more information into MySQL;
Check the checkbox;
Rince and repeat
I am only looking for info concerning step one and two, the rest is there for clarification. I do not have prior experience in Javascript writing prior my last few days of Internet browsing, the only coding I've done were statistical analysis in R.
Any help would be highly appreciated.
Thank you very much!
Nikola

Well, you can use the same class for every checkbox (i.e. rowcheck):
<input type="checkbox" class="rowcheck" id="CbRow_1" name="test" value="test">
And then you loop through the checkboxes:
$(".rowcheck").each(function (index, element) {
if ($(element).prop("checked")) {
//Get the row number from ID
var rownumber = $(element).prop("id").split("_")[1];
//Now you do stuff with the other element
$("#element_" + rownumber).html("whatever")
}
});

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;
}

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!

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.

Javascript, Jquery, Cross browser issues, Frustration

I am a predominantly PHP developer. I realize in this day and age specialization in one scripting language doesn't cut it, but the fact remains that my skills at JavaScript and jQuery are pretty green. I am a novice at best. I can create my own code but Cross Browser compatibility remains a huge issue with my work in JavaScript.
Anyway, I have a script that filters products according to categories/subcategories. This is how it works: you select a category and the javascript in the background does its thing to filter the subcategories so that the options displayed are the ones pertaining to the parent category- a combination of these two filters the product line.
Here is my code:
function scategories(){
//get the category option value from the category drop down bar
var cat = (document.getElementById('categories').value);
//get all the options from the subcategory drop down bar
var subcat = document.getElementsByClassName('subcategories');
var n=0;
//if the category bar option is set to 0 display everything
if(Number(cat)==0){
Show();
}
//filter the subcategories
while(subcat.item(n)){
//if there is no match b/w the subcategories option and the categories id FILTER
if(Number((subcat.item(n).value).split('|')[1]) != Number(cat) && Number(subcat.item(n).value) != 0){
document.getElementsByClassName('subcategories')
.item(n)
.style
.display="none";
}else{
//else display the subcategory
document.getElementsByClassName('subcategories')
.item(n)
.style
.display="list-item";
}
n++;
}
}
This code is pretty self explanatory I would say. I also have a shiftfocus function that shifts the focus from the current option selected in the subcategory to the default one which is 'none' whenever a new category is picked. This basically resets the subcategory.. here's the code:
function shiftfocus(){
document.getElementsByClassName('subcategories')
.item(0)
.removeAttribute("selected");
document.getElementsByClassName('subcategories')
.item(0)
.setAttribute("selected","selected");
}
Shiftfocus is called onChange and scategories is called onClick.
Problem 1:
1) Firefox: Shiftfocus doesn't shift the focus to the default option even though I can see it adds the 'selected' attribute.
2) Safari: Does not work at all.
EDIT: Problem 2 was the product of a careless mistake. I left open an anchor tag which was
creating havoc in IE. Should have double checked before bothering you
guys. Sorry. Problem 1 still persists.
Problem 2:
I understand none of us developers particularly like internet explorer. But I am willing to believe I have made a mistake here. I have some jQuery that fetches data from a script in another file via the native POST function and appends it to a table with the id "content". This works fine on every browser, except IE. If I try going back to IE 7,8 compatibility mode the results are a little better (the data shows up broken in pieces though) and in IE9 compatibility mode nothing is appended at all! Here's the code:
$.post("bagcontents.php", {
"Bid": $(this).attr('bid')
},
function(data){
$("#content").empty().append(data);
roundNumber();
$('#processorder_hidden').attr('value',currentBid);
});
//append here
<div id="contents" style="overflow:auto;height:345px;padding-right:5px;">
<form name="bag_contents" id="bag_contents" method="post" action="<?php _page ;?>">
<table id="content">
</table>
<input type="hidden" id="bag_contents_hidden" name="bag_contents_hidden" value="1" />
</form>
</div>
Any help will be appreciated. I tried outputting the fetched results with alert, alert(data), and the script is fetching everything just fine. Its the just the append part that fails :|
Here are some suggestions and hope you find them somewhat useful.
Problem: 1
Instead of having the shiftfocus() set the to a specific value, have you tried using .val('') just to clear it out. I can imagine that this will default to the first option.
Problem: 2
This will be hard to debug without knowing what data is coming back from the server. Might be bad formatting or some syntax error on the rendered output.

Adding an input name upon creation of new table row

I have an order form I had put together for a client, you can view it here.
As you can see it creates a new row with 5 input fields (per row). Here's my problem, I have this form outputting the form in html format to the clients email for office use. I need to add a "unique name" for each input in the newly created row in order to pass that to the processing and out to the email.
Here is the JS file for adding rows
I know this has to be triggered by the $addRowBtn but I have been at this for awhile now and everything I have tried has just broken the form.
I've tried this example but to no avail:
thisRow.find("input.ClassName").attr("name","newName" + num);
num++;
I will buy the first person that helps with this a cup of coffee or something! It's bugging the ever living crap out of me!!
in your javascript you are setting thisRow as follows
thisRow = $(this).parents("tr");
but it should be
thisRow = $(this).parents("tr").eq(0);
then you can do
thisRow.find("input").each(function(i) {
$(this).attr("name", "newName" + i);
});
Also check what this returns alert(thisRow.find("input").length); it should return 5 since you have 5 input elements in the row.
I hope it works.
Just looking at this, I can see that this is being attached to the "remove row" function. Shouldn't this be fired off on the "add row" function. I'll give it whirl and see what happens.
Also, because each row has a unique identifier (orderType, sample, pattern, etc.), each input gets incremented when a new row is created, can I just assign each one with a starting value like this:
input class="order_type" name="orderType[i]" type="text"
And couldn't I just set up an array for each of the five inputs and loop it through until it hits the "max rows" which is 6?
I just don't know how to push that value "i" off to the newly created inputs on each row.

Categories

Resources