简体   繁体   中英

Adding text to input box with jquery

I have an element on the page that looks like:

<textarea id="note-content" rows="4"></textarea>

when I try to write some jQuery to add some text to it:

$('#note-content').val('hi')

The button to "submit" the value is still greyed out.

在此处输入图像描述

I've tried

function setKeywordText(text) {
    var el = document.getElementById("note-content");
    el.value = text;
    var evt = document.createEvent("Events");
    evt.initEvent("change", true, true);
    el.dispatchEvent(evt);
}

setKeywordText("test")

as a way to "simulate" sending keystrokes to the browser, but that doesn't seem to work either.

any thoughts?

You can do that by javascript

<script>
function changetext(){
document.getElementById("note-content").value = "hi";
}
<script>

It should def. work. Plus what exactly did you mean by browser simulation? Am i missing something?

It appears this problem is occurring because your button is disabled .

To solve this you'd remove the disabled attribute using jQuery.fn.removeAttr , like this:

$("#button-id").removeAttr("disabled");

Add this solution it to your vanilla JavaScript code, like this:

function setKeywordText(text) {
  // disable button
  var btn = document.getElementById("button-id");
  btn.disabled = false;
  // set input value
  var el = document.getElementById("note-content");
  el.value = text;
  // create and dispatch the event
  var evt = document.createEvent("Events");
  evt.initEvent("change", true, true);
  el.dispatchEvent(evt);
}

// run the function
setKeywordText("test");

Good luck.

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