Updated DATE field values in form are not submitted - problem - javascript

I have some code that successfully inputs a variety of values into a form on a webpage and I can see that the data is put into the correct fields in the correct format. When I submit the form using the 'OK' button, or code, the process completes but the Date data carried through is the current date, despite the fact that I can see a different date displayed in the field. I can cut and paste data into the field from e.g., Notepad and it works fine.
Here is the html for the beginning of the form:
<form action="#" method="get">
<div class="columns group">
<div class="formColumn flex">
<div id="editConference_ownerField" style="display: none">
<div class="formRow">
<div class="labelBlock" id="editConference_ownerLbl">Owner</div>
<div class="fieldBlock fillspace">
<select id="editConference_owner"></select>
</div>
</div>
</div>
// The first input in this class loads find and is pulled through when the form is submitted using the OK button
<div class="formRow">
<label class="labelBlock" id="editConference_labelLbl" for="editConference_label">Title</label>
<div class="fieldBlock fillspace">
<input type="text" class="input" id="editConference_label" maxlength="256" value="">
</div>
</div>
<div id="editConference_timeFields" style="">
<div class="formRow">
<div class="labelBlock" id="editConference_startLbl">Start</div>
<div class="fieldBlock calendarBlock">
<input type="date" id="editConference_startNative" class="native_date has_native">
// The element id="editConference_start" is a date and does NOT pull through
<input type="text" id="editConference_start" class="sl_date has_native" placeholder="DD/MM/YYYY">
// The element id="editConference_startTime" is a time DOES pull through!
<input type="text" id="editConference_startTime" placeholder="Time" class="ui-timepicker-input" autocomplete="off">
<div id="start-date-picker"><div class="pika-single is-hidden is-bound" style="position: static; left: auto; top: auto;"></div></div>
<div id="start-time-picker"></div>
</div>
</div>
<div class="formRow">
<div class="labelBlock" id="editConference_endLbl">End</div>
<div class="fieldBlock calendarBlock">
<input type="date" id="editConference_endNative" class="native_date has_native">
<input type="text" id="editConference_end" class="sl_date has_native" placeholder="DD/MM/YYYY">
<input type="text" id="editConference_endTime" placeholder="Time" class="ui-timepicker-input" autocomplete="off">
<div id="end-date-picker"><div class="pika-single is-hidden is-bound" style="position: static; left: auto; top: auto;"></div></div>
<div id="end-time-picker"></div>
</div>
</div>
Here is the Javascript that I have been using. I have been testing it out using the Chrome F12 Console and working inside the iframe. All the inputs used appear to be of type="text". It automates the filling out of the form except the problem noted above and submits it:
\\Loading the data into the fields
var Title = "Coding syntax test again";
document.getElementById('editConference_label').value = Title;
var StDate = "06/05/2020";
document.getElementById('editConference_start').value = StDate;
var StTime = "16:20";
document.getElementById('editConference_startTime').value = StTime;
var EndDate = "06/05/2020";
document.getElementById('editConference_end').value = EndDate;
var EndTime = "17:50";
document.getElementById('editConference_endTime').value = EndTime;
var Desc = "The conference description stuff";
document.getElementById('editConference_description').value = Desc;
\\ Click 'OK'
document.getElementById("editConference_ok").click();
Things tried:
1) Using the code below to enter data via the id ="editConference_startNative" element. It does not seem to work but I am not sure if my code makes any sense or if this something worth pursing:
var StDate = document.querySelector('input[type="date"]');
StDate.value = '2020-05-05';
document.getElementById('editConference_startNative').value = StDate;
2) Creating a var with a date type for use with the Native version of the input
var StDate = new Date("05/05/2020");
document.getElementById('editConference_startNative').value = StDate;
I think the output is in the wrong form to be used but can't figure out how to shorten it in the right format. Perhaps this is not the right approach.
3) Removing the final click code then waiting for a few seconds and them adding the Click line in and executing but this did not work so I presume it is not a question of a delay. I also tried this code before the click code for a delay but I am not sure if it is valid:
setTimeout(function(){}, 3000);
document.getElementById("editConference_ok").click();
Thanks in advance for any suggestions.

Related

How to display user values from localStorage?

