Setting Events for similar fields in HTML using JQuery, and Javascript - javascript

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 class="container-fluid">
<div class="row">
<div class="col-10">
<!-- Clock-In Header -->
<h3>
<img class="logo large" 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 class="row">
<div class="col-1 col-md-12 offset-md-0">
<div class="card">
<div class="card-body">
<form asp-action="ClockInBegin" method="post">
<label for="JobNumber" class="col-7 col-md-2 col-form-label text-md-right">Job Number</label>
<div class="col-md-4">
<input type="text" id="JobNumber" name="JobNumber" class="form-control" onkeydown="jobNumberKeyDown(this)" onblur="jobNumberBlur(this)" value="#Model.TrackingItem.JobNumber">
<div class="col-md-8">
<span id="jobNumberValidationMessage"></span>
</div>
</div>
</div>
<div class="form-group row">
<div class="form-check form-switch col-4 align-with-label">
<input class="form-check-input" type="checkbox" value="" id="MultipleCheck">
<label class="form-check-label" for="MultipleCheck">Multiple</label>
</div>
</div> <!-- End form-group row -->
<div>
<button type="submit" class="btn btn-primary w-100">Start Clock</button>
</div>
</form>
</div>
</div>
</div>
</div>
<!-- Clock-In Modal Pop-up -->
<div class="modal fade" id="myModal">
<div class="modal-dialog modal-dialog-scrollable">
<div class="modal-content">
<div class="modal-header">
<h4 class="modal-title">Select Job Number</h4>
<button type="button" class="close" data-dismiss="modal">×</button>
</div>
<div class="modal-body">
<select id="jobNumberSelect" class="form-control">
<option value="">Select Job Number</option>
<!-- Dynamic options generated via JavaScript or ajax -->
</select>
</div>
<div class="modal-footer">
<button type="button" id="CANCEL"class="btn btn-secondary" data-bs-dismiss="modal">Cancel</button>
<button type="button" id="OK" class="btn btn-primary" 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>

if you have mutipule inputs like:
<input type="text" id="JobNumber1" name="JobNumber1" class="form-control"  value="1">
<input type="text" id="JobNumber2" name="JobNumber2" class="form-control"  value="2">
<input type="text" id="JobNumber3" name="JobNumber3" class="form-control"  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:

Related

In a popup, how do I add a file to the ajax submit and stay in the popup for the results of the backend?

