Check checkbox based on multiple table cell criteria - javascript

I have an html table full of data, the first column contains an input checkbox and a name. I want to check this checkbox when two criteria are met:
the name is "Complete"
the date sent matches a string passed in "m/d/yyyy" i.e. "9/20/2016" (no leading zeros)
I can already do the first using getElementByTagName("input") and checking if it is a checkbox and that the name is Complete
function checkAllComplete()
{
var allRows = document.getElementsByTagName("input");
for (var i=0; i < allRows.length; i++) {
if (allRows[i].type == "checkbox" && allRows[i].name == "complete")
{
allRows[i].checked = true;
}
}
}
The date in the cell is "9/20/2016 4:02:03 PM". I also have the regex I want to use to get it into m/d/yyyy:
var myRe = new RegExp("^([1-9]|1[012])\/([1-9]|[12][0-9]|3[01])\/(19|20)[0-9]{2}", "g");
But I'm having trouble getting the corresponding td and it's text. I tried a getElementsByClassName but since there are other input items the counts are off. I tried using class name for the checkboxes but then I cannot check them.
I've assigned a class to all the tds, the first column with the checkbox is "actionClass" and the one with the date string is "dateSentClass"
I'm open to javascript or jquery as a solution.
edit: here's the fiddle with a sample table structure https://jsfiddle.net/trueimage/4u87euz5/2/

To get the checkboxes, you can use:
document.querySelectorAll('input[type=checkbox]');
or:
jQuery('input[type=checkbox]');
You can use the following to get an array of the tds:
document.querySelectorAll('td.yourClass');
and then you can call either innerHTML or textContent to get the contents of the td as a string.
You can also use:
jQuery('td.yourClass');
and call .text() on each element to get the contents of the td.

It sounds like you are trying to get the text of a td.dateSentCell cell that exists in the same row as the cell containing the input that is represented by allRows[i]. If that's correct, you can use this jQuery:
var dateText = $('td.dateSentCell', $(allRows[i]).parent().parent()).text();

Related

Select part of the text like we select with a mouse using javascript

I am trying to select a part of the text similar to selecting it with a mouse.
I referred to this example here: How to select part of a text using select method?.
by using this code I'm able to select all content in the element (by providing the element id). however, I am unable to select only the desired part.
with the following code, I'm able to select all the contents.
var selection = window.getSelection();
var txt = document.getElementsByClassName("xyz");
var range = document.createRange();
range.selectNodeContents(txt);
selection.removeAllRanges();
selection.addRange(range);
i want to modify the code in such a way that by providing a kewyword and element id I want to slect all the instance of the keyword in that element id.
further, I want to use a loop function to loop through all the instance of the keyword and modify the text. ex: get a substring from the text etc.
If you use getElementsByClassName you get HTMLCollection - all elements with the specified class name. Use loop to go through all this elements. You have possibility to get access to the element text using innerText property.
find all elements with class 'post-text' on this page:
let elementsCollection = document.getElementsByClassName("post-text");
go through all html elements in the collection and replace the keyword with your own string. Note that the replace() method searches a string for the value (regular expression) and than returns a new string where the values are already replaced. If you want to replase all values in the test use the global (g) modifier.
let keyWord = 'element';
let newValue = 'editedElementTest';
for (i = 0; i < elementsCollection.length; i++) {
let elementText = elementsCollection[i].innerText;
let reg = new RegExp(keyWord, "g");
let newStringResult = elementText.replace(reg, newValue);
document.getElementsByClassName("post-text")[i].innerText = newStringResult;
}

Java Script - Get property "innerText" from Table td

