Javascript

Javascript quick tips : how to access data on the page

When we play with Javascript, we often don’t remember simple things because syntax is not so “intuitive” by moment.

This great language is one of the most powerfull we have to build any kind of applications then i am gathering here, for me, quick and simple tips to go fast.

1] Get the value of a form with Javascript (pure DOM)

If the form id is “form_id” (<form id=’form_id’ etc..)

You can catch any element in the form with its name (becarefull it’s then the name then the name=”XXX”

document.getElementById(‘form_id’).elements[‘XXX’].value;

1.1 ] But Checkbox always return ON when i am accessing directly in JS with Jquery ? (Jquery)

Checkbox behavior is little diffrent form other fields…just use this with Jquery where my ‘inmail’ is the id of the checkbox (<input type=’checkbox’ id=’inmail’). It will be then manage the fact you checked or not the checkbox…

if($(‘#inmail’).prop(‘checked’)) {

    alert ('IN MAIL OK');

  // something when checked

} else {

alert('IN MAIL NOK');

 // something else when not

}

2] Test if an element exists in the page (pure DOM)

var panelMainWrapper = document.getElementById(“moduletitle”+id); // try to catch the id moduletitle

if (document.body.contains(panelMainWrapper)) { // if this id is in the page…

3 ] Wait this element appears on the page (pure DOM)

var panelMainWrapper = document.getElementById(“moduletitle”+id);

setTimeout(function waitPanelMainWrapper()

{

if (document.body.contains(panelMainWrapper)) {

  // do what you want to do when the Id 'moduletitle' is on the page

} else {

    setTimeout(waitPanelMainWrapper, 100); // wait 100 ms before to test again

}

}, 10);

4] Browse all the fields of a form (jQuery).

With Jquery, you can browse easily all the fields in a form….if the ID of the form is formadd, i browse all input type=’xx’ and all select doing that :

the .each method will loop and you access data inside the form by using this chain : var input=$(this); and input.attr(‘type’) for the type, (‘name’) for the name and input.val() for the value linked…

$(‘#formadd input,#formadd textarea ,#formadd select’).each(

  function(index){

      var input = $(this);

      // Keep it to get the way to catch the information - please don't delete

      //alert('Type: ' + input.attr('type') + 'Name: ' + input.attr('name') + 'Value: ' + input.val());

      stringofvariable+=input.attr('name')+"="+input.val()+";";


  }

);