I found setting the title a bit awkward, it's complicated to exaplain in 1 sentence.. Some of our pages use popups where the user can fill in fields and then send. This is based on some Kallyas stuff and works fine with just text fields. After submitting, user staus on the same page, the form stays open and in it the message appears that the form has been sent (or not). There is also recaptcha handling in it.
Now I need to give the possibility to upload a file and this is where I am stuck. There is a .js file that does the handling. It picks up the form and does a ajax submit. I can see the form field of my input type="file" here, but with a fakepath/empty. If, in this javascript I try to append the file to the form I can submit, but the the backend says the form field is not there.
First, let me share the code.
The form :
<!-- Application form pop-up element content -->
<div id="application_panel" class="mfp-hide contact-popup">
<div class="contact-popup-panel">
<div class="container-fluid">
<div class="row">
<div class="col-md-12 col-sm-12">
<!-- Application form pop-up element -->
<div class="applicationForm pop-up-form" style="padding:50px;">
<!-- Title -->
<div id="jatitlewrapper">
<h3 class="m_title m_title_ext text-custom contact-popup-title c_title">
Some title
</h3>
<h4 class="tbk__subtitle fw-thin dark">
</h4>
</div>
<form id="appform" action="#request.projectname#/scripts/ajax/save/processform.cfm" method="post" class="contact_form row mt-40" enctype="multipart/form-data">
<div id="jafldwrapper">
<div class="col-sm-6 kl-fancy-form">
<input type="text" name="firstname" id="cf_firstname-pop-up" class="form-control" placeholder="Vul hier je voornaam in" value="" tabindex="1" required>
<label class="control-label">
VOORNAAM
</label>
</div>
<div class="col-sm-6 kl-fancy-form">
<input type="text" name="lastname" id="cf_lastname-pop-up" class="form-control" placeholder="Type je achternaam in" value="" tabindex="1" required>
<label class="control-label">
ACHTERNAAM
</label>
</div>
<div class="col-sm-12 kl-fancy-form">
<input type="text" name="place" id="cf_place-pop-up" class="form-control" placeholder="Voeg een onderwerp toe" value="" tabindex="1" required maxlength="78">
<label class="control-label">
WOONPLAATS
</label>
</div>
<div class="col-sm-12">
<label class="label_upl">
UPLOAD FILE
</label>
<input id="resume" style="padding-bottom:15px;" type="file" name="resume" id="cf_subject-pop-up" class="" placeholder="" value="" tabindex="1">
</div>
<cfif Application.isProductionURL>
<div class="col-sm-12" style="margin-left:15px;">
<div class="g-recaptcha" data-sitekey="somesitekey"></div>
</div>
<div class="col-sm-6">
<!-- Contact form send button -->
<button id="submitbtn" class="btn btn-fullcolor" type="submit" onClick="$('.g-recaptcha-response').attr('name','g_recaptcha_response');">
Send
</button>
</div>
<cfelse>
<div class="col-sm-6">
<!-- Contact form send button -->
<button id="submitbtn" class="btn btn-fullcolor" type="submit">
Send
</button>
</div>
</cfif>
<div class="col-sm-6" style="text-align:right;">
<button class="btn btn-fullcolor" type="button" onClick="closePopup();">
Cancel
</button>
</div>
</div>
<input type="hidden" name="fjobuuid" id="fjobuuid" value="">
</form>
</div>
<!--/ Application form pop-up element -->
</div>
<!--/ col-md-12 col-sm-12 -->
</div>
<!--/ .row -->
</div>
<!--/ .container -->
</div>
<!--/ .contact-popup-panel -->
<button title="Sluiten (Esc)" type="button" class="mfp-close">×</button>
</div>
<!--/ Application form pop-up element content -->
Some javascript for the popup to show :
window.onload = function() {
$('.abutton').magnificPopup({
closeBtnInside: true,
type: 'inline',
preloader: false
});
}
The standard js that handles the sumbit and works with all text fields on the form :
if(typeof($('.applicationForm form, .applicationForm.pop-up-form form, .contact_form form')) != 'undefined') {
$.each($('.applicationForm form, .applicationForm.pop-up-form form, .contact_form form'), function(index, el) {
var cform = $(el),
cResponse = $('<div class="cf_response col-sm-12"></div>');
cform.prepend(cResponse);
cform.h5Validate();
cform.submit(function(e) {
$('#g-recaptcha-response').attr('name','g_recaptcha_response');
e.preventDefault();
if(cform.h5Validate('allValid')) {
cResponse.hide();
$.post(
$(this).attr('action'),
cform.serialize(),
function(data){
console.log(data);
cResponse.html(data).fadeIn('fast');
if(data.match('success') != null) {
cform.get(0).reset();
}
}
); // end post
}
return false;
});
});
}
The backend does some handling of the fields and then produces a message, which is then visible in the popup :
<cfoutput><div class="alert alert-success alert-dismissible" role="alert"><p>Message sent, thank you</p></div></cfoutput>
or a message with class alert-danger if something went wrong.
Now I tried adding the file field 'resume' to the form by adding a cform.append, right after the cform.submit :
var files = $("#resume")[0].files;
for (var i = 0; i < files.length; i++) {
cform.append(files[i].name, files[i]);
}
It does loop and seems to append the file.
But the backend says form.resume is not there.
I tried writing my own submit :
$("#submitbtn").on("click", function(e) {
var form = $("#appform");
var params = form.serializeArray();
var files = $("#resume")[0].files;
var formData = new FormData();
for (var i = 0; i < files.length; i++) {
formData.append(files[i].name, files[i]);
}
$(params).each(function (index, element) {
formData.append(element.name, element.value);
});
$.ajax({
type: "POST",
url: $(form).prop("action"),
data: formData,
processData: false,
error : function (xhr, ajaxOptions, thrownError) {
alert(xhr.status);
alert(thrownError);}
,
success : function(data){
console.log(data);
}
});
})
Then the backend has all fields needed, including the actual file. But then I don't know how to integrate staying on the same url with the popup still in place and the message from the backend in the right place.
Then I tried changing the button type from sumbit to button, but then it won't let me send the file with the ajax call.
$.ajax({
type: "POST",
url: 'proctname//scripts/ajax/save/processform.cfm',
data: formData,
processData: false,
contentType: false,
error : function (xhr, ajaxOptions, thrownError) {
alert(xhr.status);
alert(thrownError);}
,
success : function(data){
var obj = $.parseJSON( data );
console.log(data);
}
});
Giving form field 'resume' is undefined. Apparently it needs to be a form submit.
Can I add the file field 'resume' to the standard code after the cform.submit, keep page and popup open, have the message handling etetc and if so, how?

