Jquery function triggers on page load instead of button click. Trying to send selection options to post controller

I have a <select> element in a c# file in an mvc project I am building. I want to send the items added to the select box to the post action when the user clicks the “submit” button. The problem is that the function is triggering when the page is loaded instead of when the submit button is clicked. The function does not trigger when the submit button is clicked either. So the tagvalues are not being passed to the post. Is anyone able to tell me why this is? Thank you. The Jquery code is contained in a seperate file to the create post file.
Edit: I added the full file and took out the codebyte block as they are not working.

Js file:

let index = 0;

function AddTag() {
    // get a reference to the tagentry input element
    var tagEntry = document.getElementById("TagEntry")

    //create a new select option
    let newOption = new Option(tagEntry.value);
    document.getElementById("TagList").options[index++] = newOption;

    //clear out the TagEntry control
    tagEntry.value = "";
    return true;
}

function DeleteTag() {
    var tagEntry = document.getElementById("TagEntry")
    let tagCount = 1;
    while (tagCount > 0) {
        let selectedIndex = document.getElementById("TagList").selectedIndex;
        if (selectedIndex >= 0) {
            document.getElementById("TagList").options[selectedIndex] = null;
            --tagCount;
        }
        else 
            tagCount = 0;
            index--;
    }
}

$("form").on("submit", function (){
    $("#TagList option").prop("selected", "selected");
})

Creat Post file:


@{
    ViewData["Title"] = "Create";
}

<h1 class="text-center">Create</h1>

<h4 class="text-center">Post</h4>
<hr />
<div class="row justify-content-center">
    <div class="col-md-4">
        <form asp-action="Create" enctype="multipart/form-data">
            <div asp-validation-summary="ModelOnly" class="text-danger"></div>

            <div class="form-group">
                <label asp-for="BlogId" class="control-label"></label>
                <select asp-for="BlogId" class="form-control" asp-items="ViewBag.BlogId"></select>
            </div>

            <div class="form-group">
                <label asp-for="Title" class="control-label"></label>
                <input asp-for="Title" class="form-control" />
                <span asp-validation-for="Title" class="text-danger"></span>
            </div>
            <div class="form-group">
                <label asp-for="Abstract" class="control-label"></label>
                <textarea asp-for="Abstract" class="form-control"></textarea>
                <span asp-validation-for="Abstract" class="text-danger"></span>
            </div>
            <div class="form-group">
                <label asp-for="Content" class="control-label" id="Content"></label>
                <input asp-for="Content" class="form-control"></input>
                <span asp-validation-for="Content" class="text-danger"></span>
            </div>
            <div class="form-group">
                <label asp-for="ReadyStatus" class="control-label"></label>
                <select asp-for="ReadyStatus" asp-items="@Html.GetEnumSelectList<ReadyStatus>()" class="form-control"></select>
                <span asp-validation-for="ReadyStatus" class="text-danger"></span>
            </div>
            <div class="form-group">
                <label asp-for="Image" class="control-label"></label>
                <input type="file" asp-for="Image" class="form-control" accept=".jpg, .png, .gif, .jpeg />
                <span asp-validation-for="Image" class="text-danger"></span>
            </div>

            <div class="form-group mt-4">
                <div class="row">
                    <div class="col">
                        <label class="control-label">Manage Tags</label>
                    </div>
                </div>

                <div class="row">
                    <div class="col">
                        <div class="row">
                            <div class="col">
                                <input type="text" class="form-control" id="TagEntry" />
                            </div>
                        </div>
                        <div class="row mt-2">
                            <div class="col align-bottom">
                                <button onclick="AddTag()" name="Add" type="button" class="btn btn-dark btn-md btn-block">Add</button>
                            </div>
                            <div class="col align-bottom">
                                <button onclick="DeleteTag()" name="Delete" type="button" class="btn btn-dark btn-md btn-block">Delete</button>
                            </div>
                        </div>
                    </div>

                    <div class="col">
                        <select name="TagValues" id="TagList" style="width:100%" multiple></select>
                    </div>
                </div>
            </div>

           <div class="form-group">
                <button type="submit" value="Create" class="btn btn-dark btn-md btn-block" 
                 style="border-radius: 10px;">Create</button>
           </div>
        </form>
    </div>
</div>

@section Scripts
        {
         <script src="~/js/Custom.js"></script>
        }

Difficult to say without seeing the full code, my guess would be that you included the javascript/jquery files first.

