Reputation: 117
I am trying to validate a form's input value after clicking a button using jQuery and javascript.
Right now, if I put in a value for the input and click submit the input field and button just disappears. Any idea what I have wrong here?
The HTML file...
<!DOCTYPE html>
<html>
<head>
<title></title>
<link/>
<script type='text/javascript' src='script.js'></script>
</head>
<body>
<form>
<input type="text" id='input_1'>
<input type="submit" value="Send" id="send">
</form>
</body>
</html>
The script file...
$(document).ready(function() {
$('.send').click(function() {
validateInput(document.getElementById('#input_1'));
function validateInput(inputValue){
if (inputValue === 3) {
alert("Element cannot be equal to 3");
}
}
});
});
Upvotes: 0
Views: 169
Reputation: 117
Thank you all for your responses. Unfortunately, I wasn't able to get it to work using your recommendations. I decided to use jQuery to get the element and appended a message to a div instead of using alert. This was a different approach but ended up working.
HTML...
<!DOCTYPE html>
<html>
<head>
<title></title>
<link/>
<script type="text/javascript" src="script.js"></script>
</head>
<body>
<form>
<input type="text" name="input"/>
</form>
<button id="send">Send</button>
<div class="error">
</div>
</body>
</html>
SCRIPT...
$(document).ready(function() {
$('#send').click(function(){
var toValidate = $('input[name=input]').val();
if (toValidate == 3) {
jQuery('.message').html('');
$('.error').append('<div class="message">' + toValidate + " is invalid" + '</div>');
}
else {
jQuery('.message').html('');
$('.error').append('<div class="message">' + toValidate + " is valid" + '</div>');
}
});
});
Upvotes: 0
Reputation: 11984
$(document).ready(function() {
$('#send').live('click',function() { //Because send is the id of your button
if(validateInput(document.getElementById('#input_1'))){
alert("Element cannot be equal to 3");
return false;
}
else{
//Do something else
}
function validateInput(inputValue){
if (inputValue == 3) {
return false;//Will prevent further actions
}
}
});
});
Upvotes: 1
Reputation: 363
$('.send').click(function() {
should be $("#send").click(function() {
.
Notice the Hash symbol and not the dot (.), dot is used if the selector is a class whereas the # is used if the selector is an ID. 2.You should move the validation function outside the $(document).ready(function()
.. Hope that helps
Upvotes: 0