Abdus Sattar Bhuiyan
Abdus Sattar Bhuiyan

Reputation: 3074

How can I add attribute inside an input tag using jQuery?

HTML is:

<div class="form-item" id="edit-image-upload-wrapper"><img id="img_prev" src="#">
     <label for="edit-image-upload">Upload Your Picture: <span class="form-required" title="This field is required.">*</span></label>
     <input type="file" name="files[image_upload]" class="form-file required" id="edit-image-upload" size="60"></input>

     <div class="description"><p>You need to provide a passport sized image in jpg/jpeg or png format. The image size has to be 100kb or lower.</p>
    </div>
    </div>

JS code:

$('#edit-image-upload-wrapper input').prepend('onchange="readURL(this);"');

due to this JS code input tag has been changed as follows:

<input type="file" name="files[image_upload]" class="form-file required" id="edit-image-upload" size="60">onchange="readURL(this);"</input> 

I want to change as follows:

 <input type="file" name="files[image_upload]" class="form-file required" id="edit-image-upload" size="60" onchange="readURL(this);"></input> 

How can I do this?

Upvotes: 0

Views: 738

Answers (2)

T.J. Crowder
T.J. Crowder

Reputation: 1074138

In general, to add (or update) an attribute to an element, you can use attr:

$('#edit-image-upload-wrapper input').attr('onchange', 'readURL(this);');

As that attribute is reflected as a property, prop would also work:

$('#edit-image-upload-wrapper input').prop('onchange', 'readURL(this);');

However, as you're using jQuery, I can't see any good reason for doing this as opposed to using proper event hookup, such as:

$('#edit-image-upload-wrapper input').on('change', function() {
    readURL(this);
});

And if you can change the readURL function so that it gets the URL from this rather than from its first argument, that can be simpler:

// Requires small change to `readURL`
$('#edit-image-upload-wrapper input').on('change', readURL);

Side note 1: Your input has its own id value (edit-image-upload), so those selectors could be simply #edit-image-upload, rather than #edit-image-upload-wrapper input.


Side note 2: Your HTML is invalid. input elements are "void" elements, they never have content, and so you never write an ending tag for them. E.g., you never write </input>. Any element that cannot have content (input, br, hr, and a few others) is never written with an end tag.

Upvotes: 2

Ani
Ani

Reputation: 4523

Use this:

$('#edit-image-upload-wrapper input').change(function() {
     //.....
});

Upvotes: 0

Related Questions