reaching a point of confusion
I am creating a couple of input elements and a button to search.
From using HTML previously, I am lead to believe that i should create a and contain my elements and
But the data is not to be sent anywhere apart from to the javascript to show the correct place in the google map.
I've managed to confuse myself; do i need a element to contain and s ?
The problem is when i press a whether it be a test or a search button the page reloads.
I do not want the page to reload. The only way for me not to get this to happen is by removing element, this does not feel right, I am concerned with using good practice if possible.
This is my code:
<form id="maps_form">
<fieldset id="search_maps">
<label for="marker">Search Shop: </label>
<input name="searchName" id="searchName" type="text" placeholder="Enter Shop Name">
</fieldset>
<fieldset id="map_buttons">
<button id="test"> test</button>
<button id="searchSomething">Search</button>
</fieldset>
</form>
I feel like, whilst am learning this javascript, dipping into jquery and learning xml, I am forgetting the basics of html :s is this normally to lose touch whilst learning new languages?
The page will reload if your your click/submit handler doesn't return false. So page will refresh if:
If your Javascript listener isn't registered correctly
Your Javascript handler returns true
Your Javascript handler causes an error (check dev console for errors)
$("#maps_form").submit(function () {
// do stuff
return false; // Don't submit the form
});
Never do that! Wouldn't prevent go to next page if too many action after return false.
$("#maps_form").submit(function () {
// do stuff
return false; // Don't submit the form
});
This is correct form:
$("#maps_form").submit(function (event) {
event.preventDefault();
...
});
Related
I know how to send a form without page refresh with jQuery. That is not what I'm about here. I just wanted to point that out. I have a button when onclick() will display a form and a hidden link. The problem I'm facing is when the form is being submitted the page refresh so the hidden link returns to initial state which is hidden.
Is there a way I can prevent a function to be restored on page refresh? That's what I'm interested to know. But if the best way to do this is by preventing the form to refresh I will do it. I just wanted to know if I could do it another way for knowledge sake. I'm trying to learn new ways instead of always doing same old jQuery stuff.
html
<button id="showOwn" type="button" onclick="showHiddenForm();" >
I'm a returning client</button>
<div id="hiddenForm" style="display:none;">
<form method="POST" action="form.php">
<input type="submit" name="validate_customer" value="Confirm Identity">
</form>
<a id="hiddenLink" href='other_page.php>Continue as Roger Rabbit</a>
</div>
script
function showHiddenForm(){
//show hidden form
document.getElementById("hiddenForm").style.display='block';
}
Use localStorage:
window.onload = () => {
if( localStorage.getItem("show") )
showHiddenForm();
};
function showHiddenForm(){
localStorage.setItem("show",true);
//show hidden form
document.getElementById("hiddenForm").style.display='block';
}
I just wanted to know if I could do it another way for knowledge sake.
Store a flag in local storage (or session storage) (spec | MDN) and on page load, use the presence/absense of that flag to determine whether to hook up the function (or generally, to do whatever it is you want to do differently, differently).
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
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).
let me start by saying it may look simple but im finding it extremely difficult.
ive made a search script that uses PHP and to fetch a result would look like this
search.php?term=alice&submit=Submit
Standard stuff.. problem is, i use an SPI with AJAX and PHP so my results would have to load dynamically into a div, whilst still keeping the hash value, as not to lose the page the user had visited previous to searching.
jQuery.history.js is the plugin i use for back button support, which requires links to be like such:
Home Page
this would load 'home.html' into a div named pageContent. as far as i know theres no way to call php files unless you develop a little hack, which i have,
here is my JavaScript/jQuery for my search form:
<script language="JavaScript">
$(document).ready(function() {
// bind form using ajaxForm
$('#search1').ajaxForm({
// target identifies the element(s) to update with the server response
target: '#pageContent',
// success identifies the function to invoke when the server response
success: function() {
$('#pageContent');
var hash = '#search.php?term='+($('#query').val()+'&submit=Submit').replace(/ /g, '+');
var stripped = hash.replace(/(<([^>]+)>)/ig,"");
update(window.location.hash = stripped);
}
});
});
</script>
Heres the form:
<form id="search1" action="search.php" method="post">
<input id="query" type="text" name="term" />
<input type="submit" name="submit" value="Submit" />
</form>
My problem is this:
ive tried this.form.reset(); this: Resetting a multi-stage form with jQuery , yet none of this works. please help me if you know a way of doing this..
$('#query').val(DefaultValue);
with this u can set your value to whatever you want, like blank: '';
Interesting bug here that seems to be limited to IE and Webkit.
I have a basic form setup:
<div id="output">Form output is displayed here</div>
<form id="myForm" action="#" method="post">
<input type="text" name="username" id="usernameInput" />
<input type="submit" value="Submit" />
</form>
Now if I just submit the form through a normal page refresh, the next time I go to type text into the input field, I will get the browser's default auto-suggest dropdown (this is the intended behavior). However, if I highjack the form submission behavior in order to do an AJAX submit:
$('#myForm').submit(function () {
$('#output').text($('usernameInput').val());
return false;
});
Now when I submit the form, the output div updates, but the previous values that I input into the form aren't stored and no suggestions will be made when you type.
Does anyone have any creative solutions to this problem? Maybe an (gulp) iframe?
IE and WebKit only remember values that were submitted normally, and since you are submitting it through AJAX, those engines do not remember the values. Instead of an iframe, I would use a jQuery plugin for the autocomplete, like this one. Of course, with that solution, you will need to maintain a listing of what a user has typed in the past, which shouldn't be too hard.
test with these modifications in controlling submit:
$('#myForm').submit(function (e) {
e.stopPropagation();
$('#output').html($("#usernameInput").val() + "<br />");
});