2016-08-19 38 views
3

我有ID #image_tag_list_tokens的text_field并出现文本框作为图像形式如下:如何使用Javascript或ajax实时地在文本字段中注入或添加输入字段的值?

= f.text_area :tag_list_tokens, label: "Tags (optional) ->", data: {load: @image_tags }, label: "Tags" 

我有一个输入字段和一个按钮如下:

<input type="text" name="myNewTag" id="my_new_tag"> 
<button name="meNewTagButton" type="button" id="createMy_new_tag">Create new tag</button> 

当用户键入在输入字段中添加一个新标签,我想要抓住该新标签并将其添加到tag_list_tokens的文本区域中,而无需重新加载页面。在tag_list_tokens文本字段的值是以下格式:

"old_tag1,old_tag2,'new_tag1','new_tag2'" 
+0

仅供参考 - 如果您发布呈现的HTML而不是你的轨道.erb模板,它通常是更有帮助:) – larz

回答

1

// add event listener for button click 
 
$("#createMy_new_tag").on("click", function(){ 
 
    // get the text in the input 
 
    var new_tag = $("#my_new_tag").val(), 
 
    // grab the textarea 
 
     textarea = $("#image_tag_list_tokens") 
 
    // append the input to the current text 
 
    textarea.val(textarea.val() + ", " + new_tag) 
 
    // reset the input 
 
    $("#my_new_tag").val("") 
 
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> 
 
<textarea id="image_tag_list_tokens">blah</textarea> 
 
<input type="text" name="myNewTag" id="my_new_tag"> 
 
<button name="meNewTagButton" type="button" id="createMy_new_tag">Create new tag</button>

相关问题