Friday, May 17, 2024
 Popular · Latest · Hot · Upcoming
112
rated 0 times [  118] [ 6]  / answers: 1 / hits: 37620  / 12 Years ago, sat, march 31, 2012, 12:00:00

I'm trying to take user form input and display it back to the user, among other things (all of which require the input being stored as a JS variable).



I'm trying to spit it out in an alert, as a quick feedback loop, and all I keep getting is [object HTMLInputElement]. I've tried to use document.forms[0] and document.getElementById (like below) and neither work. Also, I'm using bootstrap typeahead, could that be complicating this issue?



What am I missing?



Here's the code:



<div class=hero-unit>
<h1> Title </h1>
<p> This form description </p>
<form class=well name=formInput action= #>
<label>Input</label>
<input Id=txtvarInput class=span3 style=margin: 0pt auto; type=text placeholder=AAA, BBB, CCC... data-provide=typeahead data-items=10 data-source=[&quot;AAA&quot;,&quot;BBB&quot;,&quot;CCC&quot;,&quot;DDD&quot;,&quot;EEE&quot;,&quot;FFF&quot;,&quot;GGG&quot;,&quot;HHH&quot;,&quot;III&quot;,&quot;JJJ&quot;,&quot;KKK&quot;,&quot;LLL&quot;]/>
</label>
<div class=form-actions span3>
<input name=submit type=submit class=btn value=Select onclick=alert('you chose ' + theInput.value)/>
<script language=JavaScript type=Text/JavaScript>
var theInput = document.getElementById('txtvarInput');
</script>
</div>
</form>
</div>

<div class=page-header>
<h1>Input:
<script language=JavaScript type=Text/JavaScript>
document.write(theInput.value);
</script>
</h1>


Edit: PART II, now the code works for the alert, but I need to use it elsewhere (like I said) and the variable isn't available in other sections of the html. Above, I'm just trying to get it to display that same value as a part of the html. It could be my JS, but this is pretty boilerplate stuff, so I think it's related to the location of the variable.



What do I need to do use it elsewhere? I've added the next div above to show what I'm trying.



--left an extra declaration of the variable in part II by accident, was one of the tests I was trying, removed now.


More From » html

 Answers
10

Right now, the object you're alerting is an HTML element, not a string. You can get its value using the value property:



alert('you chose ' + theInput.value)





(Note that you probably didn't mean:



var theInput = document.getElementById('txtvarInput').value;


As other answers suggest, because that would give you an empty string. It's only read once.)


[#86485] Friday, March 30, 2012, 12 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
jackie

Total Points: 442
Total Questions: 107
Total Answers: 94

Location: Honduras
Member since Sun, Dec 26, 2021
2 Years ago
jackie questions
Sat, Sep 18, 21, 00:00, 3 Years ago
Wed, Jul 14, 21, 00:00, 3 Years ago
;