HTML validation not working for input field loaded using Jquery - html

I have a form input field loaded by jquery based on user selection but the HTML form validation and even jquery form validation not working for the input field loaded by jquery.
<tr>
<td colspan="2">
<select name="usdtnetwork" required="required" id="usdtnetwork" onChange="getaddressForm()" title="Please select your USDT Network">
<option>::: Choose your USDT Network :::</option>
<option value="ERC20">ERC20 (ETH)</option>
<option value="TRC20">TRC20 (TRON)</option>
<option value="BEP20">BEP20 (BNB)</option>
</select>
</td>
</tr>
<tr>
<td colspan="2">
<div align="left">
<span id="showinputfield"></span>
</div>
</td>
</tr>
This is my jquery (Noticed I tried e.preventDefault() but can't figure what am doing wrong so I commented it out)
<script>
/*$('.thisbuyUSDT').click(function (e) {
var myForm = jQuery( "#catalog_formusdt" );
// html 5 is doing the form validation for us,
// so no need here (but backend will need to still for security)
if ( ! myForm[0].checkValidity() )
{
// bonk! failed to validate, so return true which lets the
// browser show native validation messages to the user
return true;
}
e.preventDefault(); */
function getaddressForm() {
//e.preventDefault();
$("#loaderIcon").show();
jQuery.ajax({
url: "usdt_form_field.php",
data:'usdtnetwork='+$("#usdtnetwork").val(),
type: "POST",
success:function(data){
$("#showinputfield").html(data);
$("#loaderIcon").hide();
},
error:function (){}
});
}
//}
</script>

you have to reset validation on form after add some element (after $("#showinputfield").html(data);) by :
myForm.removeData("validator").removeData("unobtrusiveValidation");
$.validator.unobtrusive.parse(myForm );
if it doesn't work please share complete html and jquery code

Related

MVC - dropdown process ajax call on change function

Not sure what I am doing wrong here but the on change function is not hitting for some reason. I hope someone here can point me in the right direction.
I have a view that has some bootstrap tabs, inside one of those tabs I have a dropdown list. What I want to happen is, when the user selects a year, it make an ajax call to controller, gets the json data and populates a table with the data. Here is my code:
In the View:
<div id="StatementsTab" class="tab-pane fade">
<div class="text-left dash-left-padding dash-right-col-content-billing">
<select class="form-control edi-blue" id="ddlStatements">
<option value="0">VIEW STATEMENTS</option>
<option value="#DateTime.Now.Year">#DateTime.Now.Year STATEMENTS</option>
<option value="#DateTime.Now.AddYears(-1).Year">#DateTime.Now.AddYears(-1).Year STATEMENTS</option>
<option value="#DateTime.Now.AddYears(-2).Year">#DateTime.Now.AddYears(-2).Year STATEMENTS</option>
<option value="#DateTime.Now.AddYears(-3).Year">#DateTime.Now.AddYears(-3).Year STATEMENTS</option>
<option value="#DateTime.Now.AddYears(-4).Year">#DateTime.Now.AddYears(-4).Year STATEMENTS</option>
<option value="#DateTime.Now.AddYears(-5).Year">#DateTime.Now.AddYears(-5).Year STATEMENTS</option>
</select>
<br />
<table id="statementtbl">
<tr>
<td></td>
</tr>
</table>
and the jquery:
$("#ddlStatements").change(function () {
console.log("change function yes");
var yr = $("#ddlStatements").val();
if (yr > 0){
$.ajax({
//var url = '../LabOrder/DeletePatientNoteAttachment?PatientNotes=' + JSON.stringify(yr);
url: '..Members/GetStatements',
data: 'Year=' + yr, // Send value of the drop down change of option
dataType: 'json', // Choosing a JSON datatype
success: function (data) {
console.log("success");
// Variable data contains the data you get from the action method
},
error: function (ex) {
console.log(ex);
}
});
}
});
I am not sure why but the console log is not being hit. Please help...

How to know which command button has been clicked in a form

I have a form which has 3 command buttons. I want to know which command button has been clicked and store the value in a session variable
how to do it.
I am getting empty value in the session variable
<form method="post" name = "theform" >
<table>
<tr>
<td align="left" width="100%">
<input type="submit" name = "button" id ="idbutton1" value="Value1">
</td>
<td align="left" width="100%">
<input type="submit" name = "button" id ="idbutton2" value="Value2">
</td>
<td align="left" width="100%">
<input type="submit" name = "button" id ="idbutton3" value="Value3">
</td>
</tr>
</table>
</form>
Session("type")=Request.Form("button")
You need to check that Request.Form("button") contains a value before assigning it to the session variable, otherwise you will be assigning an empty string value to Session("type") every time the page loads.
if request.form("button") <> "" then Session("type") = Request.Form("button")
you can use this jquery to identify which button you clicked and what is the value of that button :
$( "#idbutton1" ).click(function() {
alert( $("#idbutton1").val() );
});
$( "#idbutton2" ).click(function() {
alert( $("#idbutton2").val() );
});
...
and instead of alert you can save it in your session.
*but this method is not dynamic and not good enough for too many buttons
edited :general mode:
you can get the id and value like this in general:
$( "input[name=button]" ).click(function() {
alert( $(this).attr("id") );
alert($(this).val());
button_value = $(this).val();
});
and if you use c# or Django or anything in your backend you can send the variable to it with ajax and then save it to your session :
.ajax({
type:'GET',
url: '/yourfunction',
data: {'button_value':button_value},
dataType: 'json',
success: function (data) {
// do anything
}
)}
and you can get the variable in your function and save it in Session.

A href go on next page when i click on star rating input

On my page I have a table. In the table there is one td, in which I am showing average rating input. I want when I click on average rating page, the href goes to next page.
Can anyone tell me how it can be possible?
Here is my html, but it doesn't work.
<table>
<tr>
<td><a href='supp_view_screen.php?id=$encrypt_id'><input id='rating-input' type='number' readonly value='".$last_cal."' step='1' class='rating'/></a></td>
</tr>
</table>
Use this code snippet for that :
<table>
<tr>
<td><a href='supp_view_screen.php?id=$encrypt_id' target='_blank'><input id='rating-input' type='number' readonly value='".$last_cal."' step='1' class='rating'/></a></td>
</tr>
</table>
A good rule of thumb is:
If there is no meaningful href, then it's a button
In your case, the element can either be a <button> element, a span, or even an image.
What I'm saying is that using a href here is not correct. What you're better off doing is using an ajax call to get the data from your controller.
$('#rating-input').click(function (e) {
"use strict";
e.preventDefault();
$.ajax({
data: user,
method: 'POST',
url: 'supp_view_screen.php?id=$encrypt_id',
done: function () {
//Do something after its done
},
success: function (data) {
//Append your data to the DOM
},
error: function (xhr, status) {
//Do something on error
}
});
});
preventDefault will need to be used if you are using a <button> inside a <form> or an <input> with the type of submit.

HTML form validation in Apps Script

I am very new to coding and have managed (with some help from friends) to create a form that geo-locates the submitter and writes the values (+coordinate) to a Google Sheet. Where I am having trouble is in the HTML5 REGEX and required validations.
When I click the submit button the REGEX and required validation pop-up windows kick in but unfortunately at the same time, the form data is submitted to the Google Sheet and the data is cleared from the form.
I cannot figure out how to make the validation happen first, and then proceed with the submission instead of both happening simultaneously.
Thank you in advance for your help!
code.gs:
function doGet() {
var html = HtmlService.createTemplateFromFile("test").evaluate()
.setTitle('Engagement Card')
.setSandboxMode(HtmlService.SandboxMode.IFRAME);
return html;
}
function addData(data){
var ss = SpreadsheetApp.openById('1g*********************OnE').getSheetByName('Sheet1');
ss.appendRow(data);
}
test.html
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<link rel="stylesheet" href="https://ssl.gstatic.com/docs/script/css/add-ons.css">
</head>
<body>
<div id="formdiv">
<table width="500">
<tr>
<td align=center>
<img src="https://lh5.googleusercontent.com/5PX_VkGEwpy6YfE9mOBP3tSZ-PE6QW_J2AIIGRYtKuA=w231-h207-p-no" alt="" width='200' />
</td>
<td colspan=2 align=center>
<font size=7>Virtual<br><br>Engagement<br><br>Card *Beta*</font>
</td>
</tr>
</table>
<table width="500">
<tr>
<td colspan=3 align=center>
<font size=3>Please complete the information below</font>
</td>
</tr>
</table>
<form id="form">
<table width="500">
<tr>
<td>First Name:</td>
<td><input type="text" pattern="^[A-Z]+[a-zA-Z]*$" id="first" placeholder="Please type your first name" title="Name must start with a capital letter and not contain punctuation or spaces" required="required" /></td>
</tr>
<tr>
<td colspan=2 align=center><button type="submit" class="action" id="submit">Submit</button></td>
</tr>
</table>
</form>
</div>
<script>
$('#submit').click(function getLocation() {//when the submit button is clicked run this function (getLocation)
if (navigator.geolocation) {//if the browser supports geolocation then...
navigator.geolocation.getCurrentPosition(getData);//get the current position and pass the values to function getData
} else {//if the browser does not support geolocation then...
$('#formdiv').append("Geolocation is not supported by this browser.");//append this message in the web interface
}
});
function getData(position) {//starts the getData function and names data passed to it by getLocation as "position"
console.log(position);//logs the data passed by getLocation in the JS log for viewing
console.log('Running getData');//logs the words "Running getData" in the JS log
var latitude = position.coords.latitude;//assigns the latitude value from geolocation to var latitude
var longitude = position.coords.longitude;//assigns the longitude value from geolocation to var longitude
var coords = [latitude, longitude];//combines latitude and longitude into an array named var coords
var data1 = $('#first').val();//gets the values from the inputs using the input id
var data = [data1,latitude,longitude];//combines data elements in an array named var data
console.log(data);//logs the data values in the JS log for viewing
google.script.run.addData(data);//runs the function in the code.gs file
console.log('Data transmitted');//logs the words "Data transmitted" in the JS log
var field1= document.getElementById('first');
field1.value= field1.defaultValue;
};
</script>
UPDATE 20DEC 1430EST: I changed getLocation to run on submit (vs. on click) using #user9090's advice and added some console logs. Changing to .submit allows the validation and required fields to do their job which is what I was looking for. However, now the script stops in getLocation. "browser supports geolocation" gets logged in the console but then the screen goes white. I believe that getData is not being ran anymore. Any ideas?
$('#form').submit(function getLocation() {//when the submit button is clicked run this function (getLocation)
console.log('getting location');
if (navigator.geolocation) {//if the browser supports geolocation then...
console.log('browser supports geolocation');
navigator.geolocation.getCurrentPosition(getData);//get the current position and pass the values to function getData
} else {//if the browser does not support geolocation then...
console.log('browser does not support geolocation');
$('#formdiv').append("Geolocation is not supported by this browser.");//append this message in the web interface
}
});
function getData(position) {//starts the getData function and names data passed to it by getLocation as "position"
console.log(position);//logs the data passed by getLocation in the JS log for viewing
console.log('Running getData');//logs the words "Running getData" in the JS log
Update 20DEC 1620EST: Turns out, the script works fine now, and validates. My last comment is only true is there is a validation error. If I complete the form abiding by the regex and required elements, the data submits just fine. Although, if I have a validation error, the script hangs in getLocation after the error is corrected and the submit button is pressed again...
Change first 7 lines inside your script block (in test.html) with following lines of code,
$("#form").submit(function(event) {
console.log("Submitting form....");
google.script.run.withSuccessHandler(function(e){
// Do you validation here
}).addData(this); // this is a form's data passed to your GAS function
});

Using HTML5, how do I use contenteditable fields in a form submission?

So I have a bunch of paragraph elements which are dynamically populated from a db. I have made the elements contenteditable. I now want to submit edits back the the db via a standard form submission. Is there a way to post the contenteditable elements back?
You have to use javascript one way or the other, it won't work as a "standard" form element as it would with a textarea or the like. If you like, you could make a hidden textarea within your form, and in the form's onsubmit function copy the innerHTML of the contenteditable to the textarea's value. Alternatively you could use ajax/xmlHttpRqeuest to submit the stuff a bit more manually.
function copyContent () {
document.getElementById("hiddenTextarea").value =
document.getElementById("myContentEditable").innerHTML;
return true;
}
<form action='whatever' onsubmit='return copyContent()'>...
If anyone is interested I patched up a solution with VueJS for a similar problem. In my case I have:
<h2 #focusout="updateMainMessage" v-html="mainMessage" contenteditable="true"></h2>
<textarea class="d-none" name="gift[main_message]" :value="mainMessage"></textarea>
In "data" you can set a default value for mainMessage, and in methods I have:
methods: {
updateMainMessage: function(e) {
this.mainMessage = e.target.innerText;
}
}
"d-none" is a Boostrap 4 class for display none.
Simple as that, and then you can get the value of the contenteditable field inside "gift[main_message]" during a normal form submit for example, no AJAX required. I'm not interested in formatting, therefore "innerText" works better than "innerHTML" for me.
Does it NEED to be standard form submission? If you cannot or do not want use a form with inputs, you may try AJAX (XMLHttpRequest + FormData), through which you could perform asynchronous requests and control better how response shows up.
If you want it even simpler, try jQuery's $.ajax function (also $.get and $.post). It sends data using simple JS objects.
Made a fully working example based on Rob's idea:
After hitting submit, the (hidden) textarea is updated with the table-data, in JSON-format.
(return true to submit)
function copyContent() {
const table = [];
$("tr").each(function() {
const row = [];
$("th, td", this).each(function() {
row.push($(this).text());
});
table.push(row);
});
$("#rows").val(JSON.stringify(table));
// return true to submit
return false;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form onsubmit='return copyContent()'>
<textarea name="rows" id="rows" rows="4"></textarea>
<button type="submit">Submit</button>
</form>
<table class="table table-striped">
<thead>
<tr>
<th>Head 1</th>
<th>Head 2</th>
</tr>
</thead>
<tbody>
<tr>
<td contenteditable="true">edit </td>
<td contenteditable="true">me</td>
</tr>
<tr>
<td contenteditable="true">please</td>
<td contenteditable="true">😊</td>
</tr>
</tbody>
</table>