Home > Software design >  Setting Events for similar fields in HTML using JQuery, and Javascript
Setting Events for similar fields in HTML using JQuery, and Javascript

Time:02-03

I am not really good at the HTML world, and I'm not even sure how to debug this one. Anyway, I have an ASP.NET core App. My issue is in a CSHTML view. It is a timeclock system. User logs time against an existing job.

I have an Index.cshtml that is working. It will verify a JobNumber to make sure it exists in the database. And if the user enters a partial number and hits F3, it pops up a modal window (I'm using Bootstrap 5) to allow them to select from a list.

The problem is, the user wants to add more Job numbers. So, they can clock time against up to five Jobs at once. So, I am creating new fields, and naming them JobNumber2, JobNumber3, etc.

What I want to do is reuse the existing scripts to add the verification and popup functionality to each of the new fields.

I have tried several different things based on a half a dozen tutorials out there, but I am just not good enough at Javascript and JQuery to know how to do this.

Any help is appreciated!

[EDIT] Ruikai Feng's answer shows how to match the first function, but that one calls validateJobNumber(jobNumber), and the result will update a field -- again based on the same pattern. So, now it updates: jobNumberValidationMessage -- but I need it to update the correct jobNumberValidationMessage depending on which JobNumber field got matched in the first half of this. IDK, maybe these could be combined into one function? I'm not sure. But how do I take what I matched with id^='JobNumber to figure out which jobNumberValidationMessage to update (ie jobNumberValidationMessage2, jobNumberValidationMessage3, etc) ;

------------ END EDIT

Here's the code I have that is working, but needs changed:

@using Microsoft.AspNetCore.Http
@using Microsoft.AspNetCore.Http.Extensions
@model dynamic

<!DOCTYPE html>
<html>

<body>
    <div >
        <div >
            <div >
                <!-- Clock-In Header -->
                <h3>
                    <img  src="logo-png-transparent.png")"
                         alt="Logo" width="100" height="100">  Add Job Number(s) to Track Time for: @Model.Employee.Name
                </h3>
                <hr />  <!-- Ruler Line for Separation -->
                <!-- End Clock-In Header -->
            <!-- Clock-In Form -->
        <div >
        <div >
            <div >
            <div >
             <form asp-action="ClockInBegin" method="post">
            <label for="JobNumber" >Job Number</label>
            <div >
            <input type="text" id="JobNumber" name="JobNumber"  onkeydown="jobNumberKeyDown(this)" onblur="jobNumberBlur(this)" value="@Model.TrackingItem.JobNumber">
            <div >
                <span id="jobNumberValidationMessage"></span>
            </div>
            </div>
          </div>
          <div >
          <div >
            <input   type="checkbox" value="" id="MultipleCheck">
            <label  for="MultipleCheck">Multiple</label>
          </div>
         </div> <!-- End form-group row -->
          <div>
            <button type="submit" >Start Clock</button>
          </div>
        </form>
        </div>
        </div>
        </div>
        </div>
        <!-- Clock-In Modal Pop-up -->
        <div  id="myModal">
            <div >
            <div >
            <div >
            <h4 >Select Job Number</h4>
            <button type="button"  data-dismiss="modal">&times;</button>
        </div>
        <div >
        <select id="jobNumberSelect" >
        <option value="">Select Job Number</option>
        <!-- Dynamic options generated via JavaScript or ajax -->
        </select>
        </div>
        <div >          
            <button type="button" id="CANCEL" data-bs-dismiss="modal">Cancel</button>
            <button type="button" id="OK"    data-bs-dismiss="modal">OK</button>                
        </div>
        </div>
    </div>
    <!-- End Clock-In Modal Pop-up -->
    </div>
    </div>
   </div>
  </div>
<script>

    $(document).ready(function () {
        $("#JobNumber").blur(function () {
            var jobNumber = $(this).val();
            validateJobNumber(jobNumber);
        });
        $("#JobNumber").keydown(function (event) {
            if (event.key === "F3") {
                event.preventDefault();
                if (event.target.value.length >= 2) {
                    // Open the modal
                    $('#myModal').modal('show');
                    // Populate the select options
                    $.ajax({
                        type: "GET",
                        url: "@Url.Action("GetJobNumbers")",
                        data: { searchTerm: event.target.value },
                        dataType: "json",
                        success: function (data) {
                            $("#jobNumberSelect").empty();

                            $.each(data, function (index, item) {
                                $("#jobNumberSelect").append("<option value='"   item   "'>"   item   "</option>");
                            });
                            $("#jobNumberSelect").val("..."); // clear the initial value. Make them select it
                            //set prompt in first cell of select
                            $("#jobNumberSelect").prepend("<option value=''>Select Job Number</option>");
                            $("#myModal").modal("show");
                        }
                    });
                }
            }
        });
        $("#jobNumberSelect").change(function () {
            $("#JobNumber").val($(this).val());
        });
        $("#OK").click(function () {
            $("#JobNumber").val($("#jobNumberSelect").val());
            validateJobNumber(); // call the validation
            $("#myModal").modal("hide");
        });

        $('#MultipleCheck').change(function () {
            if (this.checked) {
                $(this).val(true);
                $('[name="MultipleCheck"]:hidden').val(true);
                $("#hiddenFields").show();
            }
            else {
                $(this).val(false);
                $("#hiddenFields").hide();
            }
        })

    });  // end Document.Ready functions

    function validateJobNumber() {
        var jobNumber = $("#JobNumber").val();
        $.ajax({
            type: "POST",
            url: "@Url.Action("VerifyJobNumber")",
            data: { jobNumber: jobNumber },
            dataType: "text",
            success: function (respdata) {
                // alert(respdata);
                const obj = JSON.parse(respdata);
                var rmessage = obj.message;
                $("#jobNumberValidationMessage").text(rmessage);
                $("#jobNumberValidationMessage").css("color", "green");
            }
        });
    }
</script>


</body>
</html>

CodePudding user response:

if you have mutipule inputs like:

<input type="text" id="JobNumber1" name="JobNumber1"   value="1">
<input type="text" id="JobNumber2" name="JobNumber2"   value="2">
<input type="text" id="JobNumber3" name="JobNumber3"   value="3">

and you want validate the value on blur ,just try as below:

$("[id^='JobNumber']").blur(function(e)        
{             
var jobnumber=$(this).val();             
$.ajax({               
 type: "POST",               
 url: "@Url.Action("VerifyJobNumber")",               
 data: { "jobNumber": jobnumber },               
 dataType: "text",                
success: function (respdata) {                     
alert(respdata);                                  
 }            
});        
});

With a controller :

[HttpPost]       
public IActionResult VerifyJobNumber(string jobNumber)        
{            
  return Ok(jobNumber);        
}

The result:

enter image description here

  • Related