Categories
JavaScript jQuery Web

JQuery: Join JSON arrays

The simplest way to merge JSON arrays usning JQuery is to use the concat function.

var json1 = [{id: 1, name: "one"}];
var json2 = [{id: 2, name: "two"}, {id: 3, name: "three"}];
var finalObj = json1.concat(json2);

Here finalObj will contain an array of 3 objects:
[{id: 1, name: “one”},{id: 2, name: “two”}, {id: 3, name: “three”}]

Categories
JavaScript jQuery Web

JQuery Check if Element Exists – JS Helpers

JQuery Check if Element Exists using this simple piece of code. To check this in the current page, we need to check the length of the element returned by the JQuery selector, if it returns you something then the element must exists otherwise no.

if( $('#EleSelector').length ) { // use this if you are using id, replace EleSelector with the id
// it exists
}

if( $(‘.EleSelector’).length ) { // use this if you are using class, replace EleSelector with the id
// it exists
}

In case of plain javascript try this:

//you can use it for more advanced selectors
if(document.querySelectorAll("#EleSelector").length){}

if(document.querySelector("#EleSelector")){}

//you can use it if your selector has only an Id attribute
if(document.getElementById("EleSelector")){}

Categories
JavaScript jQuery Web

JQuery Check if Checkbox is checked – Simple Solution

For a check box with the id “checkbox”, here is how to check if its checked:

$('#checkbox').is(':checked'); // Returns True if checked else False

Categories
JavaScript jQuery Solutions Web

JavaScript Loop Through Select Options – Example

Sometimes we need to iterate through all the options of a DropDown list (and perform operations based on each one). Here is how to do it(for a dropdown with the id “dropdownlist”)

JavaScript:

var x= document.getElementById("dropdownlist");
for(i=0; i<x.options.length;i++){
console.log(x.options[i].value);
//Add operations here
}

JQuery:

$("#dropdownlist > option").each(function() {
console.log(this.text + ' ' + this.value);
//Add operations here
});