I created a form to collect user information and then saved it in localstorage.
To finish the programming I want to display this information in an HTML page. However, the way I did the information appears and disappears quickly.
<!DOCTYPE html>
<html>
<body>
<form style="width:50%; margin-left: 20%; margin-top: 1.9%;">
<div class="form-group mx-sm-3 mb-2">
<h2 style="font-size: 1.0rem;">Selecione a data</h2>
<input id="datepicker" width="396" />
<div class="input-group mb-3">
<input type="text" class="form-control" id="matriz" aria-label="Amount (to the nearest dollar)">
<div class="input-group-append">
<span class="input-group-text">Matriz</span>
</div>
</div>
<div class="input-group mb-3">
<input type="text" class="form-control" id="rep" aria-label="Amount (to the nearest dollar)">
<div class="input-group-append">
<span class="input-group-text">Rep</span>
</div>
</div>
<p>Saved info is:</p>
<p id="currentDate"></p>
<p id="currentRep"></p>
<p id="currentMatriz"></p>
<script>
$('#datepicker').datepicker({
uiLibrary: 'bootstrap5'
});
</script>
<script>
store();
function store(){
const inputDate = document.getElementById('datepicker').value;
const inputRep = document.getElementById('rep').value;
const inputMatriz = document.getElementById('matriz').value;
window.localStorage.setItem('Date', String(inputDate));
window.localStorage.setItem("Rep", String(inputRep));
window.localStorage.setItem("Matriz", String(inputMatriz));
document.getElementById("currentDate").innerHTML = window.localStorage.getItem("Date");
document.getElementById("currentRep").innerHTML = localStorage.getItem("Rep");
document.getElementById("currentMatriz").innerHTML = localStorage.getItem("Matriz");
}
</script>
</body>
</html>
Is there any way to display the user values in html page from local storage?
You are setting the key "Rep" but then getting "Reprodutor". This might be the issue why you don't see the values appear on the page
Your code does the following steps (in order):
Read value of DOM elements
Save that value to LocalStorage
Read value from LocalStorage and inject into DOM elements
Since the DOM elements are empty on page load, you'll push 'nothing' to the LocalStorage, read 'nothing' so there's nothing to show.
Consider the following example where we change the order if needed:
store();
function store(){
// Get elements
const inputDate = document.getElementById('datepicker');
const inputRep = document.getElementById('rep');
const inputMatriz = document.getElementById('matriz');
// IF there is NOTHING in LocalStorage
if (window.localStorage.getItem('Date') === null) {
// Set dumy value so we'll not push 'empty' things to LocalStorage
inputDate.innerHTML = 'Dummy date';
inputRep.innerHTML = 'Dummy rep';
inputMatriz.innerHTML = 'Dummy Matriz';
// Save to localStorage
window.localStorage.setItem('Date', inputDate.innerHTML);
window.localStorage.setItem("Rep", inputRep.innerHTML);
window.localStorage.setItem("Matriz", inputMatriz.innerHTML);
} else {
// Set to DOM eleemnts
inputDate.innerHTML = window.localStorage.getItem("Date");
inputRep.innerHTML = localStorage.getItem("Rep");
inputMatriz.innerHTML = localStorage.getItem("Matriz");
}
}
<p>Saved info is:</p>
<p id="currentDate"></p>
<p id="currentReprodutor"></p>
<p id="currentMatriz"></p>
<hr >
<div id='datepicker'></div>
<div id='rep'></div>
<div id='matriz'></div>
Note: This does not work in SO snippets, try it offline

Regarding enabling and disabling fields for registration form?

