Making a HTML form submit to different places - javascript

Hoping someone can help with this. I have a form which has an action attribute. This action attribute enables the user to subscribe to a newsletter when the form is submitted.
What I'm trying to do is only use that action if the user has checked a checkbox giving permission to subscribe to the newsletter. If the checkbox is left unchecked, the form can still be submitted, but will be redirected to a separate URL, disregarding the form's action attribute.
So far this is what I have, I'm not great with javascript so any help would be appreciated.
$('document').ready(function () {
$('#wifi-capture-form').submit(function() {
var newsletterTrue= $(this).attr("data-newsletter-checked");
var newsletterFalse= $(this).attr("data-newsletter-unchecked");
if ($('input.newsletter-checkbox').is(':checked')) {
$('#wifi-capture-form').attr('action', newsletterTrue);
else (
$('#wifi-capture-form').attr('action', newsletterFalse);
)
}
});
});
and the form is
<form name="wifi-capture-form" id="wifi-capture-form" action="" method="post" class="f24form wifi-capture-form" data-newsletter-checked="https://email.com/t/r/s/dkhywr/" data-newsletter-unchecked="https:www.domain.com/wifi-confirm">
<label for="fieldName">Name</label><br />
<input id="fieldName" name="cm-name" class="form-control" type="text" />
<label for="fieldEmail">Email</label><br/>
<input id="fieldEmail" class="form-control" name="cm-dkhywr-dkhywr" type="email" required /><br/><br/>
<input type="checkbox" name="newsletter" class="newsletter-checkbox" id="newsletter" value="Subscribe to newsletter"> Subscribe to our newsletter<br/><br/>
<button type="submit" class="btn btn-primary">Submit</button>

You can do it by changing the action attribute value of the form on submit. Here is the syntax:
$("#wifi-capture-form").attr("action", wifiConfirm);
So your new code must be like this:
$('#wifi-capture-form').submit(function(e) {
var wifiConfirm = $(this).attr("data-redirect");
/* if newslwetter checkbox is not checked, then change form action value*/
if (!$('input.newsletter-checkbox').is(':checked')) {
$("#wifi-capture-form").attr("action", wifiConfirm);
}
f24("send", "form", "form.#wifi-capture-form");
});
You can see other examples on How to change form action based on selection

Since you're using jQuery you can assign a click event to the checkbox that would dynamically change the action URL in case the checkbox is checked/unchecked.

Related

How to embed form data in the action link?

I have a form defined:
<form method="post">
<label for="phone_or_uid">Enter a phone number or uid:</label>
<input type="text" name="phone_or_uid" value=""></input>
<input type="submit" name="" value="Submit"></input>
</form>
Currently, when this form is submitted I am able to work with the data and add info to the page based on the value of phone_or_uid. However, what I'd like to do is something where the form redirects to the same page but with the value of phone_or_uid appended to the end. So, if the initial page is https://myhost.com/lookup then submitting the form should bring the user to https://myhost.com/lookup/16175431234 if the value of the phone_or_uid input box is 16175431234.
Essentially, my form should then look something like this:
<form action={some code that puts the value of phone_or_uid here}>
...
</form>
Is this possible? And if so, how could I accomplish this? I don't want to create or redirect to any extra files, if possible.
I would use JavaScript. Listen for the submit event and redirect to a custom url.
this is just a really general example:
<form method="post" onsubmit="submitFunction()">
<label for="phone_or_uid">Enter a phone number or uid:</label>
<input type="text" name="phone_or_uid" id="phone_or_uid" value=""></input>
<input type="submit" name="" value="Submit"></input>
</form>
<script>
submitFunction = (event) => {
event.preventDefault();
const phoneInfo = document.getElementById('phone_or_uid').value;
fetch('http://myhost.com/lookup/' + phoneInfo, {
method: 'post'
})
.then(response => {
window.location.href = "http://myhost.com/lookup/' + phoneInfo";
});
}
</script>

