javascript getelement where value contains specific string - javascript

I was wanting to count the occurrences of input fields that has a class name of text where that text input contains a specific value.
document.getElementById('c_files').getElementsByClassName('text').length;
So far this counts all textboxes with the class name of text but how can i make it value specific, say if i have 50 textboxes but i only want to count the ones where the value of that textbox contains abc somewhere within the string.
Thanks.
Edit: Thank you everyone for your time and answers, i have voted you all up, but i prefer John Bupit's solution out of them all so thats the one i will accept. Thanks again.

You can iterate over the elements and see which ones have the desired value:
var elems = document.getElementById('c_files').getElementsByClassName('text');
var count = 0;
for(var i = 0; i < elems.length; i++) {
if(elems[i].value.match(/abc/)) count++;
}

You can select all textboxes first and after that filter those matching your criteria. For example, by using Array.prototype.filter method:
var allText = document.getElementById('c_files').getElementsByClassName('text'),
filtered = [].filter.call(allText, function(textbox) {
return textbox.value.indexOf('abc') > -1;
});
Above code will produce and array of text elements where value contains substring "abc".

Hi I think you need to review this SO post-
https://stackoverflow.com/a/9558906/3748701
https://stackoverflow.com/a/10095064/3748701
This is something which would help in getting your solution.

You'll need to loop over all of the text boxes with the specified class and calculate it from there.
Something like the following logic should work:
var counter = 0;
var inputElements = document.getElementById('c_files').getElementsByClassName('text').length;
for (var i = 0; i < inputElements.length; i++) {
if (inputElements.value == "someText") {
counter++;
}
}

Related

Empty / blank out all fields in a form page

I have the below code, is there a way to put this in a simpler format.
I am having to blank out 50 or more fields when a date in a certain key field is changed or made blank.
if (zEntry ==""){
document.getElementById("Q229I1226").value="";
document.getElementById("DQ230I1227").value="";
document.getElementById("DQ231I1228").value="";
document.getElementById("Q4I1001").value="";
//Date from fall to arrival
document.getElementById("Q232I1229").value="";
document.getElementById("DQ233I1230").value="";
document.getElementById("DQ234I1231").value="";
document.getElementById("Q5I1002").value="";
//Date Time of referral to T&O surgery
document.getElementById("Q238I1235").value="";
document.getElementById("DQ239I1236").value="";
document.getElementById("DQ240I1237").value="";
document.getElementById("Q15I1012").value="";
document.getElementById("Q17I1014").value="";
//Date seen T&O 1st on call
document.getElementById("Q241I1238").value="";
document.getElementById("DQ242I1239").value="";
document.getElementById("DQ243I1240").value="";
document.getElementById("Q16I1013").value="";
}
Thank you
You have to add common class to your inputs.
var array = document.getElementsByClassName('className');
for (var i = 0, lng = array.length; i < lng; i++) {
array[i].value = '';
}
If you want to clear out all fields with same tag you can just use
document.getElementsByTagName(arg) while arg being 'input', 'option' etc.
But if you want specific inputs to be cleared, you have to give them a class and use
document.getElementsByClassName(arg)
Add class to the input fields and try
var array_container = document.getElementsByClassName('example');
for (var i = 0, i < array_container.length; i++) {
array_container[i].value = '';
}
You may try this approach too:
// store all the element ids in an array
var element_ids = ['Q229I1226', 'DQ230I1227', 'DQ231I1228', 'Q4I1001',
'Q232I1229'];
element_ids.forEach(function(element_id){
document.getElementById(element_id).value = '';
});
Here is a solution of how to clear all input boxes/fields by looping.
Loop though all input boxes and clear them

how to split the textarea into parts in javascript

