cssyphus
cssyphus

Reputation: 40096

JS verify form data inside ajax-returned html

Ajax-returned HTML includes a table and a submit button (type=button)

The table includes jQuery routine to clone table row (each row allows choosing/uploading one file, and has two values: <input type="text"> for doc title, and <input type="file">.

<table id="MyTable">
<tr name="tr3" id="tr3">
    <td>
        <input type="text" name="dt[]" id="dt1">
    </td>
    <td>
        <input type="file" name="fff[]" id="ff1">
    </td>
</tr>
</table>
<input type="button" name="sub1" id="sub1" value="Submit" onclick="checkform();">

Upon form submit, I must check that each doc title has been filled-in, so the submit button calls a javascript routine:

function checkform()
{
    if(document.updateprojectdocs.dt[0].value=='')
    {
        alert("Fields marked with an asterisk are required.");
        document.updateprojectdocs.dt[0].focus();
        return;
    }

    document.getElementById("TheForm").submit();
}

Of course, this does not work (script dies before form submit -- but submits if I remove the preceeding if structure). Can anyone tell me why and how to fix?

Also, there will be an indeterminate number of dt[] fields to check. How could I structure a loop to do this? I suspect jQuery's .find().each() could be used, but not sure what that would look like?


UPDATES:

Thanks to DaHaKa's response below, I am closer to a solution. I mod'd DaHaKa's suggested code into jQuery.

I was having trouble communicating with DaHaKa - for some reason his responses were not appearing until long, long, long after he posted them (the problem was probably on my end). While I was waiting (hours), I posted part of the problem in another question and ended up resolving it there. That other question grew into the FULL CORRECT ANSWER, and I direct future viewers there. Note that user thecodeparadox created a working JSFiddle of the full solution.

I have awarded this question to DaHaKa as he was more than willing and able to assist, but comm problems intervened. Thanks again, D.

Upvotes: 0

Views: 107

Answers (1)

nanobash
nanobash

Reputation: 5500

In this case jQuery each function isn't neccessary, you can do it simple like this =>

try

<table id="MyTable">
<tr name="tr3" id="tr3">
    <td>
        <input type="text" name="dt" id="dt1">
    </td>
    <td>
        <input type="file" name="fff" id="ff1">
    </td>
</tr>
</table>

<input type="button" name="sub1" id="sub1" value="Submit">

JavaScript

document.getElementById("sub1").onclick = function(){
    if (document.getElementById("dt1").value!=""){
        document.getElementById("TheForm").submit();
    } else {
        alert("Empty Field(s) !");
    }
};

you should use ids in JavaScript from html tags , NOT NAME tags

And whats about you file input , you could understand it from your server side scripting language like php , with super global variables $_FILES['file']['error'] types

Upvotes: 1

Related Questions