Reputation: 445
This will be a silly question, just trying to figure my way around Javascript functions interacting with HTML forms and can't get it to work.
Extremely simple, put it in a fiddle
$('#test').submit(function(){
var battery = $('#battery').value();
$('#output').text(battery);
});
<form id="test" action="">
<fieldset>
<label for="battery">Cell Count</label><br />
<input type="number" size="3" name="battery" id="battery" /><br />
<input type="submit" name="submit" id="submit" onclick="submit()" />
</fieldset>
</form>
<div id="output">
</div>
Always returns an error and I can't figure out why. Have played around with and other things, can't get it to work always error.
Upvotes: 4
Views: 3217
Reputation: 1
The correct function is val() no value() in jquery.
By using the method .submit keep in the "return false" to not run the "action" of the "form" that you have not considered.
<script type="text/javascript" src="jquery.js"></script>
<script type="text/javascript">
$(document).on('ready', function() {
$('#test').submit(function(){
var battery = $('#battery').val();
$('#output').text(battery);
return false;
});
})
</script>
If you are using jQuery, you do not need the onclick="submit()" argument in the input object
<form id="test" action="#">
<fieldset>
<label for="battery">Cell Count</label><br />
<input type="number" size="3" name="battery" id="battery" /><br />
<input type="submit" name="submit" id="submit"/>
</fieldset>
</form>
<div id="output"></div>
regards
Upvotes: 0
Reputation:
I'm not sure if this is correct, but I think your javascript code looks like php, and there's nothing in the action=""
field in the quotes. Also, I think that value should be val.
Upvotes: 0
Reputation: 12010
If you use proper developer tools (for example Firebug in Firefox) then you could easily figure out the problem here as in the console it would have shown you something like :
Uncaught TypeError: Object [object Object] has no method 'value'
Which means that there is no value
method and val()
is what should be used instead.
Upvotes: 1
Reputation: 53198
jQuery's function for returning the value of an input
element is val()
, not value()
. Your code should be:
$('#test').submit(function(){
var battery = $('#battery').val();
$('#output').text(battery);
});
<form id="test" action="">
<fieldset>
<label for="battery">Cell Count</label><br />
<input type="number" size="3" name="battery" id="battery" /><br />
<input type="submit" name="submit" id="submit" onclick="submit()" />
</fieldset>
</form>
<div id="output">
</div>
Upvotes: 1
Reputation: 5050
To retrieve values from inputs using jQuery you need to use .val()
Change:
var battery = $('#battery').value();
to:
var battery = $('#battery').val();
Upvotes: 0
Reputation: 413720
The error is probably that .value()
isn't a function. You want .val()
.
Upvotes: 4