简体   繁体   中英

Change content of textarea with jquery/javascript

I am using gridster widgets on my webpage.Each widgets have multiple images on it and a textarea.The textarea contains the links of image seperated by comma.The initial content of textarea is achieved from JSON.The images can be deleted from the grid.I want to update the content of text area as the images are deleted from the grid.(If I delete and image the link of that image from text area should go away).As of now I am getting a static content in the textarea.

My JS to delete the image and an attempt to remove the content of textarea

$('.removediv').on('click', function () {
    var textArea = $(this).parent().next();
    var text   = textArea.val();
  var imgSrc = $(this).prev().attr("src");
  textArea.val(text.replace(imgSrc, ""));

$(this).closest('div.imagewrap').remove();


});

But the above code is not capable of making the textarea dynamic.It only works when there is just one image.

My function which generate the widgets

for(var index=0;index<json.length;index++) {
    var images = json[index].html.split(',');
        var imageOutput = "";

        for(var j = 0; j < images.length; j++) {
        imageOutput += '<div class="imagewrap"><img src='+ images[j] +'> <input type="button" class="removediv" value="X" /></div></div>';
        }

gridster.add_widget('<li class="new" ><button class="delete-widget-button" style="float: right;">-</button>' + imageOutput + '<textarea>'+json[index].html+'</textarea></li>',json[index].size_x,json[index].size_y,json[index].col,json[index].row);
}

Fiddle will illustrate properly.In Fiddle if you go on deleting the image the text are content remains same.I want it to change.

You should just put the "serialize" code in a function and call that function whenever an element is deleted:

$('.removediv').on('click', function() {
    var textArea = $(this).parent().next();
    var text = textArea.val();
    var imgSrc = $(this).prev().attr("src");
    textArea.val(text.replace(imgSrc, ""));
    $(this).closest('div.imagewrap').remove();
    serialize();
});

$('.js-seralize').on('click', function() {
    serialize();
});

function serialize(){
    var s = gridster.serialize();
    $('.gridster ul li').each((idx, el) => { // grab the grid elements
        s[idx].html = $('textarea', el).html(); // add the html key/values

        json_variable = JSON.stringify(s)
    });
    $('#log').val(json_variable);
}

Fiddle

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM