Google analytics code

Showing posts with label createElement. Show all posts
Showing posts with label createElement. Show all posts

Friday, August 2, 2013

Javascript / IE8 : file fields created by javascript allows text entry

I ran into an issue in IE8 while creating file fields in javascript for a form. The newly created file field allowed text entry. It didn't matter if I used jQuery or created the field with createElement.


$
var fileField = $('',{
            'id': 'picker-2',
            'type': 'file'});

            $('#fields').append(fileField);

When the field was placed on the screen it allowed users to enter text. This isn't a huge issue, but this shouldn't happen. It doesn't happen when you create the file field through HTML. You can see an example here.

The solution to this problem is cloning the newly created field before appending it to the DOM.


var fileField = $('',{
            'id': 'picker-2',
            'type': 'file'});

$('#fields').append(fileField.clone());
            
            

This will make it behave like a normal file field. You can see an example here.

Thursday, October 8, 2009

Javascript: Adding options to a select element

I've started working with javascript more and more now. I'm leaning away from using innerHTML and started creating the objects instead. As with anything javascript related Internet Explorer will cause more problems than solutions.

When you're creating a new option element that will be added to a select element IE wants to do it one way while everyone else can handle it another way. I'll show the first way I tried to tackle it, and then show the cross browser way to handle it.

I set up a try, catch block that would try IE first. If an error occurred it would fall back to the second method that works in most browsers.


//IE code
try
{
obj_option = document.createElement('<option value="test value"/>');
obj_text = document.createTextNode("option text value");
obj_option.appendChild(obj_text);
}
//everyone else
catch(e)
{
var obj_option = document.createElement('option');

obj_option.text = "option text value";
obj_option.value = "test value";
}


Internet Explorer wants to place the value inside of the createElement method while other browsers can handle the assignment on the object property. Also IE wants the text added with createTextNode. It's a pain to have two methods for something so simple. After a bit of experimentation and research I have a method that works for all browsers.


var obj_option;
var obj_text;

obj_option = document.createElement('option');
obj_text = document.createTextNode("option text value");
obj_option.appendChild(obj_text);
obj_option.setAttribute("value", "test value");


This is much cleaner and easier to maintain. setAttribute is also a handy method for assigning non standard properties to an object. Some client-side form validation scripts want to add proprietary properties to a tag. Using setAttribute is the easiest way to create them.