How can I use jQuery to append something to the value of a form element, as opposed to changing it?

筅森魡賤 提交于 2020-01-04 04:30:19

问题


I know how to do this in basic JS:

document.getElementById("someTextarea").value += "stuff";

Note the + - I'm adding to the value, not completely changing it. How would I do that using jQuery's val()?


回答1:


$('#foo').val($('#foo').val() + 'something');

(Of course you can and should cache the element).

Another way (very jQuery style):

$('#foo').val(function(){
    return this.value + "something";
});



回答2:


$('#someTextarea').val(function(i, v){ return v + 'stuff'; });



回答3:


Since an ID selector will return a unique element you can avoid val if you want:

$('#foo')[0].value += ' stuff';



来源:https://stackoverflow.com/questions/11302658/how-can-i-use-jquery-to-append-something-to-the-value-of-a-form-element-as-oppo

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!