[jQuery] confirm on submit only if a textfield is not empty

Hallo,
I’m moving my firts steps in jQuery (and anyway JavaScript I’m not so good…)
I have a form with a text field: on submit, if field is not empty, I’d like to show a simple confirm box (Ok-Cancel)

Here’s my code: the confirm box appears even the textfield is empty


<form id="form1" method="post" action="untitled.asp">
  <input type="text" name="textfield" id="textfield" />
  <input type="submit" name="button" id="button" value="Submit" />
</form>
....
<script type="text/javascript">
$(document).ready(function(){
	$("#form1").submit(function(){
		if ($("#textfield").value != '') {
		return confirm("Are you sure?");
		}
	});
});
</script>

Please, any help?

The $() function does not return a dom element, it returns a jQuery object. jQuery objects don’t have a value attribute. They do have some methods to work with attributes of dom elements though. http://docs.jquery.com/Attributes like val()

Thanks, it’s clearer now! :slight_smile:


<script type="text/javascript">
$(document).ready(function(){
	$("#form1").submit(function(){
		if ($("#textfield").val() != '') {
		return confirm("Are you sure?");
		}
	});
});
</script>

Or


<script type="text/javascript">
$(document).ready(function(){
	$("#form1").submit(function(){
		if ($("#textfield").attr("value") != '') {
		return confirm("Are you sure?");
		}
	});
});
</script>

It works both ways, but what is the best? Or, what is the difference between them?

val() includes special functionality for select menus. Aside from that, I believe them to be the same. I prefer typing val() over attr(‘value’) as it’s short and concise.