简体   繁体   中英

Jquery event click html() only works once

I have a function that when clicking on the element should enter a textarea value, but the function works only by clicking once and then does not work anymore, unless loading the page. How to make the function work every time I click on the element?

I made the function in javascript, but this only works in Firefox and does not work in chrome, so I gave up and tried jquery

$("#element").click(function(){
    $("#nameidtextarea").html("<br>");
});

It was expected that when clicking on #element the value "<'br'>" will be inserted into the textarea

The HTML content of a textarea element is the default value, so using it will only change the value if it hasn't been changed by the user.

Do not use html() to modify the value of a form control. Use val() .


You are currently setting the value to <br> . That's a replace action, not an insert action.

If you want to insert the data and not erase the existing data, then you will need to read the current value, modify it, then set the new value back.


$("#element").click(function(){
    const old_value = $("#nameidtextarea").val();
    const new_value = old_value + "<br>";
    $("#nameidtextarea").val(new_value);
});

Thanks everyone!

$("#nameidtextarea").val($("#nameidtextarea").val()+$("#nameidtextarea").html()+"<br>");

Now works for me

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