I need to get the text that's written inside a td, but it always gives me an undefined.
This is my try of getting the text:
console.log($('USERvalue'+keykey).prop("innerText"));
console.log($('td[id^="USERvalue"]').prop("innerText"));
Both are the same element. on the first one i target a specific one. In the second line i target several, because i just say the id should start with xy.
But both give me an undefined. If I'm correct that means that it finds the element but cant find any text.
This is the element i try to reach and get the text out of it:
for(let key = 0; key < GlobalVarUS2.length; key++){
let temp = $("<tr><td id='USERvalue"+key+"' value='"+GlobalVarUS2[key]["pk_us_id"]+"'>"+GlobalVarUS2[key]["benutzername"]+"</td><td><input type='checkbox' id='CHBUSER"+key+"' style='size: 30px'></input></td></tr>");
temp.appendTo("#table_user");
}
Ultimately I want to compare it to a string and if it is correct, do something. But first i need the text of the element.
I hope someone can help me :)
You are using $('td[id^="USERvalue"]').text() like a single element. But in real case it is returning multiple elements, So if you want text of all td then you have to process them in loop and you have to contain text in single variable which will be appended each time. for example:
var text="";
$.each($('td[id^="USERvalue"]'),function(k,v){
text += $(v).text();
});
console.log(text);

How do I use getElementsByClassName and how can I fix id/index mismatch?

I am trying to grab data from the database and format it into string to display to the user under a kendo UI dropdown list when the user makes a specific selection.
Right now I'm having problem with my JavaScript function:
UpdateRange: function (e) {
var value = this.value();
allRanges[value];
console.log("length of range is:", allRanges[value].MinLength, "-", allRanges[value].MaxLength);
lengthname = "length of range is:" + allRanges[value].MinLength + "-" + allRanges[value].MaxLength;
document.getElementsByClassName("result").innerHTML = lengthname;
var elements = lengthname;
for (var i = 0; i < elements.length; i++)
elements[i];
},
My questions are...
I am using
<div class="result"></div>
in
<td></td>
tags which contain my kendo UI dropdownlist. I tried using getElementsByClassName and it did not work. Nothing happened. I'm not sure why... perhaps innerHTML does not work with Class Name?
How can I display the string from the database using innerHTML ?
Also, I noticed that the data in my database has ids starting with 1,2,3,4, etc... and allRanges[] is an array that starts with an index of 0. How do I align the two items so that when the user selects a value from the dropdownlist..e.g. that has a value of 4... then the array picks the value with index of 3 and not index of 4.

Newbie: Checking to see if radio button is checked on form initialization. What does this code mean?

