Submitting geocomplete form on suggestion select - javascript

I'm fairly new to JS so I'm a bit confused as in why this is not working.
Basically I'm using the geocomplete jQuery plugin to populate a form with the coordinates and address. Then, once a user selects the destination, I want to sumbit the form.
<form action="search.php" method="post" id="searchForm">
<input id="geocomplete" type="text" placeholder="Where are you going to?" size="35" />
<input name="lat" type="hidden" value="">
<input name="lng" type="hidden" value="">
<input name="formatted_address" type="hidden" value="" id="address">
</form>
and this would be the scripts I call to initiate the form plugin (which works), and the script to submit the form once the value of the address has been changed by the plugin:
<script type="text/javascript">
window.onload= function () {
if(window.addEventListener) {
document.getElementById('address').addEventListener('change', doIt, false);
} else if (window.attachEvent){
document.getElementById('address').attachEvent("onchange", doIt);
}
function doIt(){
document.getElementById("searchForm").submit();
}
}
$("input").geocomplete({ details: "form" });
</script>
I don't see why this won't work since the value does get changed. Many thanks!

A change event fires only when the change occurs by direct user input, not when a script changes the input value.
Use the events provided by that plugin as described on the page you already linked to.

Here is another solution uing jquery. This forces a submit when an autopopulated address is clicked on or the user selects it with the arrow keys and hits enter. There is a delay of 1.5 seconds to allow the geocoding library to populate hidden fields. This required delay is why 'onchange="this.form.submit()" didn't work for me.
/*
submit form when user clicks or hits enter on auto suggest
must sleep for 2 seconds to allow the geocoding library to update the hidden fields
*/
$(document).ready(function(){
$('#geocomplete').change(function(){
setTimeout(function() {
$('#find').click()
}, 1500);
});
});
$(document).ready(function(){
$('#geocomplete').keydown(function(event){
if (event.keyCode == 13) {
setTimeout(function() {
$('#find').click()
}, 1500);
return false;
}
});
});

$(function(){
$(".geocomplete")
.geocomplete({details:"form"})
.bind("geocode:result", function(event, result){$(".searchForm").submit();
});
});

Related

Make the click-button code not disappear instantly? [duplicate]

