jQuery .attr('value', 'new_value') not working?

前端 未结 11 1886
面向向阳花
面向向阳花 2020-12-10 04:56

I am trying to dynamically change the actual HTML value attribute of an input using jQuery. Although using input.attr(\'value\', \'myNewVal\'); wor

相关标签:
11条回答
  • 2020-12-10 05:48

    Don't use .attr() to change the value, use .val(), which was made specifically for this purpose:

    input.val("new value");
    
    0 讨论(0)
  • 2020-12-10 05:49

    That's because the developer tools do not refresh. This is a well known bug in these tools, including Opera's, Safari's as well as Firebug's (the latter one being a different issue).

    As far as I know, you can right-click the source tree window and hit "refresh". This doesn't refresh the page, just the source view. This "fix" doesn't work in firebug though.

    0 讨论(0)
  • 2020-12-10 05:49

    It won't change the value in the DOM explorer of most development tools. But JavaScript will still get the current values. So

    var newValue = 'new';
    $(sel).val(newValue);
    newValue == $(sel).val(); // true
    
    0 讨论(0)
  • 2020-12-10 05:52

    I have a case in which jQuery function .val() and .attr("value", "...") works incorrect for value with url. Functions update the user interface but it doesn't effect with DOM(source). In this case should be used:

    jQueryObj[0].setAttribute("value", "...");
    

    It's right for jQuery v1.5.* => v1.6.*, for another versions it's not be checked.

    0 讨论(0)
  • 2020-12-10 05:52

    This may be slightly off topic, but I have found that when I use the .data() function in jQuery, the value is set correctly, but the change isn't reflected in developer tools.

    So,

    $('#element').data('to-update', 'newValue')
    

    In the developer tools (Elements view) still shows the old value.

    But

    $('#element').data('to-update')
    

    returns 'newValue'

    0 讨论(0)
提交回复
热议问题