2

My program should contain both name search and ID search functionality, when user clicks the name search button, a name search validation is triggered to make sure that the required text field is not empty, on the other hand, when user clicks the id search button, an id search validation is triggered to make sure that a different required text field is not empty. So on the HTML file, I have the following jQuery and HTML codes.

    $(document).ready(function() {
        $('#submitIDSearch').bind('click', validateIDSearch);
        $('#submitNameSearch').bind('click', validateNameSearch);
        $('#searchLastName').bind('click', validateNameSearch);
        $('#searchFirstName').bind('click', validateNameSearch);
        $('#searchID').bind('click', validateIDSearch);
    });

    var validateNameSearch = function(event) {
        var btnSrchLastName = getRef('searchLastName');
        if (null != btnSrchLastName) {
            var len = btnSrchLastName.value.length;
            if (0 == len) {
                alert('Last Name is a required field, please input Last Name.');
                $('#searchLastName').focus();
                return false;
            }
        }
        return true;
    }

    var validateIDSearch = function(event) {
        var btnSrchID = getRef('searchID');
        if (null != btnSrchID) {
            var len = btnSrchID.value.length;
            if (0 == len) {
                alert('ID is a required field, please input ID.');
                $('#searchID').focus();
                return false;
            }
        }
        return true;
    }

And I have the following HTML code:

    <form id="infoForm" name="checkAbsenceForm" method="post" action="absenceReport.htm">
        <label class="q">ID * <input id="searchID" name="searchID" maxlength="9" /></label>
        <input id="submitIDSearch" type="submit" value="Search ID"/>
        <hr />
        <label class="q">First Name <input id="searchFirstName" name="searchFirstName" maxlength="23"></label>
        <br />
        <label class="q">Last Name * <input id="searchLastName" name="searchLastName" maxlength="23" /></label>
        <input id="submitNameSearch" type="submit" value="Search Name"/>
        <hr />
    </form>

The code behaves correctly except for one problem, when ever the user clicks on the textbox, a click event is fired, which cause a pre-generation of the alert message box.

I observed that when the user types 'enter' key from a text field, a click event is triggered, instead of 'submit', so I guess my listener can only be bind to the click event.

May I ask if there's a workaround method to avoid event triggering from mouse clicking on the textbox?

Thanks a lot!

ssgao
  • 5,151
  • 6
  • 36
  • 52
  • I believe what you looking for is `change` event or form `submit` event and not `click` – Selvakumar Arumugam Oct 15 '12 at 19:52
  • Thanks a lot for the answer. Yes I am expecting for submit event, but when the user types enter, the event that is fired is **click**, so even if I listen to submit event, I will never be able to catch it. Also, change event is not a good fit as well. My validation code is only expected to execute when the user is trying to submit the form. – ssgao Oct 15 '12 at 19:57
  • See my answer below.. that would be one way of doing it.. – Selvakumar Arumugam Oct 15 '12 at 20:10

3 Answers3

1

You can use the submit event from the form, so it will check every time someone submits the form. jQuery - Submit