I am a javascript novice. I'm trying to build a complex form whilst simultaneously learning JS and JQ... not an easy task. This code works, but I don't know what two lines do, so I thought I'd ask here.
What this code does is loop through an array to see if a radio button checkbox has been checked as yes or no. It runs at initialization when a user revisits the form he/she is filling out. The code is attached to a textfield element which unhides if myRadioButton is yes, stays hidden if no.
I do not know what lines 5 and 6 do (beginning with the second if statement). Would some knowledgable person please be so kind as to transcribe those lines into a couple of sentences, kind of like they do in tutorials? I would really appreciate it!
var rbVal = "";
var rbBtn = JQuery("[name=\"myRadioButton[]\"]");
for (var i = 0; i < rbBtn.length; i++)
if (rbBtn[i].checked) {
if (rbVal != "") rbVal += ",";
rbVal += rbBtn[i].value;
}
if( rbVal != "yes" ){
doSomething;
}
else {
doSomethingElse;
}
That code is checking all radio buttons with a shared name myRadioButton[], to make sure that if one is checked its value is added to rbVal string seperated by a comma.
var rbBtn = JQuery("[name=\"myRadioButton[]\"]"); <- gets an array of radio buttons
for (var i = 0; i < rbBtn.length; i++) <- loops through every button in that array.
if (rbBtn[i].checked) { <- if the button is selected it then checks to see if rbVAl is already set. <-- Either you are missing something here or it is faulty program
Line 5 compares the value of rbVal to an empty string (""). If rbVal is not equal (!=) to an empty string, a string containing a comma character is appended to rbVal. So for example, if rbVal contains the string "hello", after the execution of that line, it will contain "hello,".
Line 6 then appends the value of rbBtn[i].value to rbVal. rbBtn is an array-like object (in fact, it appears to be an instance of jQuery containing whatever was matched by the selector), and when you access a jQuery object with array syntax like that, you get the actual DOM element rather than another jQuery object, so the value property is the actual value property of the DOM element (by the look of it, that will be a radio button).
So, if you have a radio button like this:
<input type="radio" value="someVal">
then your loop would result in rbVal == "someVal".
If you have two radio buttons:
<input type="radio" value="someVal">
<input type="radio" value="anotherVal">
then you would end up with rbVal == "someVal,anotherVal". You can see from that what the overall purpose of that loop is - to build up a comma-separated string of the values of all the radio buttons matched by the jQuery selector.
Curiously, this is using jQuery to grab radio buttons and some vanilla JavaScript to see if the returned radio buttons are checked or not.
var rbVal = ""; initalises a new variable with an empty string "".
var rbBtn = JQuery("[name=\"myRadioButton[]\"]"); fetches all elements from the document that are called myRadioButton[].
for (var i = 0; i < rbBtn.length; i++) loops through each of the returned elements (there might be more than one as myRadioButton[] is an array of radio buttons hence the [] at the end). i is the current index in the array of returned elements.
if (rbBtn[i].checked) sees whether the radio button is "checked" ("on", if you like).
rbVal += rbBtn[i].value;: If the current radio button is checked (remember, for() loops through them all), fetch it's value attribute and append it (add it onto) whatever is currently in rbVal.
For example, if rbVal contains Hello and the radio button's value is world then rbVal would end up containing Hello world.
if( rbVal != "yes" ) If the value in rbVal doesn't equal (!=) yes, then we call the doSomething function.
If rbVal does contain yes, then we want to call the doSomethingElse function:
else {
doSomethingElse;
}

determining if a field exists on a form

I have a form field (a series of checkboxes) that's being created dynamically from a database, so it's possible that the field will not exist on the form (if there are no matching values in the database). I have some code that needs to execute based on whether the field exists, and pull in the values that are selected if it does exist. I can't seem to get javascript to acknowledge that this field exists, though. Here's what I've tried:
function displayAction(){
var f = document.adminForm;
var a = f.action;
if(f.prefix.value!="-") {
a = a + '&task=callExclusionDisplay&prefix=' + f.prefix.value;
}
else {
var exclusions = document.getElementById("exclusions");
if (exclusions != null){
alert("exclusions set");
a = a + '&task=callExclusionCreate&prefix=' + f.prefix.value + '&exclusions=' + exclusions.join();
}
}
alert('after if, action is ' + a);
}
The code never passes the if statement checking to see if exclusions is not null, even though when I look at the page there are a number of checkboxes named exclusions (with the id also set to exclusions). Is the issue with !=null because it's a group of checkboxes, rather than a single form element? How can I get this to work? If I skip the test for null, the code throws errors about exclusions not being defined if the database doesn't return any matching values.
You're using document.getElementById, but form elements have a name.
Try f.elements.namedItem("exclusions") instead of exclusions != null
Multiple elements in the same page cannot share an id attribute (ie. id must be unique or unset). As well, though some (older) browsers erroneously collect elements whose name matches the ID being looked for with getElementById, this is invalid and will not work cross-browser.
If you want to get a group of elements, you can give them all the same name attribute, and use document.getElementsByName to get the group. Note that the result of that will be a NodeList which is kind of like an array in that it can be iterated over.
Do all the checkboxes have the same id == exclusions?
If yes, then you must first correct that.
Before you do so, did you try checking the first checkbox and see if the if condition goes through?
if you have more than one element with the id "exclusions" it will screw up the functionality of getElementById. I would remove the duplicate "exclusions" ids from all of your elements and use getElementByName() instead, and give your group of checkboxes the name="exclusions" instead.
Edit:
But there is a much simpler way using jQuery, and it gives you some cross browser compability guarrantee. To do the same thing with jQuery do this:
var checkBoxesExist = $('[name=exclusions]').count() > 0;
Or if you have given your elements unique ID's then you can do this:
var checkbox1exists = $('#checkBox1').count() > 0;
Each element must have a unique ID.
Then, you can check just like this:
if (document.getElementById('exclusions1')) {
//field exists
}
Or if you need to loop through a bunch of them:
for (x=0; x<10; x++) {
if (document.getElementById('exclusions' + x)) {
//field X exists
}
}

Categories