Showing posts with label jquery. Show all posts
Showing posts with label jquery. Show all posts

javascript: typeerror (intermediate value) is not a constructor

It's been long time since i have written a blog post as i am busy with the project deliverable. So, here i am with one more issue which i faced today while writing some basic javascript code.

The error is 

javascript: typeerror (intermediate value) is not a constructor

i came across this issue when i am returning some object from a function. Following is the similar javascript code that i have written

function buildContact() {
        return new { name: "John", mobile: "123-456-7890", country: "US" };
    } 

this is the javascript function which was showing the mentioned error. 

Cause:

I used new which can be only used with a Function as operand. In this case i am using object as a constructor which is actually not. 

Fix:

Here we have two options to fix this error. 

1. To return object directly as shown below
function buildContact() {
        return { name: "John", mobile: "123-456-7890", country: "US" };
    }      

2. Create a constructor and use the constructor to create new object as shown below

function Contact(name, mobile, country) {
        this.name = name;
        this.mobile = mobile;
        this.country = country;
    }

    function buildContact() {
        return new Contact("John", "123-456-7890", "US");
    }

in this case we are returning the new Contact() by using constructor. 

In this way you can fix the error javascript: typeerror (intermediate value) is not a constructor.

Please do comment if you know better way to fix this error. Thanks in advance. 

To know more common javascript errors visit: Javascript 


Read more...

How to call Asp.Net MVC controller action method using JQuery

In this article i  am going to explain how to call controller actions using JQuery in Asp.Net MVC.

Get data from MVC Controller action method:


You can either use $.get or $.ajax functions to call mvc controller action methods using Jquery.

Example:

Assume you have following mvc controller and action method.

public class EmployeeController : Controller
    {
        public string GetEmployee()
        {
            var emp = new Employee() { Id = 1, Name = "John", Designation = "SE" };
            return Newtonsoft.Json.JsonConvert.SerializeObject(emp);
        }
    }

Above Employee Controller has one action method i.e., GetEmployee() which is returning serialized Employee data.

Now use the following JQuery code to call the above mvc action method

Method 1: Using $.get()

$.get("/Employee/GetEmployee", function (data) {
        var employee = JSON.parse(data);
        alert(employee.Name);
    });

Method 2: Using $.ajax()

$.ajax({
        url: "/Employee/GetEmployee",
        success: function (data) {
            var employee = JSON.parse(data);
            alert(employee.Name);
        }
    });

Note: I am using JSON.parse because controller action is returning serialized data. So we have to parse it to convert that to normal object.

Post data to MVC controller action methods using JQuery:


Using POST we can submit the data to controller actions.

Assume you have following controller action which saves the submitted data to database.

[HttpPost]
public bool SaveEmployee(Employee employee)
        {
            //your code to save employee to database
            //return true if data saved succesfully
         
            return true;
        }

Now use the following JQuery code to post data to controller action method.

Method 1: Using $.post()

//create the employee object
var employee = { Name: "Dave", Id: 2, Designation: "Sales" };

    $.post("Employee/SaveEmployee", employee, function (data) {
        if (data == "True") { //change condition based on your return type
            alert("Employee Saved succesfully");
        }
    });

Method 2: Using $.ajax()

//create the employee object
var employee = { Name: "Dave", Id: 2, Designation: "Sales" };

    $.ajax({
        url: "/Employee/SaveEmployee",
        type: "POST",
        data: employee,
        success: function (data) {
            if(data == "True") //change condition based on your return type
            alert("Employee Saved");
        }
    });

In this way we call Asp.Net MVC controller actions using JQuery.

For more posts on JQuery Visit: JQuery


Read more...

How to make Ajax call with JQuery

In this article am going to explain how to make ajax call with JQuery.

JQuery has $.ajax() method which is used to perform an asynchronous HTTP request.

The syntax of $.ajax() function is as follows

$.ajax(url[, options])

url is a string parameter that you want to reach with AJAX call while options is an object literal containing the configuration for the Ajax request.

JQuery AJAX example:

$.ajax({
  url: "demo.txt",
  success: function(result){
    alert(result);
  }
});

