开发者

Accessing live value of a DOM element

I have a hidden input that has a default value, which can be changed depending on the value of the selected radio button associated with it.

So, if I select the second radio button, the js_file_path hidden input will have its value changed to "/shared". Nice and easy, and I've got this to work fine.

My problem is when I try to get js_file_path's value via jQuery $("#js_file_path").val(), I always get the value of the hidden field when the page was loaded. How do I get its current value instead? I know of the live() handler and its purpose, but not quite sure how to make use of it in this context where I'm trying to pass "js_file_path"'s value as a function 开发者_StackOverflow社区argument.

Any help is appreciated.

EDIT:

This is the code to detect the value of the file path has changed.

<input type="hidden" id="js_local_file_path" value="local">
<input type="hidden" id="js_shared_file_path" value="shared">
<input type="radio" name="js_type_for_file_upload" value="local" checked>
<input type="radio" name="js_type_for_file_upload" value="shared">
<input type="hidden" id="js_file_path" value="local">

$("[name=js_type_for_file_upload]").live( "change", function(){
    switch( $(this).val() ){
        case "local":
            $("#js_file_path").val( $("#js_local_file_path").val() );
            // do other stuff
        break;
        case "shared": 
           $("#js_file_path").val( $("#js_shared_file_path").val() );
            // do other stuff
        break;
    }
});`

So, when I select the second radio button and check the DOM I can see that the js_file_path's value has been changed to "shared" correctly.

I then try to proceed and make a function call that includes the value of js_file_path as its argument when a button with an id "button" is clicked.

$("#button").click( function(){ 
     a_name_of_a_function( $("#js_file_path").val() ); 
});

For debugging, I put an alert prompt inside a_name_of_a_function() to output its file_path's parameter's value.

function a_name_of_a_function( file_path ){
    alert( file_path );
    // other stuff
}

Even if I've selected the "shared" radio button, the alert prompt will always displays "local".


Based off your example HTML, you shouldn't even need to do a switch:

$("input[name=js_type]").live( "change", function(){
    $("#js_file_path").val( $(this).val() );
});

Working example: http://jsfiddle.net/AlienWebguy/2JrWM/2/ -- I simply changed the hidden field to a text field so you could see it in action without looking at the console.

EDIT: This is the updated code on the fiddle. Works fine:

$("input[name=js_type_for_file_upload]").live( "change", function(){
    $("#js_file_path").val( $(this).val());

});

$('#button').live('click',function(){
    alert($("#js_file_path").val());
});
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