0

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/

3
  • Change the select drop down for execution time to 'no wrap - in <head>' Fiddle Commented Feb 18, 2014 at 21:15
  • @Bic what exactly is that doing? It works, but I just want to know what it is doing so I can implement it. Commented Feb 18, 2014 at 21:19
  • 1
    You had it set to onLoad, which means your method isn't defined until AFTER the page has loaded and the onclick has been bound. When the page loads, the onclick method doesn't exist, and therefore nothing gets bound. If you have it wrap in the head, the content will get loaded BEFORE the page renders, ensuring the method exists at the time of binding. Commented Feb 18, 2014 at 21:20

2 Answers 2

3

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;
  }
}
Sign up to request clarification or add additional context in comments.

Comments

1

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>

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.