JQuery AJAX post example:

$.ajax({
  type: "POST",
  url: url,
  data: {name:"ranadheer",id:2},
  success: function(data, status,, jQxhr){
     alert(data);
  },
  error: function(jQxhr, textStatus){
     alert(error);
  }
  dataType: dataType
});


This way we can make AJAX calls with JQuery.

For more posts on JQuery visit: JQuery

Read more...

Create cookie using JQuery

This article explains how to create/read/edit/delete cookie in Jquery.

First you need to add jquery cookie plugin. Add jquery.cookie.js javascript file from following url.

https://github.com/carhartl/jquery-cookie/blob/master/src/jquery.cookie.js

Create/Set cookie using JQuery:

Use the following jquery code to create the cookie.

 $.cookie("cookieName", "cookieValue");

Use the following jquery code to create the cookie with expiry.

$.cookie("cookieName", "cookieValue", { expires: 7 });

above cookie expires in 7 days.


Get/Read cookie using JQuery:

Use the following jquery code to read the cookie value.


$.cookie("cookieName");

We just have to use the cookie name to read it's value.


Edit cookie value using JQuery:

Use the following jquery code to edit the cookie value.

$.cookie("existingCookieName", "newValue");

above code updates the existing cookie value.


Delete cookie using JQuery:

Use the following jquery code to delete the cookie

$.removeCookie("cookieNameToBeRemoved");

In this way we can create/get/edit and delete cookies using JQuery.

For more posts on JQuery visit: JQuery


Read more...

Upload file asynchronously using JQuery

In this post i am going to show you how to upload a file asynchronously using JQuery.

Using HTML5 we can upload files with Ajax and JQuery. We can also do file validations like name, checking size and file type. We can also handle the progress event. All the above things without using any external plugins.

How to upload a file : 


Assume you have following html. 

<form enctype="multipart/form-data">
    <input name="file_name" type="file" />
    <input id="btnUpload" type="button" value="Upload_File" />
</form>
<progress></progress>

In the above html we have a form in which we have a file upload control and a button to upload the file. We also have a progress tag using which we can track the file upload status.

To do the validation we have to use the onChange event of the fine control.

Validation for file upload :

$(':file').change(function(){
    var file = this.files[0];
    var fileName = file.name;
    var fileSize = file.size;
    var fileType = file.type;
    //Add validation code here
});

In the above code we got the uploaded file's name, size and type. Validation can be done using these properties.

JQuery code to upload the file :

$('#btnUpload').click(function(){
    var formData = new FormData($('form')[0]);
    $.ajax({
        url: 'url for processing file',
        type: 'POST',
        xhr: function() {  // Custom XMLHttpRequest
            var myXhr = $.ajaxSettings.xhr();
            if(myXhr.upload){ // Check if upload property exists
                myXhr.upload.addEventListener('progress',progressHandlingFunction, false); 
                // For handling the progress of the upload
            }
            return myXhr;
        },
        //Ajax events
        beforeSend: beforeSendHandler,
        success: completeHandler,
        error: errorHandler,
        // Form data
        data: formData,
        //Options to tell jQuery not to process data or worry about content-type.
        cache: false,
        contentType: false,
        processData: false
    });
});

Now lets implement the file upload progress handling function

function progressHandlingFunction(e){
    if(e.lengthComputable){
        $('progress').attr({value:e.loaded,max:e.total});
    }
}

Above code updates the progress tag with the percentage of file uploaded.

In this way we can upload files using JQuery and Ajax.


For any doubts/suggestions please comment in comments section below.

For more posts on JQuery visit: JQuery 

Read more...

How to redirect a page using JavaScript or JQuery

In this article i am going to explain how to redirect a page using javaScript or JQuery.

It is better to use JavaScript to redirect a page than using JQuery as JavaScript is simple compared to JQuery.

Example:

You can use any of the following code to redirect a page using JavaScript

// similar behavior as an HTTP redirect
window.location.replace("http://yourdomain.com");

// similar behavior as clicking on a link
window.location.href = "http://yourdomain.com";

