jeudi 19 mai 2016

Access checkbox through JavaScript and JQuery with their ID

Despite the facts that I have been searching for almost a week now, I couldn't find a way a way to do what I wanted to, so here I am. Here's what I want to do: I have a form that should display file names and a checkbox for each name, allowing the user to select which files he wants to choose. Each checkbox's value is the path of the file it's related to, and each checkbox'ID is its file's directory's path plus a number. In my JavaScript, I try to "build" each ID through a loop and then access my checkbox, but I can't make it work, and I'm starting to get a bit desperate; so i hope that you guys can help me. Here's my cshtml code:

<div class="modal-dialog modal-lg ">
<div class="modal-content">
    @{
        string dir = ""+Path.GetDirectoryName(Model);
        var listFiles = System.IO.Directory.GetFiles(dir);
        var nbFiles = listFiles.Count();


    }
    <div class="modal-header">
        <h4 style="word-wrap:break-word;" class="modal-title">Fichiers contenus dans le répertoire @dir</h4>
        <h3>Nombre de fichiers: @nbFiles</h3>
    </div>

    @{var nb = 0; var idCheck = "";}

    <div class="modal-body">
        <form class="frmMoveFile"> 
            @foreach (var file in listFiles)
            {

                idCheck = "check-"+nb+"-"+dir;
                <div style="border:ridge">
                    <p>
                        <b>Fichier</b> : @Path.GetFileNameWithoutExtension(file) 

                        <b>Extension :</b> @Path.GetExtension(file)

                        <input class="btn btn-primary"  type="checkbox" id=@idCheck value=@file />
                    </p>
                </div>
                nb++;
            }
        <br />
        <br />
        </form>
        <div class="center">
            @{                                                                            
                var idBtnOk =Model;
            }             
            <button value="@dir" class="btnFrmMove">Déplacer fichiers sélectionnés vers l'outbox</button>
            <input class="btn btn-success" type="submit" value="Supprimer log d'erreur">
        </div>
    </div>
</div>

And here is the Javascript code:

<script type="text/javascript">
    $('.btnFrmMove').click(function () {
        var path = $(this).attr("value");
        alert(path);
        for (var i = 0; i < 2; i++){
            var idCheckBox = "check-" + i + "-" + path;
            if ($(idCheckBox).is(":checked")) {
                alert($(idCheckBox).attr("value"));
            }
         }

    })
</script>

Am I missing something ? I haven't done a lot of web development until now so it might be a beginner mistake




Aucun commentaire:

Enregistrer un commentaire