I have to create a registration form with fields as first name,last name,address,contact no,email.initially only first name shouid be visible as i enter name it should enable last name as i enter last name it should enable address
you could do somthing like this
<form>
<input id='firstname' >
<input id='lastname' disabled>
</form>
<script>
const firsname = document.getElementById('firstname')
const lastname = document.getElementById('lastname')
firstname.oninput = function(){
if(firstname.value.length>0) lastname.disabled = false
else lastname.disabled = true
}
</script>
I have totally different take on this. There is nothing wrong with this approach. In-fact there are many cool UIs design with same terminology. typeform.com is great example for this.
This is very bad practice at SO, whats a point in down rating a new user.
If you cant give a proper suggestion, then you have no right to down rate someone only because you failed to understand his view point.
To answer this :
It will be very bad idea if its just implemented this in wrong way, and user might get annoyed with this.
Its better to use combination of CSS and JS (jquery) to achieve this for great looking, user friendly UI.
Find this small snippet i've created using jQuery might help you.
with little css it can be made to look great!
Press enter after entering detail into text box.
jQuery.extend(jQuery.expr[':'], {
focusable: function(el, index, selector) {
return $(el).is('a, button, :input,[tabindex]');
}
}); // extention to jquery
$("#res").hide();
$("#email").hide();
$("#mobile").hide();
//Focuse Next on Enter press
$(document).on('keypress', 'input,select', function(e) {
if (e.which == 13) {
e.preventDefault();
var $focusable = $(':focusable');
var index = $focusable.index(document.activeElement) + 1;
if (index >= $focusable.length) index = 0;
$focusable.eq(index - 1).hide();
$focusable.eq(index).show();
$focusable.eq(index).focus();
}
});
function subscribeRelease() {
$("#res").show(200);
$(".btn").hide(200);
}
body,
html {
height: 100%;
}
<link href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" rel="stylesheet" />
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.0/jquery.min.js"></script>
<div class="container-fluid h-100 justify-content-center">
<div class="row justify-content-center align-middle h-100">
<div class="col-10 text-center align-self-center">
<h1 style="font-size:40pt;">Register</h1>
<form id="register" class="form-inline justify-content-center">
<input type="text" class="form-control" id="name" placeholder="Name" /><br>
<input type="text" class="form-control" id="email" placeholder="Email" /><br>
<input type="text" class="form-control" id="mobile" placeholder="Mobile" /><br>
<br><br><br>
<button class="btn btn-info" onclick="subscribeRelease(); return false;">Submit!</button>
<span id="res"><h3 class="text-success">Registration Completed!</h3></span>
</form>
</div>
</div>
</div>

Each time I click button page refreshes