I have a button (<input type="submit">). When it is clicked the page reloads. Since I have some jQuery hide() functions that are called on page load, this causes these elements to be hidden again. How do I make the button do nothing, so I can still add some action that occurs when the button is clicked but not reload the page.
There is no need to use JS or jQuery.
to stop the page to reload, just specify the button type as 'button'.
If you don't specify the button type, the browser will automatically set it to 'reset' or 'submit' which causes the page to reload.
<button type='button'>submit</button>
Use either the <button> element or use an <input type="button"/>.
In HTML:
<form onsubmit="return false">
</form>
in order to avoid refresh at all "buttons", even with onclick assigned.
You could add a click handler on the button with jQuery and do return false.
$("input[type='submit']").click(function() { return false; });
or
$("form").submit(function() { return false; });
In HTML:
<input type="submit" onclick="return false">
With jQuery, some similar variant, already mentioned.
You can use a form that includes a submit button. Then use jQuery to prevent the default behavior of a form:
$(document).ready(function($) {
$(document).on('submit', '#submit-form', function(event) {
event.preventDefault();
alert('page did not reload');
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<form id='submit-form'>
<button type='submit'>submit</button>
</form>
You could also use JavaScript for that:
let input = document.querySelector("input");
input.addEventListener("submit", (event) => {
event.preventDefault();
})
As stated in one of the comments (burried) above, this can be fixed by not placing the button tag inside the form tag. When the button is outside the form, the page does not refresh itself.
I can't comment yet, so I'm posting this as an answer.
Best way to avoid reload is how #user2868288 said: using the onsubmit on the form tag.
From all the other possibilities mentioned here, it's the only way which allows the new HTML5 browser data input validation to be triggered (<button> won't do it nor the jQuery/JS handlers) and allows your jQuery/AJAX dynamic info to be appended on the page.
For example:
<form id="frmData" onsubmit="return false">
<input type="email" id="txtEmail" name="input_email" required="" placeholder="Enter a valid e-mail" spellcheck="false"/>
<input type="tel" id="txtTel" name="input_tel" required="" placeholder="Enter your telephone number" spellcheck="false"/>
<input type="submit" id="btnSubmit" value="Send Info"/>
</form>
<script type="text/javascript">
$(document).ready(function(){
$('#btnSubmit').click(function() {
var tel = $("#txtTel").val();
var email = $("#txtEmail").val();
$.post("scripts/contact.php", {
tel1: tel,
email1: email
})
.done(function(data) {
$('#lblEstatus').append(data); // Appends status
if (data == "Received") {
$("#btnSubmit").attr('disabled', 'disabled'); // Disable doubleclickers.
}
})
.fail(function(xhr, textStatus, errorThrown) {
$('#lblEstatus').append("Error. Try later.");
});
});
});
</script>
Use event.preventDefault() in the first line of your event function.
Buttons must be of the type button and contain type="submit" in the button html.

If the text-box value in HTML5 form is x, then y: Is that possible?

So basically, I want to enter a certain string into a text-box, and check what it is. It's basically for a command system that I'm trying to implement. There's a little Terminal pop-up and there is a text-box in it waiting for a command. This is the HTML I used to make the text-box inside a form:
<form id="command-input">
<input type="text" placeholder="Enter Command" id="command-box">
<input type="submit" style="display: none">
</form>
I made the submit invisible so you could press enter and it would submit the form. Here is the JavaScript I'm using:
function changeStyle(sheet) {
document.getElementById('specific-sheet').setAttribute('href', sheet);
}
var command = document.getElementById('command-input');
if(command.value=="windows"){
changeStyle('../css/windows-xp.css');
}
I want to make it to where if I type "windows" into the command box and hit enter, it will change my stylesheet. The people on this website are smart, so I once again am asking for help. Thanks for contributing!
You will need to check with an event. Assuming this is in the plain tags; you can use the following:
var inputbox = document.getElementById('command-input');
function changeStyle(sheet) {
document.getElementById('specific-sheet').setAttribute('href', sheet);
}
inputbox.addEventListener('input', function (evt) {
if (this.value == 'windows'){
changeStyle('../css/windows-xp.css');
}
});
Edit:
you can do this as well. Change the event to "onsubmit" if you want enter key to trigger.
function changeStyle(sheet) {
document.getElementById('specific-sheet').setAttribute('href', sheet);
}
document.getElementById('command-input').addEventListener(
'keyup',
function(eve){
if (eve.target.value == 'windows'){
changeStyle('../css/windows-xp.css');
}
},
false
);
If you want to keep the changes even after the page refresh you might have to keep the file path in the localstorage and use that in dom load event.
Also, you really dont need to wrap this in a form tag. You can use a simple div and this is not triggered by a form submit.
You could create a function that you can call on form submission as explained here at https://www.w3schools.com/jsref/event_onsubmit.asp.
<form onsubmit="myFunction()">
Enter name: <input type="text">
<input type="submit">
</form>
<script>
function myFunction() {
var command = document.getElementById('command-input');
if(command.value=="windows"){
changeStyle('../css/windows-xp.css');
}
}
</script>

Submit form without page reloading, and link to javascript

I have made a system that when you enter a specific value, it'll fade in values based on the selection.
I have this code here which is the main form where you can input the specific model numbers into the form and then press enter.
<form>
<input type="text" name="ModNum" id="ModelNumber" pattern="^PIV13RT[23]?$"
title="Your Model Number." placeholder="Please Input a Model number" size="35" maxlength="8">
<center><span class="egsmall"><strong>Eg: PIV13RT, PIV13RT2, Ect.</strong></span></center>
<center><div class="btnwrap"><input name="proceed" type="submit" class="submitsup" id="forward" /></div></center>
</form>
The problem is that when you press enter, because it's inside of a form, it reloads the page, which means that the fade in won't load because it's reloading the page.
$("#forward").click(function(){
$.ajax({
}).done(function() {
$('.optionbk').fadeIn('slow');
});
});
I realise that this can also be done with Javascript, but that wouldn't allow me to use a Form.
$("#forward").click(function(){
var text = $("#ModelNumber").val();
var comparingText = "PIV13RT";
var comparingText2 = "PIV13RT2";
var comparingText3 = "PIV13RT3";
if (text == comparingText) {
$('.optionbk').fadeIn('slow');
}
if (text == comparingText2) {
$('.optionbk').fadeIn('slow');
}
if (text == comparingText3) {
$('.optionbk').fadeIn('slow');
}
});
Is there anyway that I can do it inside of a form, but make it so that the page doesn't reload itself so that the fade works instead of reloading. The form is needed because it is following that specific pattern. Please note that the form isn't linking to an external PHP file.
The quickest solution is to add onsubmit="return false" into your opening <form> tag.
You should bind your callback function to the submit event that the form dispatches and make it return false to cancel the actual submission.
$('form').bind('submit', function(){
$.ajax();
return false;
});

Submit form normally after validating with jquery

I'm using the jquery.form.js from here: http://www.malsup.com/jquery/form/. I want to validate the text of the text input from the form before submitting. Validation goes to
'search_validate.php'. This part works fine. If validation passes, the form action's is changed. That works too.
Getting the form to submit normally after changing the action attribute doesn't work. The browser never goes to the '/videos/search/' page. It stays on the same page. I see the '/videos/search/' page loading in Firebug over and over though.
<form id="search" method="post" action="">
<input type="text" id="query" />
<input type="image" id="searchmag" src="blah.jpg" ?>
</form>
<script>
$(function(){
$('#searchmag').click(function(){
$('#search').attr('action','/search_validate.php');
$('#search').ajaxForm(function(data, textStatus){
if ((data.indexOf('letters & numbers only')>-1)) {
$('#query').css('color','#FF0000').val(data);
$("#query").unbind("click").click(function(){
$('#query').css('color','#848484').val('');
});
} else {
$('#search').attr('action','/videos/search/' + $('#query').val());
$('#search').submit();
}
});
});
});
</script>
This always works for me:
$("#myForm").on("submit", function(event) {
event.preventDefault();
// Validate form, returning on failure.
$(this).off("submit");
this.submit();
});
I hope this helps!

How to change the value of textbox when form is submitted?

I have a form which has fields pre-filled with a default value, like this:
<input type=text name=first value="First Name" class="unfilled" />
When the textbox is clicked, the class unfilled is removed from the textbox, and the textbox is made blank so the user can type in his/her own info.
The problem is that when the form is submitted, its getting submitted with these default values, which is messing up the server side validation. How can I do it so that when the form is submitted, all the fields which have a default value are made blank, so the server side validation would throw the error: 'Please fill in this field'?
I'm trying the following code which isn't working:
$("#myForm").submit(function()
{
$(".unfilled").val('');
}
);
This does make the fields blank, but the server still receives them with their previous default values.
I think you simply have a syntax error. You're missing the closing parenthesis on your submit method.
I just whipped this up and it works fine
<!DOCTYPE html>
<html>
<body>
<?php
var_dump($_POST);
?>
<form action="test.php" method="post">
<input type="text" name="first" value="First Name" class="unfilled">
<input type="submit">
</form>
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js"></script>
<script type="text/javascript">
jQuery(function($) {
$('form').submit(function() {
$('.unfilled').val('');
});
});
</script>
</body>
</html>
You need to stop the form execution first, change the values, and then manually submit the form.
$("#myForm").submit(function(e)
{
// Stop the form submit
e.preventDefault();
$(".unfilled").val('');
$(this).submit();
}
You have to return true; if you want the form to submit, or false, if you don't.
The problem with this approach is that the fields will 'blink' before posting the values, thus creating a bit of unprofessional feel.
It is better to use hidden values and set them in submit() event.
I think you need the .click() function of JQuery.
Example:
$(function () { // shorthand for document.ready
$('.unfilled').click(function () {
$(this)
.val('')
.removeClass('unfilled');
})
});
UPDATE
Sorry, i missunderstand you, thought you need a feature like a placeholder.
Of couse you can do it with return false;, but this cancel the submitting. Or like GreenWebDev says to use e.preventDefault();.

Categories

Resources