How to fetch and display selected value into <select2> tag in my Edit Form using ajax (codeigniter)

I create one form which includes select2 control.and i have data in database.
Now I want to fetch value of particular data value into select2 control when edit the form. My selected select value is store in one variable Now i want that value dispaly in select2 control inside the edit form and i dont know how ..
here is my edit form code:
<div id="editm" class="modal fade" tabindex="-1" role="dialog">
<div class="modal-dialog modal-sm" role="document">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">×</span></button>
<h4 class="modal-title">Update Rayon</h4>
</div>
<div class="modal-body">
<form id="validate1" method="POST">
<div class="form-group">
<label class="control-label">Kode Rayon</label>
<div>
<input type="text" class="form-control" id="edit_Kode_rayon" name="edit_Kode_rayon" placeholder="Kode Rayon" readonly>
</div>
</div>
<div class="form-group">
<label class="control-label">Nama Rayon</label>
<div>
<input type="text" class="form-control" id="edit_nama_rayon" name="edit_nama_rayon" placeholder="Nama Center" >
</div>
</div>
<div class="form-group">
<label class="control-label">Nama Region</label>
<div>
<!-- HERE IS THE SELECT2 THAT IM TALKING ABOUT.. -->
<select class="form-control kode_region" id="nRegionE" name="kode_region" style="width: 100%;">
<option value=""></option>
</select>
</div>
</div>
</form>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
<button type="button" id="update" class="btn btn-primary">Update</button>
</div>
</div>
</div>
here is jquery code for edit button:
$(document).on("click", "#edit", function(e){
e.preventDefault();
var editid = $(this).attr("value");
$.ajax({
url: "<?php echo base_url();?>Rayon/editdata",
type: "POST",
dataType: "json",
data:{editid: editid},
success: function(data){
if(data.responce == "success"){
$('#editm').modal('show');
$("#edit_Kode_rayon").val(data.posts.kode_rayon);
$("#edit_nama_rayon").val(data.posts.nama_rayon);
//$("#nRegionE").val(data.posts.kode_region);<-- I TRIED LIKE THIS .. NOT WORK -->
//$("#nRegionE").select2().select2('val',data.posts.kode_region);<-- I TRIED LIKE THIS . NOT WORK-->
$('#nRegionE').val(data.posts.kode_region).trigger("change");<-- EVEN THIS ONE IS NOT WORK -->
}else{
toastr["error"](data.message);}
}
});
});
and here is my Select2 script that im using it for inssert and my edit form:
$(function () {$('.kode_region').select2({
//placeholder: "Please select region",allowClear: true,
ajax: {
dataType: 'json',
url: '<?=site_url('Bonus/nregion')?>',
type: "post",
delay: 250,
data: function(params) {
return {search: params.term}},
processResults: function (data, page) {
return {results: data};
},
}
})});
just to make it clear i took a screenshot of my edit form:
all what i want is to fetch the value of data into select2 form control of Edit Form .. can anyone help me to do that ? n i'll be so thankful.
You are fetching options list correctly in data.posts.kode_region,
then update this line
$("#nRegionE").val(data.posts.kode_region);
to this
$("#nRegionE").html('<option value = "'+data.posts.kode_region+'" selected >'+data.posts.kode_region+'</option>');
and don't forget to comment this line
$('#nRegionE').val(data.posts.kode_region).trigger("change");
I am dam sure this will work for you
$("select#nRegionE option").val("hello"); //Change hello string to your record Id
$("select#nRegionE option").html(data.posts.kode_region);

