264

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 ""?

Kamil Kiełczewski
  • 85,173
  • 29
  • 368
  • 345
Ali Taha Ali Mahboub
  • 3,271
  • 6
  • 26
  • 25

7 Answers7

576

Javascript

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

jQuery

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

YUI

Dom.get("gadget_url").set("value","");
Jess
  • 23,901
  • 21
  • 124
  • 145
Sangeet Menon
  • 9,555
  • 8
  • 40
  • 58
  • `goodForm.coolinput.value='foo'`, is not possible, why can`t I use it instead of addressing the input directly by `id`? Wait, [here](https://stackoverflow.com/a/42860401/1705829).. – Timo May 14 '21 at 07:18
87
document.getElementById('gadget_url').value = '';
Calum
  • 5,308
  • 1
  • 22
  • 27
  • @Alastair I confirm - that is not using YUI. However OP in title write "Set Value of Input Using Javascript Function" (not YUI function) so answer meet question requirements – Kamil Kiełczewski Sep 16 '19 at 06:38
7

The following works in MVC5:

document.getElementById('theID').value = 'new value';
Bogdan Mates
  • 520
  • 4
  • 8
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.

thug-gamer
  • 355
  • 6
  • 9
2
document.getElementById('gadget_url').value = 'your value';
frianH
  • 7,295
  • 6
  • 20
  • 45
SMD
  • 21
  • 4
1

I'm not using YUI, but 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.

Nimantha
  • 6,405
  • 6
  • 28
  • 69
BSounder
  • 134
  • 9
-5

Shortest

gadget_url.value=''

addGadgetUrl.addEventListener('click', () => {
   gadget_url.value = '';
});
<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" />
  <br>
  <span id="error"></span>
</div>

This is the shortest working solution (JSFiddle).

Kamil Kiełczewski
  • 85,173
  • 29
  • 368
  • 345