Title virtually says it all. Each time I click calculate button the page just refreshes. I added the stopPropagation and preventDefault which worked on my other button on a different page, however in this situation they don't seem to work. Any thoughts?
JS:
/******** Loan Balance Constructor *********/
function LoanBalance(mLoanAmt, mIntRate, nMonths, mMonthlyPmt){
//Declarations
this.loanAmount = mLoanAmt;
this.interestRate = mIntRate;
this.numbOfMonths = nMonths;
this.monthlyPayment = mMonthlyPmt;
//Calculates Remaining Balance
this.calculateRemaining = function(){
console.log(this.loanAmount);
console.log(this.interestRate);
console.log(this.numbOfMonths);
console.log(this.monthlyPayment);
//COME BACK TO FIX THE FORMULA
var remainingBalance = this.loanAmount*(Math.pow(1+this.interestRate, this.numbOfMonths) -
(this.monthlyPayment*(Math.pow(1 + this.interestRate, this.numbOfMonths) - 1) / this.interestRate));
return remainingBalance;
}
return this.calculateRemaining()
}
function newBalanceObject(e){
e.stopPropagation();
e.preventDefault();
var balanceObject = new LoanBalance(document.getElementById("loanAmount").value, document.getElementById("interestRate").value,
document.getElementById("numMonthsPaid").value, document.getElementById("sliderDuration").value);
var result = balanceObject.calculateRemaining();
document.getElementById("remainingBalanceTag").innerHTML = "Your remaining balance is: " + "$" + result.toFixed(2);
}
HTML:
<div id="remainingBalance">
<h1 class="text-center">Loan Balance Calculator</h1>
<form>
<div class="form-group">
<label for="loanAmount">Loan Amount:</label>
<input class="form-control" id="loanAmount">
</div>
<div class="form-group">
<label for="interestRate">Interest Rate:</label>
<input class="form-control" id="interestRate" placeholder="Please enter number as a decimal">
</div>
<div class="form-group">
<label for="numMonthsPaid">Number of Months Paid: </label>
<input id="numMonthsPaid" type="text" data-slider-min="0" data-slider-max="600" data-slider-step="1" data-slider-value="300">
<div class="form-group">
<label for="sliderDuration">Loan Duration: </label>
<input id="sliderDuration" data-slider-id='ex1Slider' type="text" data-slider-min="0" data-slider-max="600" data-slider-step="1" data-slider-value="300"/>
</div>
<button id="calcButton" class="btn btn-default">Calculate</button>
</form>
<h1 class="text-center" id="remainingBalanceTag"></h1>
</div>
The form is getting submitted by default. You need to intercept the submission event and stop the default's browser action.
Since you haven't specified the action on the form element, it's simply refreshing the page, because it doesn't know where to send the data to.
Here's a sample code which shows how to intercept and stop all forms fom being submitted by the browser. Adjust it according to your setup so you only prevent submission of the forms that you want prevented.
Array.from(document.forms).forEach(form => {
form.addEventListener('submit', e => e.preventDefault())
}

jquery dynamic subselection combining last and form elements

Update
Tidied up the solution in progress and added some extra details
I have a form area which creates clones based on a template. In order to make sure the form transmits in an order, the script goes through the form at send time appending a number which defines the current batch set. Below is an over simplified representation of what is going on:
<form>
<div class="batch-template">
<div class="batch-piece">
<a class="clone" />
<input name="test-input">
<input name="another-test-input">
<select name="a-drop-down">
</div>
</div>
<div class="batch-paste-area">
</div>
</form>
When the page starts:
The contents of "batch-template" are stored to an object variable
The original template is removed from the page
An instance of the template is appended to the "batch-paste-area"
The following is an example of the output created after clicking twice.
<form>
<div class="batch-template">
</div>
<div class="batch-paste-area">
<div class="batch-piece">
<a class="clone" />
<input name="test-input">
<input name="another-test-input">
<select name="a-drop-down">
</div>
<div class="batch-piece">
<a class="clone" />
<input name="test-input">
<input name="another-test-input">
<select name="a-drop-down">
</div>
</div>
</form>
When it comes to submitting the form: prior to serialization, I would like the script to loop through each "batch-piece" within "batch-paste-area" and add a count value to the end of each form field name. Continuing with the set above, the result (to a browser) would seem like that shown below:
<form>
<div class="batch-template">
</div>
<div class="batch-paste-area">
<div class="batch-piece">
<a class="clone" />
<input name="test-input1">
<input name="another-test-input1">
<select name="a-drop-down1">
</div>
<div class="batch-piece">
<a class="clone" />
<input name="test-input2">
<input name="another-test-input2">
<select name="a-drop-down2">
</div>
</div>
</form>
So far, I can either loop through EVERY input within the paste area or just select the last.
Selecting the last batch-piece is simple:
var intCount = 1;
$('.batch-paste-area .batch-piece').each(function(){
/*
* Would like to be able to loop through form fields here
* Below is an attempt to select all form fields for current set
*/
$(this + ' input, '+ this + ' select').each(function() {
var strName = $(this).attr('name') + intCount;
$(this).attr('name', strName);
});
intCount++;
});
Frustratingly, I had actually tried the correct solution in advance but had forgotten to use the comma at the time!
var intCount = 1;
$('.batch-paste-area .batch-piece').each(function(){
/*
* Would like to be able to loop through form fields here
* Below is an attempt to select all form fields for current set
*/
$(this).find("input, select").each(function() {
var strName = $(this).attr('name') + intCount;
$(this).attr('name', strName);
});
intCount++;
});

jQuery.find() a form into an element not working

dynamically i generate a formular into a defined div-container and i would like grab the send-action for sending with ajax.
The generate HTML:
<div class="mhuntform">
<form action="/wp-admin/admin-ajax.php" method="POST">
<h2>Title</h2>
<p>A text</p>
<div id="form" style="padding: 5px 0px;">
<p>
<label for="email" style="display: inline-block; margin-right: 10px;">E-Mail</label>
<input type="email" name="email" id="email" placeholder="E-Mail" style="width: 60%;">
</p>
<p>
<button name="mhskl_send" id="mhskl_send">Anmelden</button>
</p>
</div>
</form>
</div>
The Formular is defined by the admin into the wordpress-page. In Javascript (jQuery) i know only the classname of the div-container (here .mhuntform). So in Javascript i try to catch the event:
// mhuntskl.options.container = '.mhuntform'
$(mhuntskl.options.container).find('form').submit(function(ev){
ev.preventDefault();
var email = $(mhuntskl.options.container).find('input[type="email"]').val();
var res = $.ajax(mhuntskl.options.ajaxurl,{async:false,data:{action:'subscribe',email:email},dataType:'json',type:'POST'}).responseText;
res = $.parseJSON(res);
if (res.success) {
$(mhuntskl.options.container).hide();
}
return false;
}
But unfortunately the submit-event will not catch and if i prints the containter with find into the console console.log($(mhuntskl.options.container).find('form')) it will received an empty object only.
What i make wrong here?
If console.log($(mhuntskl.options.container).length); is 1 and console.log($(mhuntskl.options.container).find('form').length); is 0 then there is only one possible reason. Your form is still not inside the .mhuntform div when you execute the code. Is that form generated by another javascript. If not, then is the js code wrapped in $(document).ready.

Categories

Resources