Already sucess to add select form dyamically , but the data from success ajax cannot be send to the new select form

I'm trying to make a dependent dropdown, and it already works.
The problem is, the user want the second dropdown (in a different div) to be added dynamically but when we try to add a new dropdown, the new dropdown doesn't show any data when I choose value from first dropdown.
How to make the new dropdown contain data from ajax?
P.S: the option value is in another html where the ajax call the html if it succeeds.
This is the html:
$(document).ready(function() {
$("#dataselect").change(function() {
var urls = "{% url 'polls:load-column' %}";
var column = $(this).val();
$.ajax({
url: urls,
data: {
'column': column
},
success: function(data) {
$("#columnselect").html(data);
},
error: function(data) {
alert("error occured");
}
});
});
});
function appendBox() {
$('#test').append('<select id ="columnselect" style="width:425px;background-color:white;height:30px;font-color:red;text-align-last:center;"></select>')
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="form-group">
<label class="control-label col-md-3">Table Name</label>
<div class="col-md-4">
<div class="input-group bootstrap-timepicker">
<div class="btn-group">
<select id="dataselect" style="width:425px;background-color:white;height:30px;font-color:red;text-align-last:center;">
</select>
</div>
</div>
</div>
</div>
<div class="form-group">
<button class="btn btn-theme" onclick="appendBox()">Add</button>
<label class="control-label col-md-3">Column Name</label>
<div class="col-md-4" id="test">
<div class="input-group bootstrap-timepicker">
<div class="btn-group">
<select id="columnselect" style="width:425px;background-color:white;height:30px;font-color:red;text-align-last:center;">
</select>
</div>
</div>
</div>
</div>

btn-next is not working when given inside a v-if and else condition?

I am using vue js and html for my project and i am doing a registration. So, I have few tabs. For going to next-tab "btn-next" is the class needed. But, i need to move to next tab only if the json response i receive is true.
So, i modified my html as
<div class="wizard-footer">
<div class="pull-right">
<div v-if="response.status == false">
<button type="submit" class='btn btn-primary'>Submit Again</button></div>
<div v-if="response.status == true">
<button type="submit" class='btn btn-next btn-primary'>Next</button></div>
<div v-else>
<button type="submit" class='btn btn-primary'>Submit</button>
</div>
</div>
</div>
But when I try this way.. i am not able to move to the next tab? can anybody please help me to have a solution..
I am able to get response and move through the different conditions but i am not able to move to next tab. it means btn-next is not working when i give inside div. So, please help me to find out a solution.
My detailed code is
<div class="tab-pane" id="step2">
<form method="POST" id="form1" v-on:submit.prevent="handleSubmit($event);">
<div class="row p-b-15 ">
<div class="row">
<div class="col-sm-12">
<div class="col-sm-6">
<div class="form-group">
<label>Contact Name :</label>
<input name="cname" type="text" class="form-control" id="cname" placeholder="Contact Name" required="required" v-model="cname" />
</div>
</div>
</div>
</div>
<div class="wizard-footer">
<div class="pull-right">
<div v-if="response.status == false"><button type="submit" class='btn btn-next btn-primary'>Next</button></div>
<div v-if="response.status == true"><button type="submit" class='btn btn-next btn-primary'>Next</button></div>
<div v-else>
<button type="submit" class='btn btn-primary'>Next</button>
</div>
</div>
</div>
</div>
</form>
</div>
My vue js code
submitBox = new Vue({
el: "#submitBox",
handleSubmit: function(e) {
var vm = this;
data = {};
data['name'] = this.cname;
data['pid'] = this.pid;
$.ajax({
url: 'hpost/contact/',
data: data,
type: "POST",
dataType: 'json',
success: function(e) {
if (e.status) {
vm.response = e;
console.log(vm.response);
alert("Registration Success")
} else {
vm.response = e;
console.log(vm.response);
alert("Registration Failed")
}
}
});
return false;
},
Case 1:
If the buttons are rendered correctly, please check your web server's backend code. I find that you are rendering a form with two "submit" buttons, maybe the backend does not know which submit is your expectation.
when response.status == false: Submit Again and Submit are rendered
when response.status == true: Next is rendered
but they are all normal submit buttons, does your backend or handleSubmit know that?
Case 2:
If the buttons are not rendered correctly, please check your JSON structure and vue syntax.

How To pass the modified data from dual listbox to controller?

I have created a form with two listboxes in which it is possible to move the items from one listbox into another.
The view also loads correctly, but I haven't figured out how to send the modified listbox data back to controller.
The view code is the following:
<script>
$(function() {
$(document)
.on("click", "#MoveRight", function() {
$("#SelectLeft :selected").remove().appendTo("#SelectRight");
})
.on("click","#MoveLeft", function() {
$("#SelectRight :selected").remove().appendTo("#SelectLeft");
});
});
#Html.Hidden("RedirectTo", Url.Action("UserManagement", "Admin"));
<h2>User</h2>
<div class="container">
<form role="form">
<div class="container">
<div class="row">
<div class="col-md-5">
<div class="form-group">
<label for="SelectLeft">User Access:</label>
<select class="form-control" id="SelectLeft" multiple="multiple" data-bind="options : ownership, selectedOptions:ownership, optionsText:'FirstName'">
</select>
</div>
</div>
<div class="col-md-2">
<div class="btn-group-vertical">
<input class="btn btn-primary" id="MoveLeft" type="button" value=" << " />
<input class="btn btn-primary" id="MoveRight" type="button" value=" >> " />
</div>
</div>
<div class="col-md-5">
<div class="form-group">
<label for="SelectRight">Owners:</label>
<select class="form-control" multiple="multiple" id="SelectRight" multiple="multiple" data-bind="options : availableOwners, selectedOptions:availableOwners, optionsText:'FirstName'">
</select>
</div>
</div>
</div>
</div>
</form>
</div>
<script>
var data=#(Html.Raw(Newtonsoft.Json.JsonConvert.SerializeObject(Model)));
var selectedOwners = #Html.Raw(Newtonsoft.Json.JsonConvert.SerializeObject(ViewBag.AccessOwners));
var availableOwners = #Html.Raw(Newtonsoft.Json.JsonConvert.SerializeObject(ViewBag.Owners));
function viewModel() {
this.username=ko.observable(data.Username);
this.password=ko.observable(data.Password);
this.email=ko.observable(data.Email);
this.isActive=ko.observable(data.IsActive);
this.userId = ko.observable(data.UserId);
this.ownership=ko.observableArray(selectedOwners);
this.availableOwners = ko.observableArray(availableOwners);
this.submit = function()
{
$.ajax({
url: '#Url.Action("UserSave", "Admin")',
type: 'POST',
data: ko.toJSON(this),
contentType: 'application/json',
});
window.location.href = url;
return false;
}
this.cancel = function()
{
window.location.href = url;
return false;
}
};
ko.applyBindings(new viewModel());
var url = $("#RedirectTo").val();
I would be very thankful if anyone could suggest the way to pass all the selected options back to controller by populating the data with modified lists when the submit function is executed.
Thanks!
Before form submission save one side items values in an hidden input element. (comma separated values of listbox items.) The value of hidden element is sent to server by submitting the form. In controller you can do the next things.

Categories