SitePoint Sponsor

User Tag List

Results 1 to 4 of 4
  1. #1
    SitePoint Zealot
    Join Date
    Dec 2008
    Posts
    156
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)

    [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

    Code:
    <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?

  2. #2
    SitePoint Wizard bronze trophy
    Join Date
    Jul 2008
    Posts
    5,757
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    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()

  3. #3
    SitePoint Zealot
    Join Date
    Dec 2008
    Posts
    156
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Thanks, it's clearer now!
    Code:
    <script type="text/javascript">
    $(document).ready(function(){
    	$("#form1").submit(function(){
    		if ($("#textfield").val() != '') {
    		return confirm("Are you sure?");
    		}
    	});
    });
    </script>
    Or
    Code:
    <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?

  4. #4
    SitePoint Wizard bronze trophy
    Join Date
    Jul 2008
    Posts
    5,757
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    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.


Bookmarks

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •