Showing posts with label html. Show all posts
Showing posts with label html. Show all posts

Wednesday, November 11, 2015

Data attribute in html and setting multiple data-* attributes in JQuery

Have you heard of data attribute in HTML? Well, it's a very handy attribute in developing web applications. We can easily bind custom data to any element in the DOM using the data attribute. This custom data can then be easily fetched using JQuery.

Suppose we have a link like this
<a id="show_data" data-category="Student" data-name="John" data-semester="sixth" href="#" >Show Data</a>
Now we can extract the data in JQuery like this
$("#show_data").click(function() {
         var name = $(this).data("name");
         var category = $(this).data("category");
         var semester = $(this).data("semester");
         alert(name + ", " + category + ", " + semester);
});

Now the reverse, suppose you have a link element or any element and want to set data attribute(not just data, you can set any attribute too) using JQuery
<a href="#" id="our_link">Our link element</a>

$(document).ready(function() {
         $("#our_link).attr({
                      'data-name' : 'John',
                      'data-category' : 'Student',
                      'data-semester' : 'sixth'
         });
});

This way you can set multiple attributes to an element.

Monday, October 19, 2015

Post Values from Uneditable input fields

Sometimes you want to set the data of an input field through JQuery and at the same time you need that field to be uneditable, then the workaround is to add the attribute 'readonly' to that field. Being 'readonly' makes the field uneditable and the form will submit the value as well whereas the attribute 'disabled' makes the field uneditable but the form will not submit the value.

Example:
<input name="un_editable_field" type="text" readonly />

Now you can get the values normally in the action file
$value = $_POST['un_editable_field'];