Both lines mentioned above redirects the page to location given in parenthesis. Only difference is window.locaiton.replace does not put the new page in session history. That means once you redirected to new page then you will not be able to go back to old page using browser's back button.

Where as if you use window.location.href new page will be stored in the session so that you can be able to go back to old page using browser's back button.

I have added an example in JSFiddle. You can check in this link Redirect page using JavaScript


Redirect page using JQuery


Use the following code to redirect a page using JQuery

$(location).attr('href', 'http://yourDomain.com')

In this way you can redirect a page using JavaScript or JQuery.


For more posts on JavaScript visit JavaScript


For more posts on JQuery visit JQuery

Read more...

Dynamically add or delete rows to table using Javascript

In this article i am going to show you How to dynamically add or remove(delete) rows from table using Javascript

Consider you have following html

<html>
 <body>
   <div id="table-container">
       <table id="my-table">
       </table>
   </div>
 </body>
</html>

We already have a table with id = "my-table"

Now, let's see how to add rows dynamically using Javascript


first let's create rows

  var row1 = table.insertRow(0);

Above command creates an empty <tr> element and adds it to the first position of the table

  var row2 = table.insertRow(1); 

Above command creates an empty <tr> element and adds it to the second position of the table

Now, let's create row cells

 var cell1 = row1.insertCell(0);
 cell1.innerHTML = "Name";

Above command creates an empty cell and adds it to first row of the table

 var cell2 = document.createElement("td");
 cell2.innerHTML = "Age";

Above command creates an empty cell and adds it to first row of the table.

Now we have a table with two rows and first row having two cells.


Remove rows dynamically using Javascript


  document.getElementById("my-table").deleteRow(0);

Above command deletes first row from the table having id = "my-table"

In this way we can dynamically add or delete rows from table dynamically JavaScript

Also check - Create table dynamically using JQuery

Read more...

Create table dynamically using JQuery

In this article i am going to show you How to create a table dynamically using JQuery

Consider you have following html

<html>
 <body>
   <div id="table-container">
   
   </div>
 </body>
</html>

Now you can create table dynamically using following JQuery

  var table  = $(document.createElement('table'));             // creating table dynamically
  var tableBody= $(document.createElement("tbody"));      // creating table body dynamically
  var row = $(document.createElement("tr"));                      // creating table row dynamically
  var cell1 = $(document.createElement("td"));                    // creating table cell dynamically
  cell1.html("Name");


// append cell to row. (you can create any number of cells and then append to row)
row.append(cell1);

// append row to table body
tableBody.append(row);

// finally append table body to table
table.append(tableBody);

So, by above JQuery code we have created a table dynamically.

Now let's append the dynamically created table to div.

  var container = $("#table-container");
  container.append(table);

We added dynamically created table to container.

In this way we can create a table dynamically using JQuery
Read more...

Checkbox checked property in JQuery

Using JQuery we can check whether a checkbox is checked or not.

Consider you have a check box like below

<input type="checkbox" id="checkbox1"/>

 Using the below JQuery code, you can check whether the above checkbox is checked or not


if ($("#checkbox1").is(':checked')) {
    alert("checked");  // checked
}
else {
    alert("not checked"); // unchecked 
}

Note: is(':checked') returns TRUE if the checkbox is checked else it returns false.

You can also use below code to check checkbox is checked:


if ($("#checkbox1").attr("checked")) {
    alert("Checked");
}
else {
    alert("Unchecked");
}

Note: Since jQuery 1.6, The behavior ofjQuery.attr() has changed. So it is recommended not to use it.

Javascript Code to check checkbox's checked property:


var myCheckbox = document.getElementById('checkbox1');
 
myCheckbox.onchange = function () {
    if (this.checked) {
        alert("checked");
    }
    else {
        alert("not checked");
    }
}

In this way you can check whether a checkbox is checked ot not using JQuery

For more posts on JQuery please visit: JQuery

Read more...

How to disable or enable input field using JQuery

If you want to disable any input field like button or checkbox or textbox etc, you can do it using JQuery.

Consider you have the following input fields in your page

