Marcus
Marcus

Reputation: 4490

Jquery val() always grabs first select value no matter which is selected

I'm using Jquery to allow users to upload an image via Ajax in a form (the image uploads before the form is actually submitted). I've added the ability to add a watermark to each image that is uploaded (this is done in upload_image.php) this part works fine.

The user can select where they want the watermark to be placed on their image via a form select. I'm using Jquery's .val() to grab the value of the id="watermark" select and add it as a query string value to be passed to upload_image.php.

The problem is that it always passes the first select value no matter what I actually select in the form. I tried putting it in a function (thought it was grabbing the value on page load) no luck there. I changed the select to radio buttons. It still grabs the value of the first radio button on the page; no matter what you select.

Here is the portion of the script that handles this:

<script type="text/javascript" >
$(function(){

    // build URL to php upload script with watermark placement
    function setWatermark() {
        var uploadUrl = 'http://www.mysite.com/upload_image.php?w=';
        var watermarkValue = $('#watermark').val();
        var watermarkUrl = uploadUrl + watermarkValue;
        return watermarkUrl;
    }

    var btnUpload=$('#upload');
    new AjaxUpload(btnUpload, {
        action: setWatermark(),
        name: 'uploadfile',
    });

});
</script>

This is the form (with irrelevant fields removed):

<form id="image_form" action="this_form.php" method="post" enctype="multipart/form-data">
    <select id="watermark">
        <option value="top_left">Top Left</option>
        <option value="top_right">Top Right</option>
        <option value="center">Center</option>
        <option value="bottom_left">Bottom Left</option>
        <option value="bottom_right">Bottom Right</option>
    </select>
    <div id="upload" ><span><img src="upload_button.jpg" /></span></div>
</form>

Upvotes: 0

Views: 646

Answers (1)

icktoofay
icktoofay

Reputation: 129139

To execute this code:

new AjaxUpload(btnUpload, {
    action: setWatermark(),
    name: 'uploadfile',
});

The browser must first construct the arguments to pass to the constructor. To construct the second argument, the object, it must call setWatermark to get the value for the action property. This is where your problem is; setWatermark is being called when the AjaxUpload object is created.

I don't know what AjaxUpload is, but you'll have to find a way to get it to call a function when it needs the action rather than it being provided as a constant in the options.

Upvotes: 5

Related Questions