Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 2

jQuery

Button click() Method


    $("p").click(function(){
        console.log(The paragraph was clicked.");
    });
Get Attribute attr() Method
    $(".btn").click(function(){
        id = $(this).attr("data-id");
        console.log(id);
    });
Set Attribute attr() Method
    $("button").click(function(){
    $("img").attr("width","500");
    });
Set or Change Form Input Value Based on the name Attribute
   $('input[name=username]').val("username1");
Set or Change Form Select Value
    var value = "valueIntChar";
    $("#selectInputId option[value='"+value+"']").attr("selected","selected");

Reset or Clear the Select Input’s selected attribute


    $('#selectInputId option:selected').removeAttr('selected');

jQuery Functions

jQuery Ajax
Ajax on form submit
    $("#myformName").submit(function(e) {
        e.preventDefault();
        $.ajax({
            url: 'ajax.php?action=save_data',
            method: "POST",
            data: $(this).serialize(),
            success: function() {
                alert("Success");
            }
        })
    })
Ajax form submit with an image
    $('#image-form).submit(function(e) {
        e.preventDefault();
        $.ajax({
            url: 'ajax.php?action=save_image',
            data: new FormData($(this)[0]),
            cache: false,
            contentType: false,
            processData: false,
            method: 'POST',
            type: 'POST',
            success: function() {
                    alert("Data successfully added", 'success')
                }
            }
        })
    })
Here contentType and processData attributes are very important, since the image cannot be
processed with serialize function.

Get Selected Array From Form Select Options


var val1=[];
  $('select[name="array_name[]"] option:selected').each(function() {
    val1.push($(this).val());
  });
  console.log(val1);
Set Options as Selected From Array
    var values = ["2","3","5"];
    $.each(values.split(","), function(i,e){
        $("select[name='arr_name[]'] option[value='" + e +
"']").prop("selected", true);
    });
Void Javascript anchor href Method
 <a href="javascript:void(0)">No Redirection</a>

You might also like