Append options to a select element using javascript

//dynamically add 20 years from this year to drop-down

      var select = document.getElementById(“ccexp”);

      var startYear = new Date().getFullYear();

      var option, currentYear, currentYearString, currentYearTwoDigit;

      for (var i = 0; i <= 20; i++) {

          currentYear = startYear + i;

          currentYearString = currentYear.toString();

          currentYearTwoDigit = currentYearString.substring(2);

          option = document.createElement(“option”);

          option.setAttribute(“value”, currentYearTwoDigit);

          option.appendChild(document.createTextNode(currentYear));

          select.appendChild(option);

      }

Javascript to append options to a select element

select multiple elements by class, and loop through them with javascript

I have a table with elements in it. I need to target them and change the css class.

<div class="dwtooltip"><img src="note_icon.png" /><span class="dwtooltiptext">my tooltip text here.</span></div>

const items = document.querySelectorAll(‘.dwtooltip’);
if(items){

}
for (var i=0; i < items.length; i++) {
console.log(i);
items.forEach(function(el){
el.classList.add(“notooltip”);
el.classList.remove(“dwtooltip”);
});
}


Change an elements class with JavaScript

To change all classes for an element:

To replace all existing classes with one or more new classes, set the className attribute:

document.getElementById("MyElement").className = "MyClass";

(You can use a space-delimited list to apply multiple classes.)

To add an additional class to an element:

To add a class to an element, without removing/affecting existing values, append a space and the new classname, like so:

document.getElementById("MyElement").className += " MyClass";

To remove a class from an element:

To remove a single class to an element, without affecting other potential classes, a simple regex replace is required:

document.getElementById("MyElement").className =
   document.getElementById("MyElement").className.replace
      ( /(?:^|\s)MyClass(?!\S)/g , '' )
/* code wrapped for readability - above is all one statement */

An explanation of this regex is as follows:

(?:^|\s) # match the start of the string, or any single whitespace character

MyClass  # the literal text for the classname to remove

(?!\S)   # negative lookahead to verify the above is the whole classname
         # ensures there is no non-space character following
         # (i.e. must be end of string or a space)

The g flag tells the replace to repeat as required, in case the class name has been added multiple times.

To check if a class is already applied to an element:

The same regex used above for removing a class can also be used as a check as to whether a particular class exists:

if ( document.getElementById("MyElement").className.match(/(?:^|\s)MyClass(?!\S)/) )

Temporary disable HTML5 “required” attribute

Sometimes when developing, I need to turn off the html5 required so that I my test and implement server side validation. I don’t want to have to remove the attribute from each input element manually, and then have to put them back on. So I use jquery to select the inputs and remove the required attribute.  Then I just delete this line of code when I’m finished testing/developing and wish to turn back on html5 client side required.

// temp for dev
$(“:input”).each(function(){$( this ).removeAttr(“required”);});

Allow user to print the contents of an element

Here is a cross browser solution to allow the user to press a button and print out the contents of an element. Suppose we have a content area with an id of “mycontentarea”, and a button that says “print”. We can attach a handler to the click event and run this code in the function to print out the contents of “mycontentarea”:

[code]
w=window.open();
reportinfo =  document.getElementById(‘mycontentarea’);
w.document.write(reportinfo.innerHTML);
w.document.close();
w.print();
w.close();[/code]

Get numbers from end of string JavaScript Regular Expression

Here is a regular expression that will match the numbers at the end of the string and return an array with the match it made.

var mystringwithnumbersatend="mycoolname32";
var thenumbersmatch = mystringwithnumbersatend.match(/\d+$/);
if(thenumbersmatch){number=thenumbersmatch [0];}

To use the number in a calculation, make sure to parse it:

number=parseInt(number, 10);

Remove Quotes From A String Using JavaScript

If you ever need to strip out quotes from a string, here is a handy Regular Expression. This will remove any single or double quotes from the var str.

function delquote(str){return (str=str.replace(/[“‘]{1}/gi,””));}

 

Example:

str=”My string’s really “quoted”, eh?;

delquote(str); // returns My strings really quoted, eh?

Working with numbers in JavaScript

Make a string into a number for use in calculations : Number(string);

Round a number to certain place after making calulations:
The Math.round() function returns the value of a number rounded to the nearest integer.

Math.round(x)

The Math.abs() function returns the absolute value of a number.

var abs = Math.abs(x);

The Math.floor() function returns the largest integer less than or equal to a number. This is basically to round DOWN:

Math.floor(x) 

The Math.ceil() function returns the smallest integer greater than or equal to a number. This is to round UP:

Math.ceil(x)

Check for url anchor code in a string with JavaScript

Well, I have come across the need to make sure that a string doesn’t contain any code that would make it a link. For example, I need to allow the user to enter a filename but not have any html code in it.

For this current situation:
<a href=”myfile.html”> is an invalid string.
http://myfile.html        is an invalid string.

I want the user to only be able to submit “myfile.html” and then I will handle the linking and referencing using server side code.
[code] function checkurl(){ // function to ensure no a href or quotes get in here.
console.log(“Lets check the url to make sure no a href or quotes”);
var thelink=$(“#slide_external_link”).val();
if(thelink !== “”){ // check for stuff we dont want.
if(thelink.match(/href=”([^”]*”)/g) || /^(f|ht)tps?:///i.test(thelink)){ // this looks like it comments out after i.test, but its workin.
console.log(“Can’t process the request because there is code inside the string. We only want the address of page without anchor code”);
alert(“Please remove any anchor code from the external link. An example of valid entry is: directory.asp_Q_pagenumber_E_520”);
return false; } } } // end check url funk[/code]
Now I can call this function as part of my client side validation upon form submit. I also need to implement a server side catch as well, just in case.

Sort a table using JavaScript and Jquery

I have come across the need to update a ui view of tabular content to be sorted by numeric order ascending. Javascript has a sort() that can be used for this purpose. I will use jquery for its powerful and easy selection capabilities.

Here is a sample of the tablular data:

Sequence Filename Description Enabled Delete
0 sliders/test.jpg Its a slider True X
1 sliders/test2.jpg Its another slider! True X
2 my file location my file description True X

When the user changes the sequence, I would like to update the ui view to reflect the changes in the display order.

I have given each row of the table that contains sortable data a class of “sort”

Then I use Jquery to select those rows, and sort them by the number in the sequence column.

 function sortthetable(whattable){ var $tbody = $('#'+whattable); $tbody.find('tr.sort').sort(function(a,b){ var tda = $(a).find('td:eq(0)').text(); // can replace 0 with the column you want to sort on var tdb = $(b).find('td:eq(0)').text(); // this will sort on the firstcolumn // if a < b return 1 return tda > tdb ? 1 // else if a > b return -1 : tda < tdb ? -1 // else they are equal - return 0 : 0; }).appendTo($tbody); }