$('#infoForm').submit(function (event){
    if (!validateIDSearch() && !validateNameSearch()){
        event.preventDefault(); // Prevent the submit event, since didn't validate
    }
    // Will continue to the dafault action of the form (submit it)
});
jaxkodex
  • 484
  • 2
  • 6
  • 17
  • Thanks a lot for the answer. I have two buttons there, one for name search and another for id search, so when a submit event is fired, I want to be able to find out which element has fired it so that I can pop up different alert messages in response. If I do manipulation on form element in general. How may I find out which element has fired the event? – ssgao Oct 15 '12 at 20:03
  • The submit event is unique for the form and you cannot know which button submitted it. Look [here](http://stackoverflow.com/questions/3577469/form-onsubmit-determine-which-submit-button-was-pressed) <- Nice way to fix that. The proposal was to run both validators and there will be pop up for each validation – jaxkodex Oct 15 '12 at 20:19
  • Thanks for the direction, but the button itself is not the problem, my binding handler solution can accomplish it as well, but when it comes to button and text field, then both solution fails to work. – ssgao Oct 15 '12 at 20:29
  • Yeah, Kind of already new that, that's why you have to call the function that is set as the ´submitActor()´ wich will call the validation function according to the button that was clicked. Kind of similar to the other answer, diference is that I found it in the web... – jaxkodex Oct 15 '12 at 20:42
  • The jsfindle does not works because you are blocking the event ´event.preventDefault();´ and calling the submit again so it will never send the form and will go into a loop (submit calls submit again) – jaxkodex Oct 15 '12 at 20:47
  • so I removed the line, but this time it does not have validation property at all: http://jsfiddle.net/aaFyP/6/ – ssgao Oct 15 '12 at 20:53
  • let us [continue this discussion in chat](http://chat.stackoverflow.com/rooms/18074/discussion-between-hydrology-and-jaxkodex) – ssgao Oct 15 '12 at 21:09
1

In case you still need help... http://jsfiddle.net/jaxkodex/Cphqf/

$(document).ready(function() {

    $('#submitNameSearch').click(function(event) {
        event.preventDefault();
        if (validate($('#searchLastName'), 'Last name field is required.')) {
            $('#infoForm').submit();
        }
    });

    $('#submitIDSearch').click(function(event) {
        event.preventDefault();
        if (validate($('#searchID'), 'ID field is required.')) {
            $('#infoForm').submit();
        }
    });
});

function validate(input, errorMsg) {
    if (input.val() == null || input.val().length == 0) {
        alert(errorMsg);
        return false;
    }
    return true;
}

Since you are using jQuery, You can submit the form whenever a button is clicked with $('#infoForm').submit(); If you check you'd need to use button inputs and no submit inputs any more, since they will trigger the submit event. This is just one approach. If you are looking for live validation, you could use the blur events instead of click but in the text inbut and the click event to the buttons to make sure it works. I guess that overwritting the submit function would work when you have to do some ajax. Hope it helps.

[Edit] If you want to keep the buttons as submit you can do some thing like: http://jsfiddle.net/jaxkodex/S5HBx/1/

jaxkodex
  • 484
  • 2
  • 6
  • 17
  • Thanks a lot for the help, yes I am still looking for the solution. The second example is exactly what I want, except one problem, I added id for the textboxes in the selector, so, when I leave the 'searchLastName' empty and type 'enter' from the 'searchLastName' text field trying to submit the form, what I expect is an alert box shows up with message: 'Last name field is required.'. However, the message that shows up is instead: 'ID field is required.' Could you please help me figure out a solution for this? Thanks – ssgao Oct 17 '12 at 02:18
  • Cann't find the question where some people dicussed that, how ever they got to the conclusion that a submitted form with the `enter` key will submit the data with the first input button that is loaded - thereby it will always send it with that button. You can add a handler for the keyup event on each input so that it will determinate wich validation you need and after submit the form. – jaxkodex Oct 17 '12 at 13:04
0

You just need to set what button the user has selected and do validation based on that during form submit.

searchLastName searchFirstName submitNameSearch are calling validateNameSearch, and submitIDSearch searchRUID are calling validateIDSearch

 $(function () {

    var validateFx = null; //none selected;

    $('#submitNameSearch, #searchLastName, #searchFirstName')
        .bind('click', function () {
           validateFx = validateIDSearch;
        });
    $('#searchIDSearch, #searchRUID')
       .bind('click', function () {
         validateFx = validateNameSearch;
       });

    $('#infoForm').submit(function (event){
         event.preventDefault();

         if (validateFx != null && validateFx ()) {
            $(this).submit();
         }
    });
});
Selvakumar Arumugam
  • 79,297
  • 15
  • 120
  • 134
  • thanks a lot for your reply. I found a small mistake of assigning `validateNameSearch` and `validateIDSearch` function in your code, and I fixed it. However, when I type `enter` key in the `searchLastName` textbox, mysteriously, the function that's triggered is validateIDSearch function and I got a alert message "ID is a required field, please input ID.". May I ask why would this happen? – ssgao Oct 15 '12 at 20:19
  • @hydrology What did you fix? The `searchLastName` is calling the `validateIDSearch` search isn't it? – Selvakumar Arumugam Oct 15 '12 at 20:24
  • `searchLastName` `searchFirstName` `submitNameSearch` are calling `validateNameSearch`, and `submitIDSearch` `searchRUID` are calling `validateIDSearch` – ssgao Oct 15 '12 at 20:27
  • @hydrology I have updated the answer based on what you mentioned in the comment... – Selvakumar Arumugam Oct 15 '12 at 20:30
  • I created a jsfiddle page here: http://jsfiddle.net/aaFyP/2/, but so far the code still doesn't behave as it should – ssgao Oct 15 '12 at 20:42