Date input in form field is not submitted - 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 on the screen, 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.
So, in short, although I can see the correct Date date on screen it does not submit when supplied by the script.
Here is the html for relevant part of the form with what I think is relevant code flanking it:
<iframe id="mainPanel_iframe" name="mainPanel_iframe" class="mochaIframe" src="https://portal.starleaf.com/pbx/node-1.live.pr.starleaf.com/portal/#page=addUserConference&">
#document
<div> class="mainTableContainer">
<form action="#" method="get">
<div class="formRow">
<div class="fieldBlock calendarBlock">
<input type="date" id="editConference_startNative" class="native_date has_native">
<input type="text" id="editConference_start" class="sl_date has_native" placeholder="DD/MM/YYYY">
<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>
</form>
</div>
<div class="buttons">
<input type="button" id="editConference_ok" value="OK">
</div>
</iframe>
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. It automates the filling out of the form and submits it. The line with StDate (id="editConference_start") does not work but the next line with StTime (id="editConference_startTime") does pull through after 'clicking'. Both are type="text".
\Loading the data into the fields
var StDate = "06/05/2020";
document.getElementById('editConference_start').value = StDate;
var StTime = "16:20";
document.getElementById('editConference_startTime').value = StTime;
\ 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 into the Console and executing but this did not work. 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

Submit form then disable in Bootstrap 5

