嗨,我正在努力实现以下目标:
1) 用户单击文件输入按钮,文本字段将替换为文件名
2) 用户更改文本字段的值,文件内容被删除..
这很好用。但是,如果用户在执行 2) 操作后执行 1) 操作,则值将不再显示在文本字段中。
这是在 Backbone 上使用 CoffeeScript ..
events:
'change #soundfile': 'soundReceived'
'change #soundtrack': 'linkInput'
soundReceived: (event) ->
$('#soundtrack').html($('#soundfile').val().replace("C:\\fakepath\\", ''))
@
linkInput:(event) ->
match = $('#soundtrack').val().match('http://')
if match
$('#soundfile').replaceWith($("#soundfile").clone());
console.log($('#soundfile').val())
else
console.log($('#soundfile').val())
$('#soundtrack').html($('#soundfile').val().replace("C:\\fakepath\\", ''))
@
编辑
<div id = "create_form" >
<form class="new_plot" name="create_form" id ="new_plot" data-remote="true" enctype="multipart/form-data">
<div id = "sound_gen">
<span>
<textarea class="input" id="soundtrack" name="name" rows="1" onClick="if(this.value == 'Soundtrack: upload mp3 file') { this.value = ''; }">Soundtrack: upload mp3 file</textarea>
</span>
<img id = "btn_upload" src ="/assets/upload_icon.png"></img>
<input name="soundtrack" type="file" id ="soundfile"/>
<span class ="generate">
<input class="blue_button btn_generate" name="commit" type="submit" value="create" id ="plot_subm"/>
</span>
</div>
</form>
</div>
最佳答案
您应该使用 val
更改表单元素的值,而不是 html
,例如:
soundReceived: (event) ->
$('#soundtrack').val($('#soundfile').val().replace("C:\\fakepath\\", ''))
@
尝试更改 <input type="file">
的值通过脚本通常是没有意义的(希望原因显而易见),但您可以尝试使用 .val(...)
如果你愿意的话。
精简演示:http://jsfiddle.net/ambiguous/5n6aZ/
此外,您可能应该使用 placeholder
属性而不是您的 onClick
您的 <textarea>
中的处理程序.
关于Javascript/Jquery .html() 仅替换一次,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12519478/