After submit, input text disappears and reload the page(AJAX)

Why my page reloads even I used ajax to it and it also disappears my input text after clicking the submit button. I already used show to solve it but it doesn't work.
<form method="POST" action="<?php $_SERVER['PHP_SELF'];?>">
<input type="text" name="name" id="name">
<span id="namenotif" style="color:red;"> <span>
<br>
<input type="text" name="price" id="price">
<span id="pricenotif" style="color:red;"> <span>
<br>
<input type="submit" name="submit" id="save"><br>
</form>
<script>
$(document).ready(function() {
$(document).on("click","#save",function(){
var name = $("#name").val();
var price = $("#price").val();
if(name==""){
$("#namenotif").html("Enter a name");
$("#name").show("fast");
$("#save").show("fast");
}
else if(price==""){
$("#pricenotif").html("Enter a price");
$("#price").show("fast");
$("#save").show("fast");
}else{
$.ajax({
url:"addproduct.php",
type:"POST",
data:{name:name,price:price},
success:function(data){
alert("Successful");
}
});
}
});
});
</script>
add return false to end of function, that handle click event
Two solutions:
Change the button type='submit' to type='button'
or ( and preferably )
Change the event listener to listen for the form's onSumbit event then call event.preventDefault or in jQuery, I think you just do return false in the callback.
The form is being submitted I think, because it is the default behavior of submit button to submit the form, no matter if you used ajax or not. so you can prevent the default behavior by simple adding a code in jquery. Modify the code like this:
$(document).on("click","#save",function(e){
e.preventDefault();
...............
Rest of the codes can remain same. so only prevent the default action, it should work.
Its because of type="submit"
Use
<input type="button" name="submit" id="save"><br>
Or
<a href="javascript:void(0) id="save">
or
jquery's preventDefault();

Javascript send variable post

i've got this script that send the variable recordID with GET (and works OK)
<input type="hidden" id="suggest1_hidden" name="suggest1_hidden" value="">
<input name="suggest1" type="text" class="suggest_table {th : ['nome', 'email', 'tel', 'cell']}" id="suggest1" style="width:650px;" alt="Adm_ut_search.php" />
<span id="comando"><span class="button">Dettagli utente</span></span>
<script language="javascript">
$(document).ready(function()
{
$('#comando').click(function () {
var url="Adm_ut_view_details.php?recordID=" + $('#suggest1_hidden').val()
document.location.href = url
});
});
</script>
I need to send the variable with POST and i wrote this... but doest work
<form id="myForm" action="Adm_ut_view_details.php" method="post"/>
<input type="hidden" id="suggest1_hidden" name="suggest1_hidden" value="">
<input name="suggest1" type="text" class="suggest_table {th : ['nome', 'email', 'tel', 'cell']}" id="suggest1" style="width:650px;" alt="Adm_ut_search.php" />
<input name="recordID" type="hidden" id="userID" value="" />
<button type="submit" id="comando">Submit</button>
</form>
<script language="javascript">
$(function(){
$('#myForm').on('submit', function(e){
document.getElementById('userID').value=+ $('#suggest1_hidden').val()
$('#myForm').submit();
});
});
</script>
what i do wrong ?
There is nothing inherently different that you need to do with your form fields because you are sending a POST request vs. a GET request. Changing the form's action to POST is all you need to do as long as no JavaScript pre-submit processing is desired.
And, the hidden form field is going to be sent along with the other form fields anyway, so why bother concatenating it to the userID?
But, to your question and your code, you have a typo:
document.getElementById('userID').value =+ $('#suggest1_hidden').val()
Should be:
document.getElementById('userID').value += $('#suggest1_hidden').val()
Now, you have code that sets up your submit event handler, but you have no code that sets the value of the hidden form field. That needs to be done prior to the submit taking place.
Also, you need to prevent the form from submitting first, so that you can modify the form field value.
$(function(){
$('#myForm').on('submit', function(e){
e.preventDefault(); // Stop the submit
// YOU NEED TO MAKE SURE THAT THE HIDDEN FORM FIELD'S
// VALUE HAS BEEN SET BY THIS POINT.
document.getElementById('userID').value += $('#suggest1_hidden').val()
$('#myForm').submit(); // Then manually submit
});

How to submit form data in ajax using enter in the keyboard

I am creating a comment functionality and below are my code so far.
html
<form action="http://website.com/transaction_items/add_comment" class="" id="form-comment" role="form" method="post" accept-charset="utf-8">
<input type="hidden" name="checklists_item_id" value="6" style="display:none;">
<input type="hidden" name="user_id" value="1" style="display:none;">
<div class="input-group col-xs-12">
<input type="text" name="comment" value="" class="form-control" id="comment-input" placeholder="Enter your comments..">
<span class="input-group-btn">
<button class="btn btn-default" id="doc-comment" type="button">Post</button>
</span>
</div>
</form>
jQuery
This function is called when document is ready.
function comment () {
$('#doc-comment').click(function (e) {
var form_id = '#' + $(this).parents('form').attr('id');
// submit data from the form
submit.send(form_id);
});
}
The problem:
Using the button <button class="btn btn-default" id="doc-comment" type="button">Post</button> to submit data work fine, but
if I use enter in the keyboard, submit.send(form_id); will not do its function, instead the default form submission will execute.
How can I use ajax if use enter in the keyboard to submit form data?
nutshell
$("#form-comment").on('submit', function(evt) {
evt.preventDefault();
// do your ajax stuff here
});
you can then toss the onclick button listener.. as this will handle the button submit as well
There are more ways to submit a form then simply pressing the submit button.
You need to:
Use the forms submit method
Keep the form from doing the full submit.
-
// This will catch the *enter* as well as the submit button
$("#form-comment").on('submit', function(evt) {
evt.preventDefault();
// You can then submit the form via ajax and update things as needed.
});
IF you are going to use a button you should at least do a
<button type="button">...</button>
which behaves differently.
$("#form-comment").keyup(function (e) { // On pressing enter
if (e.keyCode == 13) {
// put your ajax code here
}
});
You may have to disable the default Enter event for the form submit button as well depending on your browser.
So in the Jquery Button click function make sure you have something like
event.preventDefault();

Trigger html form submit as if you clicked on button (but without a button)?

If you have a <form> and a <button type='submit'> and you click on the submit button, it will do the default form validation, such as checking whether an <input> is required or not. It would normally say Please fill out this field.
However, if I programmatically submit the form through $("form").submit() for example, it would submit it without performing any checks.
Is there a simpler way to perform the default form validations using native JavaScript? There seems to be only checkValidity() on the form element which return true or false. And if I call the same native function on the input itself, it doesn't really do anything.
Here is a demo code of what I mean:
http://jsfiddle.net/totszwai/yb7arnda/
For those still struggling:
You can use the Constraint validation API - https://developer.mozilla.org/en-US/docs/Web/API/Constraint_validation
<div id="app">
<form>
<input type="text" required placeholder="name">
<input type="text" required placeholder="email">
</form>
<button id="save">Submit</button>
</div>
const form = document.querySelector("form");
document.getElementById("save").addEventListener("click", e => {
e.preventDefault();
if (form.checkValidity()) {
console.log("submit ...");
} else {
form.reportValidity();
}
});
Check out and play here: https://stackblitz.com/edit/js-t1vhdn?file=index.js
I hope it helps or gives you ideas. :)
I think this might be the answer you are looking for :
JavaScript :
document
.getElementById('button')
.addEventListener("click",function(e) {
document.getElementById('myForm').validate();
});
HTML :
<form id="myForm" >
First name: <input type="text" name="FirstName" required><br>
Last name: <input type="text" name="LastName" required><br>
<button id="button">Trigger Form Submit</button>
</form>
Demo : http://jsfiddle.net/2ahLcd4d/2/

Categories

Resources