In Bootstrap v5, how do I submit a form via Post method first, and then after the form is submitted, show the form is being processed? I've found lots of examples for Bootstrap v4 and jQuery but Bootstrap v5 does not have jQuery and the documentation says there could be issues with jQuery.
Here is a striped down version of my form:
<form action="" method="post" id="reqform">
<div class="input-group">
<div class="form-floating mb-3">
<input class="form-control " id="nameInputId" placeholder="name" name="name" aria-describedby="basic-addon1" type="text">
<label for="nameInputId">Name</label>
</div>
</div>
<button type="submit" id="submitBtnId" class="btn btn-primary">Submit</button>
</form>
I tried this in a script block at the bottom of the file:
//when click submit button, show loading
submitBtnElm = document.getElementById("submitBtnId")
submitBtnElm.addEventListener("click", function () {
// disable button
submitBtnElm.disabled = true;
//disable rest of form
document.getElementById("nameInputId").disabled = true;
//add spinner to button and change text to "loading'''"
submitBtnElm.innerHTML = '<span class="spinner-border spinner-border-sm" role="status" aria-hidden="true"></span>Loading...'
});
In Chrome on CentOS 7, the form never gets submitted to the backend; I just get the loading button. On Firefox, the form gets submitted but the name field does not have a value on the backend. If I strip out this JavaScript, everything works fine.
I tried the form field onsubmit but I get the same results:
<form action="" method="post" id="reqform" onsubmit="return disableForm(this);">
I'd like to first post to the backend server and then after the post, show the loading button and disable the other fields. I want a way that the JS does not interfere with what is sent to the backend server. In other words, I'd like to be able to submit to the backend server when JS is disabled. I've found people asking the same with jQuery but none of them work for me.
Update:
I also tried:
submitBtnElm.addEventListener("submit", function ()
I setup a breakpoint on the backend server. The JS does not execute while the server is processing the information. As soon as the form gets submitted to the server, I want to change the button and form so the user can not do anything.
Update 2
I found this article that wraps the code that disables the form in a setTimeout:
https://chasingcode.dev/blog/javascript-disable-submit-button-form/
For me, it works in both Chrome and Firefox on CentOS 7. I don't have a mac to test. Here is my updated code that worked:
submitBtnElm = document.getElementById("submitBtnId")
submitBtnElm.addEventListener('click', function(event) {
setTimeout(function () {
event.target.disabled = true;
}, 0);
});
Do any Javascript gurus know if this is a good cross browser solution? If not, what is? The next best solution I found was where the functional button is swapped out with a non-function one that said something like 'loading'.
you can use Javascript, create a function that triggers when the form is summited. you can add a disabled class to the form. with a simple, if statement.

Get checkbox values and create window.location URL with them as search parameters

The code is supposed to be a youtube-like website where users can select a bunch of hashtags (via checkboxes) within a form and then click "search" and it's supposed to make a URL dynamically so that "window.location=dynamicURL" will be something like window.location="http://www.example.com/search.php?input1+input3+input4".
I've tried
var data = $('form').serialize();
to get started however when I type "data" in console, it says the variable isn't in use.
What I'm looking at doing is using some js to re-serialize the form each time a user clicks on a hashtag checkbox, so that each time a hashtag is clicked, a new array is made (clearing the old array) to be put to use in creating the URL.
I've tried several types of form serialize code and it doesn't seem to fill a variable that the console can see.
examples:
function ser()
{
$data = 'asd';
var data = 'add';
var serial = $("#divid").html($('#formid').serialize());
}
and
$('#button1').click(function () {
$("#divid").html($("#formid").find("select,textarea, input").serialize());});
both do naught. The var serial is not defined and button1.click doesn't input any html into #divid.
Here is my html:
<div id="divid">
<form action="" name="formid" id="formid" onsubmit="return false">
<button id="button1" onclick="$('.VideoTagsArraysUniqueId').prop('checked', !($('.VideoTagsArraysUniqueId').is(':checked')));ser();">
<label for="VideoTagsArraysUniqueId" class="VideoTagsArraysUniqueId_label">
<p>#VideoHashTag</p>
<input type="checkbox" class="VideoTagsArraysUniqueId" value="VideoHashTag"></input>
<span class="Checkmark">
</label>
</button>
<button id="button2" onclick="$('.VideoTagsArraysUniqueId').prop('checked', !($('.VideoTagsArraysUniqueId').is(':checked')));ser();">
<label for="VideoTagsArraysUniqueId" class="VideoTagsArraysUniqueId_label">
<p>#VideoHashTag</p>
<input type="checkbox" class="VideoTagsArraysUniqueId" value="VideoHashTag"></input>
<span class="Checkmark">
</label>
</button>
</form>
</div>
What I need to do is (when a user clicks on "search"), Get the values and build a js redirect using "window.location=URL" so that the values are separated by "+" so input2+input3+input4.
Are the form.serialize() vars I'm trying to declare supposed to output something when typed into the console?
Do I need to use ajax and a php script to build this redirecting button?
In my code, under "function ser()" I have "$data = 'asd';" and "var data = 'add';". I'm wondering why $data is populating however "data" is not. Are "$variables" treated differently than "variables"?
How to get the inputs and make the URL?
Thanks.

Console.log data from HTML form input

https://codepen.io/anon/pen/NYaeXV
I am trying to log the value of a HTML form input. I put multiple options inside the CodePen. Here is my initial thought process.
<form action="">
<input type="text" name="data" id="data">
<button type="submit">Submit</button>
</form>
function sConsole() {
var data = document.getElementById("data");
console.log(data.value());
}
sConsole();
You need to use value instead of value() since value is not a function , also consider using e.preventDefault() to avoid the page reload one more thing , by adding sConsole() into your js file you're asking the function to be executed when the page load, you need to move your function to the submit event instead.
Here is a working example and Happy coding :)
function sConsole(event) {
event.preventDefault();
var data = document.getElementById("data");
console.log(data.value);
}
<div id="container">
<h1>Hello, world!</h1>
<h4>Input your console data below : </h4>
<form action="" id="form" onsubmit="sConsole(event)">
<input type="text" name="data" id="data">
<button type="submit">Submit</button>
</form>
</div>
You missed onclick or onSubmit , you should also use .value
function sConsole() {
var data = document.getElementById("data");
console.log(data.value);
//!!Option 1a
//console.log(data.submit());
}
<div id="container">
<h1>Hello, world!</h1>
<h4>Input your console data below : </h4>
<form action="">
<input type="text" name="data" id="data">
<button type="submit" onClick="sConsole()">Submit</button>
</form>
</div>
You were close, just a few things to consider.
Getting the value of an input field
The value attribute of an input element stores the text in the textbox. To retrieve, this in javascript, use ExampleElement.value, for example:
var dataValue = document.getElementById("data").value;
or
var data = document.getElementById("data");
var dataValue = data.value;
You can also specify the value attribute in the input tag with value="". This is useful if you want to prefill the input text box, for instance, if you send the user input to a php script for action and wanted to return the textbox with information already included.
Calling a Javascript Function
There are multiple ways to call a javascript function, including doing so when certain events occur. In your situation, you probably want the input value logged every time the user clicks submit. You could add an event listener, but for simplicity sake of understanding, let's just use inline code. Every time they submit, let's log it, so onsubmit="sConsole();". Now the submit action will run your logging function.
If you wanted to log every change while the user was typing, you would use an event listener with more complex evaluation of the input value.
Prevent Default
It's likely that you don't want the form to actually be submitted to the server and page reloaded every time the user clicks submit. By using event.preventDefault();, javascript prevents the usual action of submitting the form to the server and instead leaves the user input and the page as is.
If you want the textbox to be "erases" after each submit, it's probably best to reset the value in your function rather than submitting the form. To reset the value, you would simply do data.value = "".
Code Example
Putting it all together, here's an example code segment with comments about your original sample.
<form action="" onsubmit="event.preventDefault(); sConsole();"> <!-- use inline JS to print input to console on submit -->
<input type="text" name="data" id="data">
<button type="submit">Submit</button>
</form>
<script>
function sConsole() {
var data = document.getElementById("data");
console.log(data.value); // data is the element, and we want its value
}
//sConsole(); This would call it only on script load, which isn't what you want
</script>

