Set Value of Input Using Javascript Function

谁说胖子不能爱 提交于 2019-11-26 03:34:02

问题


I\'m currently using a YUI gadget. I also do have a Javascript function to validate the output that comes from the div that YUI draws for me:

Event.on(\"addGadgetUrl\", \"click\", function(){
    var url = Dom.get(\"gadget_url\").value;  /* line x ------>*/
    if (url == \"\") {
        error.innerHTML = \"<p> error\" /></p>\";
    } else {
        /* line y ---> */ 
        /*  I need to add some code in here to set the value of \"gadget_url\" by \"\" */
    }
}, null, true);

Here is my div:

<div>
<p>URL</p>
<input type=\"text\" name=\"gadget_url\" id=\"gadget_url\" style=\"width: 350px;\" class=\"input\"/>
<input type=\"button\" id=\"addGadgetUrl\" value=\"add gadget\"/>
<br>
<span id=\"error\"></span>
</div>

As you can see my question is, how can I set the value of gadget_url to be \"\"?


回答1:


Try... for YUI

Dom.get("gadget_url").set("value","");

with normal Javascript

document.getElementById('gadget_url').value = '';

with JQuery

$("#gadget_url").val("");



回答2:


document.getElementById('gadget_url').value = '';



回答3:


The following works in MVC5:

document.getElementById('theID').value = 'new value';



回答4:


Depending on the usecase it makes a difference whether you use javascript (element.value = x) or jQuery $(element).val(x);

When x is undefined jQuery results in an empty String whereas javascript results in "undefined" as a String.




回答5:


I'm not using YUI, but in case it helps anyone else - my issue was that I had duplicate ID's on the page (was working inside a dialog and forgot about the page underneath).

Changing the ID so it was unique allowed me to use the methods listed in Sangeet's answer.




回答6:


document.getElementById('gadget_url').value = 'your value';




回答7:


Try

gadget_url.value=''

gadget_url.value = ''

function set() {
   gadget_url.value = 'cool gadget';
}
<div>
  <p>URL</p>
  <input type="text" name="gadget_url" id="gadget_url" style="width: 350px;" class="input" value="some value" />
  <input type="button" id="addGadgetUrl" value="add gadget" onclick="set()" />
  <br>
  <span id="error"></span>
</div>


来源:https://stackoverflow.com/questions/5700471/set-value-of-input-using-javascript-function

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!