Ryan Salmons
Ryan Salmons

Reputation: 1459

Need to store input value to variable on change

I am trying to store the value of an input into a variable. For now, I want to just paste the input value into a span element so I can know that it works. However I cannot get it work in my JSFIDDLE. Any suggestions?

HTML:

<label>Advertising Budget:</label>
                <input id="advertising" onchange="updateAdvertising(this.value)">  </input>
<span id="test">xxx</span>

Javascript:

function updateAdvertising(adv){
    document.getElementById('test').innerText = adv;
}

JSFIDDLE: http://jsfiddle.net/6J4MN/

Upvotes: 0

Views: 1888

Answers (2)

mplungjan
mplungjan

Reputation: 177860

innerHTML is more compatible, also change fiddle to head instead of onload

Here is a neater solution

Live Demo

window.onload=function() { 
  document.getElementById("advertising").onchange=function(){
    document.getElementById('test').innerHTML = this.value;
  }
}

Since onchange needs a blur to trigger, use onkeyup for immediate change:

Live Demo

window.onload=function() { 
  document.getElementById("advertising").onkeyup=function(){
    document.getElementById('test').innerHTML = this.value;
  }
}

Upvotes: 3

Newse
Newse

Reputation: 2338

Note the "OnChange" event for the text box will fire once you hit enter or leave the text box. If you change the event to, say keyup, it will update the span after every letter you type.

<script type='text/javascript'>//<![CDATA[ 
  window.onload=function(){

    function addEvent(element, evnt, funct){
       if (element.attachEvent)
         return element.attachEvent('on'+evnt, funct);
       else
         return element.addEventListener(evnt, funct, false);
    };

    addEvent(document.getElementById('advertising')
        , 'change'
        , function () { updateAdvertising(this.value); }
    );

   var updateAdvertising = function(adv){
      document.getElementById('test').innerText = adv;
   };
 };
</script>

Upvotes: 1

Related Questions