I am trying to open the 5 urls inputted by the user in the textarea
But the array is not taking the url separately instead taking them altogether:
function loadUrls()
{
var myurl=new Array();
for(var i=0;i<5;i++)
{
myurl[i] = document.getElementById("urls").value.split('\n');
window.open(myurl[i]);
}
}
You only should need to split the text contents once. Then iterate over each item in that array. I think what you want is:
function loadUrls() {
var myurls = document.getElementById("urls").value.split('\n');
for(var i=0; i<myurls.length; i++) {
window.open(myurls[i]);
}
}
Here's a working example:
var input = document.getElementById('urls');
var button = document.getElementById('open');
button.addEventListener('click', function() {
var urls = input.value.split('\n');
urls.forEach(function(url){
window.open(url);
});
});
<button id="open">Open URLs</button>
<textarea id="urls"></textarea>
Note that nowadays browsers take extra steps to block popups. Look into developer console for errors.
There are a couple issues I see with this.
You are declaring a new Array and then adding values by iterating through 5 times. What happens if they put in more than 5? Or less?
split returns a list already of the split items. So if you have a String: this is a test, and split it by spaces it will return: [this, is, a, test]. There for you don't need to split the items and manually add them to a new list.
I would suggest doing something like:
var myUrls = document.getElementById("urls").value.split('\n');
for (var i = 0; i < myUrls.length; i++) {
window.open(myUrls[i]);
}
However, as others suggested, why not just use multiple inputs instead of a text area? It would be easier to work with and probably be more user friendly.
Basically:
document.getElementById("urls").value.split('\n');
returns an array with each line from textarea. To get the first line you must declare [0] after split the function because it will return the first item in Array, as split will be returning an Array with each line from textarea.
document.getElementById("urls").value.split('\n')[0];
Your function could simplify to:
function loadUrls(){
var MyURL = document.getElementById("urls").value.split('\n');//The lines
for(var i=0, Length = MyURL.length; Length > i; i++)
//Loop from 0 to length of URLs
window.open(
MyURL[i]//Open URL in array by current loop position (i)
)
}
Example:
line_1...
line_2...
... To:
["line_1","line_2"]

adding radio button values in separate groups using javascript

I have a form with radio buttons that I'm using javascript to loop through and return the sum of all the radio buttons to an input element at the bottom of the page. The script I'm using is this and it works fine.
<script type="text/javascript">
function checkTotal() {
var radios = document.querySelectorAll('input[type=radio]'),
sumField = document.querySelector('input[type=text]');
var sum = 0;
for (var i = 0, len = radios.length - 1; i <= len; i++) {
if (radios[i].checked) {
sum += parseInt(radios[i].value);
}
}
sumField.value = sum;
}
</script>
Here's my form http://cognitive-connections.com/Prefrontal_Cortex_Questionnaire.htm
However I need to build another form where there are several questions in different groups and I need to sum the totals for each group separately and post them to their corresponding input elements on the page accordingly. Here's my new form http://cognitive-connections.com/Prefrontal_Cortex_Questionnaire100913.htm
I'm not an advanced javascript user but do have a pretty good understanding of programming itself (I think, lol) My head tells me that I should be able to simply declare a unique var for each different group and a unique element to post it's results to and use the same loop (with correct vars for each group) for each group. But when I add [name="elements name"] as the identifier for the document.querySelectAll it grabs the elements with that name only and if I name the elements themselves the same name the radio buttons loose their inherent property of only letting one radio button per question be selected at a time? I've also tried creating a class id for each group and tried to use it as the identifier in the document.querySelectAll and it doesn't seem to work at all then. Any help is greatly appreciated..
As per my understanding of question, below is my answer. And here is the fiddle http://jsfiddle.net/8sbpX/10/.
function enableQ(cls) {
var ele = document.querySelectorAll('.' + cls)[0],
ev = (document.addEventListener ? "#addEventListener" : "on#attachEvent").split('#');
ele[ev[1]](ev[0] + "change", function () {
var radios = ele.querySelectorAll('[type="radio"][value="1"]:checked').length;
ele.querySelector('[type="text"]').value = radios;
});
}
enableQ("rad-grp");

Replace string of text javascript