a html file reads from top to bottom, so if the <script> tags are first, $("form") tries to find the element, but it hasn’t been rendered

jquery offers document ready to help you with this

I have removed all code from the Js file and left just the following method in it:

$(document).ready(function () {
$(“form”).on(“submit”, function () {
$("#TagList").prop(“selected”, “selected”);
})
}

This code never actually triggers at all, so the data is never passed to the post.
If i adjust the method to exclude the .ready function so it looks like this:

$(“form”).on(“submit”, function () {
$("#TagList").prop(“selected”, “selected”);
})

The above triggers on page load and therefore is useless.

And you did include jquery? This project is much bigger then the original post indicated, so difficult to say. Do you host the project on github or something so we can see?

thanks for your help stetim. No is it’s not hosted on github.
if I just add options to the select field in the html, and hit the submit button
it posts the options that I have selected to the post, but no others.

I want the user to create tags, have those tags added to the select list (which currently works),
then have all those tags submitted along with the other data to the post when the submit button is hit.

So I need some code to make all the options (tags) in the select list selected (highlighted) automatically
when the submit button is hit so they’re posted to the post as the user cannot select them all themselves.

That is what the Jquery code is meant to do:

$(“form”).on(“submit”, function () {
$("#TagList").prop(“selected”, “selected”);
})

But this is not working.
I think there is probably some way to do it with razor, that is what I am searching for now,.
If you know how to approach this, any assistance is appreciated. Thank you.

Also judging from the amount of issues with the one simple issue I posted above in the links, combined with that
Jquery is getting less and less support, I think it is possible that there is some underlying issue that is beyond my control so I should just try to use something besides jquery.

jquery is a library, did you actually include the library? Did you check your console for any errors?

I am also slightly worried about your html code:

                <input type="file" asp-for="Image" class="form-control" accept=".jpg, .png, .gif, .jpeg />

there is a " missing to close your accept attribute

Can’t you just add the tags selected by default:


function AddTag() {
    // get a reference to the tagentry input element
    var tagEntry = document.getElementById("TagEntry")

    //create a new select option
    let newOption = new Option(tagEntry.value, tagEntry.value, true, true);
    
    document.getElementById("TagList").options[index++] = newOption;

    //clear out the TagEntry control
    tagEntry.value = "";
    return true;
}

and simply disable the select to prevent the user tampering with it:

<select name="TagValues" id="TagList" style="width:100%" multiple disabled></select>

jquery was made to solve a problem that no longer exists (cross browser support). I mean, cross browser is still needed by now Javascript does this a lot better then it did a couple years ago

The link scripts are included:

\<script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js">

To add the options selected by default would be ideal stetim, however I need to give the user the chance to delete tags as well, so they have to remain unselected whilst the page is active (so the user can select one tag at a time to delete). I need some way to make the options selected once the submit button is hit so the data is posted to the post controller. So an .on submit function of some sort. I will continue to search.

@tera5693753039 thanks for filling me in.

Well, the moment the submit button is pressed its going to a different page, so you would need to prevent this default behavior:

$("form").on("submit", function (e){
    e.preventDefault();
    $("#TagList option").prop("selected", "selected");
})

then you can use jquery (or just Javascript) for whatever behavior you need

Thanks for the code stetim, it would be nice if I could use it, but I get the same error “Uncaught ReferenceError: $ is not defined” @ the $(“form”) line …so the same problem I was having before. I might try playing around with different ways of including the Jquery for a while to see if i can get lucky. That is definately the source of the Jquery error, as it won’t execute that line. I’ll update here once I get somewhere, or not.

IN REPLY TO stetim94 (I cannot reply here officialy more than twice as I am a new user still so I am doing it in this edit)

Apologies stetim, the paragraph I wrote about the “Uncaught ReferenceError: $ is not defined” console error and associated links were omitted in the edit somehow. i will include the link again below here:
Uncaught ReferenceError: $ is not defined
https://www.tutorialrepublic.com/faq/how-to-fix-dollar-is-not-defined-error-in-jquery.php

I am using the cdn links provided by google (at 2waytutorial dot com) (i have tried others) I tried both the minified file and the uncompressed file.: (I would provide the link but I cannot as I am a new user and therfore restricted to 2 links)

You are only mentioning this now? I asked if you had any errors:

Then jquery is not properly included, make sure the jquery.min.js file is included before you attempt to use jquery

are you using babel?