Magento 2, Magento Development, Customization, Extension Development and Integration, Optimization, SEO and Responsive Design

Magento 2, Magento Development, Customization, Extension Development and Integration, Optimization, SEO and Responsive Design

Usefull jQuery and Javascript Examples

In our daily life we need to use some jQuery methods like addClass, removeClass, add ID or remove ID etc. So today i created a single page where user can find this all in one place.
jQuery-javascript

1) jQuery addClass()
    $( "#YOURID" ).addClass( "yourClass" );

2) jQuery removeClass()
    $( "#YOURID" ).removeClass( "yourClass" );

3) jQuery Add ID to Div()
    $( "#YOURID" ).attr('id', 'value');

4) jQuery Remove ID from Div()
    $( "#YOURID" ).removeAttr('id');

5) String replace
    var str = "My name is Hardik";
    var res = str.replace("Hardik", "HK");

6) Get value of text box
    var myval = $("#txtname").val();
    alert(myval );

7) Set value of text box
    $("#txtname").val("something");

8) Check element has class
    if($("#YOURID").hasClass("ClassName"))
    {
          alert("Class found");
    }
    else
    {
          alert("Class not found");
    }

9) Submit page
    $("#FORMID").submit();

10) Jquery ajax function
    $.ajax({
        type: "POST",
        url: "(URL OF YOUR PAGE)",
        data: 'id='+id+'&name='+name,
        success: function(data)
       {

        }
   },
   error: function(xhr, ajaxOptions, thrownError) { alert(xhr.responseText); }
  });

How to show image thumbnail before upload with jQuery

If you want to show image thumbnail before you upload image. Suppose you are using input type "file" in PHP and you want to show image which one is selected than you can use this simple solution.

Demo

Step1: Add following line of code in your file

<form id="myform">
         <input type='file' onchange="showImage(this);" /> 
         <img id="imagepreview" src="" alt="your image" /> 
</form>

Step2: Add following script in same page

<script type="text/javascript">
function showImage(input) { 
         if (input.files && input.files[0]) { 
         var reader = new FileReader(); 
         reader.onload = function (e) { 
                 $('#imagepreview').attr('src', e.target.result); 
         }
         reader.readAsDataURL(input.files[0]); 
      } 
  } 
</script>

Demo

 

Copyright @ 2017 HKBlog.