Im trying to replace a string of text for another string of text here is my code plus js fiddle
HTML
<div class="label">Rating:</div>
<div class="data rating">****</div>
Javascript
var str=document.getElementsByClassName("data" ,"raiting").innerHTML;
var n=str.replace(/\*/g,"star");
document.getElementsByClassName("data", "raiting").innerHTML=n;
Demo
http://jsfiddle.net/sgGQz/1/
document.getElementsByClassName() method returns, as its name suggests, a collection (HTMLCollection) of elements, not a single one -even if there's just a single element with the given classname(s) in DOM.
You need to go through each of them in order to make such a replacement. For example:
var elements = document.getElementsByClassName("data rating");
for (var i = 0, l = elements.length; i < l; i++) {
elements[i].innerHTML = elements[i].innerHTML.replace(/\*/g, 'star');
}
JSFiddle.
Alternatively, if you know for sure that there should be only a single element, you can assign it directly:
var elementToAdjust = document.getElementsByClassName("data rating")[0];
// ...
If you only have one occurrence of the element this will work:
var str=document.getElementsByClassName("data rating")[0].innerHTML;
var n=str.replace(/\*/g,"star");
document.getElementsByClassName("data rating")[0].innerHTML=n;
If multiple data rating elements exist use:
var elems =document.getElementsByClassName("data rating");
for(var i = 0; i < elems.length; i++){
elems[i].innerHTML = elems[i].innerHTML.replace(/\*/g,"star");
}
Both method correct some flaws in the original code.
First, rating was misspelled in the argument passed to getElementsByClassName. Second, getElementsByClassName() uses class names delimited by spaces to select elements with multiple classes, instead of multiple arguments. Get elementsByClassName returns an array of elements which must be iterated through.
JS Fiddle: http://jsfiddle.net/sgGQz/5/
You need to check again for getElementsByClassName,It returns node-List, so you can do like this and You can loop through then after each element and set your value
var str=document.getElementsByClassName("data" ,"raiting")[0].innerHTML;
var n=str.replace(/\*/g,"star");
document.getElementsByClassName("data", "raiting")[0].innerHTML=n;
Here is the example as you have only one occurance

how to loop though div and get each value

I am trying to figure out how to get each value within my div. I am using
var cart = $('.basic-cart-cart-node-title.cell').text();
It is giving the results of OI-01OP-01OS-10-5SOR-04OR-05
I need to view them one by one: OI-01, OP-01, OS-10-5S, OR-04 OR-05.
So that I can match them against another field.
If you care to help me further, I have another div on the page:
var ParNum = $('.assess-title').text();
I would like to compare the values returned from the var cart and see if that value is in the ParNum. If it is there, I would like to apply a class.
Any help would be greatly appreciated.
Thanks!
You can store the values in an array using .map() method:
var values = $('.basic-cart-cart-node-title.cell').map(function() {
return $.trim( $(this).text() );
}).get();
For checking existence of the ParNum value in the array:
var does_exist = values.indexOf(ParNum) > -1;
Try this to iterate over elements:
var text = '';
$('.basic-cart-cart-node-title.cell').each(function (i, div) {
text += ' ' + $(div).text();
});
or this to get an array of matching div elements:
var divs = $('.basic-cart-cart-node-title.cell').toArray();
for (var i = 0; i < divs.length; i++) {
// $(div).text();
}
Reason for this is that $('.basic-cart-cart-node-title.cell') returns all div's at once, and you need to loop through the result. More specifically, $(selector) returns a so-called "wrapped set". It can be used to access each matching element (as I've shown above) or it can be used to apply any other jQuery function to the whole set at once. More info here.
var text = "";
$('.basic-cart-cart-node-title.cell').each(function(){
text += $(this).text() + ", ";
});
// remove the last ", " from string
text = text.substr(0, text.length -2);
var cart = [];
$('.basic-cart-cart-node-title.cell').each(function {
cart.push($(this).text());
}
This performs the matching and class adding you mentioned in the question.
var ParNum = $('.assess-title').text();
$('basic-cart-cart-node-title.cell').each(function () {
if ($(this).text() == ParNum) {
$(this).addClass("someclass");
}
}
You should try using
var cart ='';
$('.basic-cart-cart-node-title'.find('.cell').each(function()
{
cart = cart + $(this).val();
});
Hope it works for you.
var cart = $('.basic-cart-cart-node-title.cell').text().match(/.{5}/g);
This will give you an array with items 5 chars long. Regexes arent very fast, but a loop might be slower
Or easier to read, and in a string with commas:
var cart = $('.basic-cart-cart-node-title.cell').text(); // get text
cart = cart.match(/.{1,5}/g); // split into 5 char long pieces
cart = cart.join(",",); join on comma

Categories

Resources