Use form data to update web page

Before I provide a bunch of code I'd like to first find out if what I'm trying to do is even possible.
I've created a web based version of the dice game called PIG using HTML & JavaScript. The user can change some of the game's settings by clicking on a "Settings" button on the main page. This button brings up a modal window containing an HTML form (). I'd like to use the data that the users enters and submits on this form to update various settings on the game's main page.
I chose to use an HTML5 form because was hoping to use the native HTML5 form validation capabilities rather than try and replicate that validation checking logic myself using JavaScript.
So my approach was to use javascript to get the data off the form on submit. I tried two different approaches to get this to work:
1) Using an "onsubmit=function getSettings()" on the tag
2) Using a submit button for the form with an onclick="getSettings()".
With both of these approaches I was able to successfully get all the values from the form on submit and use those values to successfully populate the main game page using the gettSettings() function however when I exit the getSettings() function the webpage values that I updated don't stick...they revert back to the original values regardless of which of these two approaches I use.
I know the values were successfully updated because when I set a break point on the last statement of the getSettings() method I can see that all of the values on the main page have been updated to reflect what was filled in on the form...so I know I'm grabbing all of the data successfully and updating the main page with those values.
I'm puzzled as to why the values that I successfully change on the web page simply revert back to their original value upon exit of the getSettings() function.
Maybe it's just not possible to do what I'm trying to do? And if not does anyone know why given I can see the values are successfully changed before they revert back to their original value. What am I missing?
Again I'm using a Form and collecting the data on submit so that I can leverage the "native" HTML5 form validation capabilities.
Regards.
***** EDIT TO ADD KEY SEGMENTS OF CODE *******
Here is the code HTML Code for the modal form:
<form name="config-settings" onsubmit="getSettings()">
<!-- <form name="config-settings">-->
<span class="errMsg"></span>
<div class="row clearfix">
<div>
<label>Player 1:</label>
</div>
<div>
<input type="text" name="input-name-0" id="input-name-0" maxlength="10" placeholder="Enter name" pattern="^\S+$">
</div>
</div>
<div class="row clearfix">
<div>
<label>Player 2:</label>
</div>
<div>
<input type="text" name="input-name-1" id="input-name-1" maxlength="6" placeholder="Enter name" pattern="^\S+$">
</div>
</div>
<div class="row clearfix">
<div>
<label>Winning Score:</label>
</div>
<div>
<input type="number" name="winning-score" id="winning-score" default="100" placeholder="Enter winning score">
</div>
</div>
<div class="row clearfix">
<div>
<label>Number of Dice:</label>
</div>
<div>
<select name="diceValues" id="dice-value">
<option value=""> - Select - </option>
<option value="dice-1">One Dice</option>
<option value="dice-2">Two Dice</option>
</select>
</div>
</div>
<!-- Below is alt method I used to submit form..yields same results -->
<!-- <input type="submit" value="Submit" onclick="getSettings()">-->
<input type="submit" value="Submit">
</form>
Here are the global variables defined and used in getSettings() method:
// Global variables
var scores, roundScore, activePlayer, gamePlaying, gamesWonCount, playerNames, winningScore, numOfDice, matchScore, msgs;
var player0, player1, score;
var player0Field = document.getElementById('name-0');
var player1Field = document.getElementById('name-1');
var scoreField = document.getElementById('winScore');
Here is the listener for the Settings button on the main web page that brings up the setting modal window containing the settings form:
//*********************************************************
// Open Settings Modal Windows
//*********************************************************
document.querySelector('.btn-settings').addEventListener('click', function () {
// Settings can't be changed if game is actively underway
if (!gamePlaying || roundScore === 0) {
document.querySelector('#modal-settings').style.display = 'block';
} else {
// Make error message visible
msgs.style = 'block';
// Create message to indicate settings successfully updated
msgs.textContent = "Settings can't be updated during game";
msgs.style.backgroundColor = 'pink';
fadeOut(msgs);
}
});
Here is the getSettings() javaScript function (note: there are no local variables defined in this function...they are all defined as global values (first few lines of javaScript app).
function getSettings() {
// Alternative call if I want this function to be called via eventListner
//document.querySelector('.btn-save').addEventListener('click', function () {
console.log("getSettings method called");
player0 = document.forms["config-settings"]["input-name-0"].value;
player1 = document.forms["config-settings"]["input-name-1"].value;
score = document.forms["config-settings"]["winning-score"].value;
// Reset msgs so they will be displayed each time
msgs.style = 'block';
playerNames[0] = player0;
player0Field.innerHTML = playerNames[0];
playerNames[1] = player1;
player1Field.textContent = playerNames[1];
// Set Winning score on UI to value on form
scoreField.textContent = score;
// numOfDice = document.getElementById('dice-value').value;
// Create message to indicate settings successfully updated
msgs.textContent = "Successfully updated settings";
msgs.style.backgroundColor = 'lightgreen';
fadeOut(msgs);
document.querySelector('#modal-settings').style.display = 'none';
}
I don't know exactly what this getSettings() function of yours is supposed to do, but I can try to give you a piece of advice:
Some of the form validation capabilities of HTML5 are not entirely supported on all of the used browsers(some users don't fancy to update their browser). Therefore relying on the "native" validation of HTML5 isn't exactly best practice.
If you want to manipulate the form values in any way before submitting the form I would rather add a listener to the submit button for click events, prevent any other action, make the checks/ manipulation of the form data and then manually submit the form. Anyways, front-end validation isn't entirely safe, so if you're peddling sensitive data it's mandatory that you'll make checks on serverside(if your app uses a server).
To exemplify what I've explained earlier:
document.getElementById("myBtn").addEventListener("click", function(event){
//Stops the form submitting.
event.stopImmediatePropagation();
//Do the checks here.
//Sends the form.
document.getelementById("myForm").sumbit();
);
If you change local variables inside this getSettings() function, the variables will be changed only within the function scope. You might want to read about scope in javascript. (this was just an educated guess).
I hope you find this useful, good luck!
Okay...I finally figured it out! The problem was not a scoping problem but instead and issue with how "onSubmit" works.
The solution involved making two changes:
1) Adding a return statement to the "onsubmit" attribute when calling the "getSettings()" function;
<form name="config-settings" onsubmit="return getSettings()">
2) Returning false at the end of the gettSettings();
return false;
Note: I had previously tried returning true but not false. I was errantly under the impression that returning false value from getSettings() function would disable HTML5 "native" validation and force me to implement all of the error checking myself...which was not what I wanted. It is now my understanding that returning false merely prevents the form from being submitted..but it doesn't disable the HTML5 native validations.
This solution worked perfectly for me because my goal was not to submit the form to the server (as there is no server component here) but merely to use the "native" HTML5 form checking and then update the values on the local web page.
With all of that said I'm still not entirely sure why when I didn't provide the return statement or when I returned true why all of my changes reverted back to their originally value. If anyone can shed some light on why I'd appreciate it.
Cheers

Updating DOM elements using jQuery

I'm looking for a way to update the webpage I'm working on to act as a report for several different people to pass back and forth. I'm using forms to take in several pieces of data and am wondering how I can make it so that it just immediately adds the content to the divs under the right heading. I'm currently using jquery and append and it looks like it adds the desired input and then immediately removes it. I tried using .live as well and it did not show up at all. Is there a way to make form inputs post to the page without submitting to another page?
Here is my code so far, testing just the element that will be the heading for the issue:
<div class="IssueDiv">
</div>
<form id="newIssue">
<fieldset>
<legend>Add a new important issue:</legend>
<input type="text" id="issue" placeholder="Issue Summary...">
<input type="text" id="issue-client" placeholder="Client...">
<input class="ticket" type="text" id="issueParent" placeholder="Parent ticket..."><br>
<textarea placeholder="Issue details..."></textarea><br>
<button id="addIssue">Add Issue</button>
</fieldset>
</form>
And the jquery:
<script>
$(function(){
$("#addIssue").click(function() {
var $issue = $("#issue").val();
var $issueSum = $("<h3></h3>").text($issue);
$(".IssueDiv").append($issueSum);
});
});
</script>
edit: I'm looking into using AJAX but I'm not sure how to make it so that all of the input data will persist. I am basically looking to make a webpage-style-report that will allow myself and my team to update the entries on the report and they will stay on the report until we are able to take them off by removing a div that encapsulates the individual issue.
I would also like to be able to format the individual pieces here separately, so, for instance, I could add a check-box that says the issue is urgent and format the heading of those to be red. What is the easiest way to have data that persists, can be added into new (div/h/p) elements, and is shown on the main webpage, while also allowing me to update formatting?
Your code appears to add the text and then immediately remove it because your form gets posted and the page reloads, effectively resetting the page to its initial state.
If you just want to add the text to the page without posting the form or executing any server-side processing, you can prevent the form from posting using jQuery's preventDefault(). Note that I have created a submit listener on the form itself, rather than a click listener on the submit button.
$("#newIssue").on('submit', function(e) {
e.preventDefault();
...
});
$(function () {
$("#newIssue").on('submit',function (e) {
e.preventDefault();
var $issue = $("#issue").val();
var $issueSum = $("<h3></h3>").text($issue);
$(".IssueDiv").append($issueSum);
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div class="IssueDiv"></div>
<form id="newIssue">
<fieldset>
<legend>Add a new important issue:</legend>
<input type="text" id="issue" placeholder="Issue Summary...">
<input type="text" id="issue-client" placeholder="Client...">
<input class="ticket" type="text" id="issueParent" placeholder="Parent ticket...">
<br>
<textarea placeholder="Issue details..."></textarea>
<br>
<button id="addIssue">Add Issue</button>
</fieldset>
</form>
However, keep in mind that if you're using this to share reports between computers, this will not work. This is only updating the DOM in the current browser and is not doing any data storage or retrieval. If you need the reports to update online, consider using AJAX to post your data to a server-side script without refreshing the page. Then include some sort of timer that refreshes the content (also using AJAX) on a schedule (e.g. every 10 seconds).

Categories

Resources