<input type="text" id="tb1" />
<input type="button" id="btn1" />
<input type="checkbox" id="chkbx1" />
<input type="radio" id="radio1" />
Now if you don't want to allow a user to enter text into textbox(in cases when you are showing pre-loaded data) or if you don't want to allow a user to click on the submit/send button until all the form fields are valid, then in the above cases you can disable those input fileds using jQuery's prop() method.

jQuery code to disable the input fields:


Disable textbox using jQuery


$("#tb1").prop('disabled'true);  //for jQuery 1.6+
$("#tb1").attr('disabled''disabled'); //for jQuery 1.5 and below

Re-enable textbox using jQuery


$("#tb1").prop('disabled'false); //for jQuery 1.6+
$("#tb1").removeAttr('disabled'); //for jQuery 1.5 and below

Disable button using jQuery


$("#btn1").prop('disabled'true);  //for jQuery 1.6+
$("#btn1").attr('disabled''disabled'); //for jQuery 1.5 and below

Re-enable button using jQuery


$("#btn1").prop('disabled'false); //for jQuery 1.6+
$("#btn1").removeAttr('disabled'); //for jQuery 1.5 and below

You can also disable radio button or checkbox using jQuery in the same way.

In this way you can disable the input fields using jQuery. Let me no if it helped you through comments section. Feel free to share any information.

For more posts on jQuery please visit: jQuery

Read more...

get current window url in javascript

You can get the url of the current window using javascript.

To get the current window url, use the below javascript:

var url = window.location.href;
The above javascript code gives the full url of the window.


To get the current window url using jquery, use the below code:

var url = $(location).attr('href');


To get the origin of the url use the following javascript code:


var origin = window.location.origin;


To get the pathname use:


var pathname = window.location.pathname;


To get the current window protocol use:


var origin = window.location.protocol;


To get the port number of the current window use:


var port = window.location.port;


To Reload the current page using javascript use:


window.location.reload();


In this way you can get the url of the current window using javascript.

For more posts regaring please visit : Javascript


Read more...

Get selected radio button value using JQuery

Using JQuery, we can get the selected radio button value. Lets see how we can do this..

Consider you have a list of Radio Buttons in your form like below

<form id="form1">
    <input type="radio" name="myRadio" value="1" /> 1 <br />
    <input type="radio" name="myRadio" value="2" /> 2 <br />
    <input type="radio" name="myRadio" value="3" /> 3 <br />
</form>

JQuery code to get the selected radio button value is

$('#form1 input').on('change'function () {
        var value = ('input[type="radio"]:checked').val();
        alert(value);
    });
 or you can also use the following code

$('#form1 input').on('change'function () {
        var value = ('input[name="myRadio"]:checked').val();
        alert(value);
    });
When a user selects the radio button, then JQuery's .change() event gets called. And when this event is raised, we are storing the value of the selected radio button in a javascript variable.

For live example look at this fiddle: http://jsfiddle.net/codingsolver/MsYqx/

In this way we can get the selected radio button value using JQuery.

For more posts on JQuery please visit: JQuery

Read more...

Get Asp.Net TextBox or Label value using JQuery

If you have a Asp.Net TextBox or Label then you can get the value of that textbox/label using Jquery.

Get TextBox value with jquery:


Lets say you have a asp.net textbox like below

<asp:TextBox ID="txtName" runat="server" />

then you can get the value of the above textbox using JQuery using the below code

var name = $("#<%=txtName.ClientID %>").val();

Get Label value with jquery :


Lets say you have a asp.net label like below

<asp:Label ID="lblName" runat="server" Text="codeSolver"/>

then you can get the value of the above label using JQuery using the below code

var name = $("<%=lblName.ClientID %>").html();

Note: If you notice the selector in the above code, we are using "ClientID" to get the value of the control. This is because Asp.Net controls are rendered as html controls in the browser. The "id" will be not same as what you have given to that control.

So if you simply write $("#txtName") it won't work. We use that syntax to get the value of a HTML input(type="text") element.

In this way we can get the Asp.Net TextBox or Label values using JQuery.

For more posts on JQuery visit: JQuery

Read more...