Tag Archives: javascript

Web

Bind event to element in jQuery

ordjq
To bind any event to element (for ex. textarea) use next code:

$(document).ready(function() {
  var prevValue = $("#some_id").val();
  $("#some_id").bind('change click keyup', function(e){
    if($(this).val() != prevValue){
      alert(e.which);
    }
    prevValue = $(this).val();
  });
});
Web

For loop through an associative array

assocarr
To go through an associative array or object, you could use:

<script type='text/javascript'>
/* <![CDATA[ */
var data = {};
data['var1'] = 'value1';
data['var2'] = 'value2';
data['var3'] = 'value3';
console.log(data);

for (var prop in data) {
  if (Object.prototype.hasOwnProperty.call(data, prop)) { 
    console.log("prop: " + prop + " value: " + data[prop])
  }
}
/* ]]> */
</script>
Web

JQuery ajax request

ajax
Next example demonstarates Login method:

var backEndpath = '/backend';

function unparam(p) {
  // http://stackoverflow.com/questions/1131630/javascript-jquery-param-inverse-function/4764403#4764403
  var ret = {}, seg = p.replace(/^.*\?/,'').split('&'), len = seg.length, i = 0, s;
  for (;i<len;i++) {
    if (!seg[i]) {
      continue;
    }
    s = seg[i].split('=');
    ret[s[0]] = s[1];
  }
  return ret;
}

function doLogin() {
  var data = unparam($.param( $('form input,textarea,select') ));
  data['operation_name'] = 'login';
  data['formatter'] = 'json';
  $.ajax({
      url: '/user',
      type: 'POST',
      data: data,
      success: function(data) {
        try {
          //alert(data);
          event = JSON.parse(data);
          if (event.is_error == 'true') {
            $('#login_result').html(event.message).show();
          }
          else {
            $(location).attr('href', backEndpath);
          }
        } catch(e) {
        alert(e);
        }
      },
      error: function(jqXHR, textStatus, errorThrown) {
        alert(textStatus + ': ' + errorThrown);
      }
  });
  return false;
}

Method unparam converts all form fields to array.

Web

Confirm dialog in Javascript

To implement confirmation for some action in webpage, use:


In element attribute onclick:

onclick="return doConfirmMultipleInvoice();"
Web

Escape/Unescape HTML in Javascript


Very useful function for working with HTML.

  function escapeHTML(str) {
    return str.replace(/&/g,'&')
      .replace(//g,'>');
  }

  function unescapeHTML(str) {
    return stripTags(str)
      .replace(/</g,'<')
      .replace(/>/g,'>')
      .replace(/&/g,'&');
  }
  
  function stripTags(str) {
    return str.replace(/<\w+(\s+("[^"]*"|'[^']*'|[^>])+)?>|<\/\w+>/gi, '');
  }