Set Value of Input Using Javascript Function

772,813

Solution 1

Try... for YUI

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

with normal Javascript

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

with JQuery

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

Solution 2

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

Solution 3

The following works in MVC5:

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

Solution 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.

Solution 5

document.getElementById('gadget_url').value = 'your value';
Share:
772,813

Related videos on Youtube

Ali Taha Ali Mahboub
Author by

Ali Taha Ali Mahboub

Updated on April 24, 2022

Comments

  • Ali Taha Ali Mahboub
    Ali Taha Ali Mahboub about 2 years

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

    • Sangeet Menon
      Sangeet Menon about 13 years
      Try...Dom.get("gadget_url").set("value","");...I'm not quite sure though
  • qbantek
    qbantek about 8 years
    javascript != MVC5
  • Matthew Nichols
    Matthew Nichols about 8 years
    And yet he gave the correct answer. There are newbies that will find this question based on this answer.
  • Pogrindis
    Pogrindis almost 8 years
    Just for brevity and future reference, all id's on the page should ALWAYS be unique
  • Kamil Kiełczewski
    Kamil Kiełczewski over 4 years
    @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
  • Timo
    Timo about 3 years
    goodForm.coolinput.value='foo', is not possible, why cant I use it instead of addressing the input directly by id`? Wait, here..