Open a link using onsubmit - javascript

I have the following mock snippet:
JS :
function generateLink()
{
var A = document.getElementById('AAA').value;
var B = document.getElementById('BBB').value;
if(B == "1" || B == "2")
link ='http://' + B + '.' + A + '.domain';
else if(B == "3" || B == "4")
link ='http://' + B + '.' + A + '.domain/link.jsp';
else
link ='/404.html';
return link;
}
function showLink()
{
var link = generateLink();
document.getElementById("link").href = link;
document.getElementById("link").innerHTML = link;
}
document.formName.onsubmit = function(){
this.action = generateLink();
}
HTML :
<form name="formName" target="_blank">
<div style="margin: 0 auto; width:600px;">
<div style="float:left;"><span>Pick AAA</span><br>
<select id="AAA" onchange="showLink()">
<option value="11">Eleven</option>
<option value="12">Twelve</option>
<option value="13">Thirteen</option>
<option value="14">Fourteen</option>
</select>
</div>
<div style="float:right;"><span>Pick BBB</span><br>
<select id="BBB" onchange="showLink()">
<option value="1">One</option>
<option value="2">Two</option>
<option value="3">Three</option>
<option value="4">Four</option>
</select>
</div>
<div style="float:left; margin-left:120px; margin-right: 40px; margin-top:70px;">
<br><br>
<input type="submit" value="Go to"><br><br>
<input type="reset" value="Reset Selection">
</div>
When I run this code what happens is that the href opens the correct url in a new tab, while the submit button opens the page I am currrently on in a new tab. I am not sure what I am doing wrong. Doesn't the document.formName.onsubmit suppose to make the submit button work the same as the href?

I tried to setup a fiddle with your code, and it worked well enough. But while doing it, I realized I had to move a piece of code around to avoid a small problem, so I'm going to guess that you are having the same situation.
My guess is that you have all your JavaScript code before the HTML. When this part
document.formName.onsubmit = function(){
this.action = generateLink();
}
is executed, the form does not exist yet, and the onsubmit can't be set (you should see an error about it in your console, too). When you click on your submit button later, the form has no action defined, and just goes to the same page (its default behaviour). Here's a fiddle having with this problem.
The simplest fix is moving the onsubmit assignment after the form. Here's the same fiddle, with the relevant code moved, that actually does what you expect.

You want to set an action="" on the
<form>
tag. When the form is submitted, it will submit to the page defined in action="". If not defined, it will submit back to the same page by default.

Related

How to direct user to an specific page depending on selection they made after form submission?

I have created a list with 6 options and users can only select one. I want that whenever a user selects an option from the list after they submit the form it directs them to a specific page depending on which selection.
Eg. I have 3 options
Facebook
Youtube
Twitter
If the user selects option 1 after submission it will direct them to the Facebook page, if they select option 2 it will direct them to a youtube page .. etc
This is quite simple. You just have to get the value from the selector & use JS to open that link. Check my solution for reference -
solution on JS Fiddle
function myFunction() {
let link =
document.getElementById("social").value
let fb = "https://facebook.com"
let tw = "https://twitter.com"
if(link == 'fb') {
window.open(fb);
} else if (link == 'tw') {
window.open(tw);
}
}
<select id="social">
<option value="fb">Facebook</option>
<option value="tw">Twitter</option>
</select>
<button onclick="myFunction()">
go to site
</button>
This somehow doesn't work here, working on JS Fiddle
<body>
<form>
<select name="" id="target">
<option value="facebook">Facebook</option>
<option value="youtube">Youtube</option>
<option value="twitter">Twitter</option>
</select>
<button type="button" id="sub_button">submit</button>
</form>
<script>
const data = {
facebook: 'https://facebook.com',
youtube: 'https://youtube.com',
twitter: 'https://twitter.com',
}
document.querySelector('#sub_button').onclick = function() {
let target = document.querySelector('#target').value;
window.location.href = data[target];
}
</script>
</body>

how can insert all table's rows from script to database at once

I have a problem ... here the create table's row each time user press Add button , How I can send all the data of the table to database at once cuz when press submit only last row inserted into database but not all the table but it should submit all rows with all data
I'm new in php so I don't have a lot in php code
this is the php code
<?php
include_once("dbinfo.php");
session_start();
$name= $_SESSION['user'];
if(isset($_POST['savepav'])){
date_default_timezone_set("Asia/Riyadh");
$pavdate= date("Y/m/d");
$pavtime=date("h:i:sa");
$pavloca=$_POST['pavlocation'];
$pavtype=$_POST['ddlPassport'];
$pavdist=$_POST['pavedist'];
$pavplan=$_POST['pavplan'];
$pavseve=$_POST['pavseverity'];
echo "<script>alert(' Pavement data saved successfully ');</script>";
$query="INSERT INTO `pevement`(`userName`, `plocation`, `pavType`, `padistr`, `pavplan`, `severity`, `pavdate`, `pavtime`) VALUES ('$name' ,'$pavloca', '$pavtype', '$pavdist' ,'$pavplan', '$pavseve', '$pavdate' ,'$pavtime')";
$result_query=mysqli_query($conn,$query);
}
?>
this is script code
<script>
function AddData() {
var rows = "";
var name = document.getElementById("locapavm").value;
var city = document.getElementById("sevepavm").value;
var plan = document.getElementById("planpavm").value;
rows += "<tr><td>" + name + "</td><td>" + city + "</td><td>" + plan + "</td><td><button onclick = deleterow(this)>Delete</button></td></tr>";
$(rows).appendTo("#list tbody");
}
function ResetForm() {
document.getElementById("person").reset();
}
function deleterow(el) {
$(el).closest('tr').remove();
}
</script>
and HTML
<html>
<div id = "data">
<form id = "person">
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<div class="col-12" style="width: 1514px">
<select id = "locapavm" name = "pavlocation" style="width: 26%">
<option value="">- Location -</option>
<option value="Runway 17">Runway 17</option>
<option value="Runway 35">Runway 35</option>
<option value="Runway 18">Runway 18</option>
<option value="Runway 36">Runway 36</option>
</select><br>
<div class="col-12">
<select id = "ddlPassport" name = "ddlPassport" style="width: 26%" onchange = "ShowHideDiv()">
<option value="">- Pavement Type -</option>
<option value="Flexible Pavement (Asphalt)">Flexible Pavement (Asphalt)</option>
<option value="Rigid Pavement (Concrete)">Rigid Pavement (Concrete)</option>
</select>
</div><br/>
<div class="col-12" style="width: 1514px">
<select id="pavdistrees" name="pavedist" style="width: 26%">
<option value="">- Distress selections - </option>
</select><br> </div>
<div class="col-12" style="width: 1514px">
<select id="sevepavm" name="pavseverity" style="width: 26%">
<option value="">- Severity -</option>
<option value="Low">Low</option>
<option value="Medium"> Medium</option>
<option value="High">High</option>
</select><br> </div>
<!----------------------------------------------------------------------->
<p class="auto-style1">Maintenance Plan:</p>
<textarea id="planpavm" name="pavplan" style="width: 572px; height: 129px" ></textarea><br>
<input id = "person" type = "reset" value = " Reset " onclick = "ResetForm()">
<input id = "button" type = "button" value = " Add " onclick = "AddData()">
</form>
</div>
<div id = "tab" style="width: 76%">
<table style="width: 96%" id = "list" cellspacing = "0px" cellpadding = "20px" text-align = "center">
<thead>
<tr>
<td>Location</td>
<td>Pavement Type</td>
<td>Type Distrees</td>
<td>Severity</td>
<td style="width: 396px">Maintenance Plan</td>
</tr>
</thead>
<tbody>
</tbody>
</table>
</div>
<br><input type="submit" name="savepav" value="Submit"/>
</html>
I see you are using JQuery, so just based on that I think XHR would be your best bet. If you are adding it to the table with the "add" button, then I don't really see the point of the "Submit" button other than to redirect to a different page, so I will omit it just for this example, and edit my answer later if you have a different plan for it.
Your PHP code looks fine, other than it is vulnerable to an SQL injection attack. To prevent this, I would call the mysql_real_escape_string method on all of the strings you are putting in the database like so:
$pavloca=mysql_real_escape_string($_POST['pavlocation']);
$pavtype=mysql_real_escape_string($_POST['ddlPassport']);
$pavdist=mysql_real_escape_string($_POST['pavedist']);
$pavplan=mysql_real_escape_string($_POST['pavplan']);
$pavseve=mysql_real_escape_string($_POST['pavseverity']);
For the HTML, I would give your Add button the type of submit, then add the action and method attributes to your opening form tag like so:
<form id = "person" method = "POST" action = "/path/to/php/page">
where /path/to/php/page is the path to the PHP page that adds everything to the database.
And finally for the JavaScript.
Instead of having the onclick attribute on your Add button, I would remove that then just add this bit of JQuery to your script tag:
$("#person").submit(function(d){
d.preventDefault();
AddData(new FormData(d.target));
})
Then for your AddData function add an input parameter for the form:
function AddData(form)
P.S, a little trick after you've done that, you can actually get the values by the name attribute rather than an id like so:
var name = form["pavlocation"];
var city = form["pavseverity"];
var plan = form["pavplan"];
Then last but not least, add this little bit of code to the end of your AddData() function:
var xhr = new XMLHttpRequest();
xhr.open(form.method, form.action);
xhr.send();
And that should be it!
NOTE: I did not test any of this, so I apologize for any typos or syntax errors. If this does not work, I will edit my answer accordingly.
EDIT: There were a couple out-of-order tags in the HTML you posted, so I ran it through an IDE to clean it up a bit, and created a JSFiddle for it here: https://jsfiddle.net/djy9vget/2/
You will have to change the action="/path/to/php/page.php" bit to the actual path, but other than that this should work. I also noticed a typo in my original answer where XmlHttpRequest(); should be XMLHttpRequest();.
I also changed the ID of the Reset button from person (which is the same as the form), to reset.

How to change button URL through JS?

I have been spending a lot of time researching how to change a button href dynamically in my website using JS. I have a functioning Wordpress website, but would like to add some small additional functionality using JS to change a button's link based on a few user options.
I have researched this and found answers, but I absolutely cannot get the solutions to work on my site.
One of the simplest solutions that should work was found here:
How to make option selection change button link?
I can't understand what is different between what I am trying to accomplish and what the accepted answer proposed. I added window.onload() to prevent the JS from running before elements were loaded.
I am trying to do something similar with the following HTML & JS code:
HTML Code:
<input type="hidden" id="input-book-type" value="GlassCrystal">
<br><br>
<select id="select-page-size">
<option value="6x6">6" x 6"</option>
<option value="10x10">10" x 10"</option>
</select>
<br><br>
<input id="input-project-title" value="Optional Project Title">
<br><br>
<a class="button" id="design-button" href="http://">Design Now</a>
JS Code:
window.onload = function() {
document.getElementById("design-button").onclick = function() {
var booktype = document.getElementById("input-book-type");
var pagesize = document.getElementById("select-page-size");
var projtitle = document.getElementById("input-project-title");
this.href = "http://test/?sessionid=guest&ref="+booktype.value+pagesize.value+"&projectName="+projtitle.value+"/";
};
}
JS Fiddle:
https://jsfiddle.net/w65c9x2d/
I think your code to change the href is correct. However, the onload function is not immediately invoked for the code to work.
window.onload = function(e) {
var booktype = document.getElementById("input-book-type");
var pagesize = document.getElementById("select-page-size");
var pagenum = document.getElementById("select-page-num");
var projtitle = document.getElementById("input-project-title");
document.getElementById("design-button").onclick = function() {
this.href = "http://design.framesmile.com/?sessionid=guest&ref=" + booktype.value + pagesize.value + "*projectName=" + projtitle.value + " / ";
console.log(this.href);
};
}();// invoke the function
<input type="hidden" id="input-book-type" type="" value="GlassCrystal">
<br>
<br>
<select id="select-page-size">
<option value="6x6">6" x 6"</option>
<option value="10x10">10" x 10"</option>
</select>
<br>
<br>
<select id="select-page-num">
<option value="20">20</option>
<option value="22">22</option>
</select>
<br>
<br>
<input id="input-project-title" type="" value="Optional Project Title">
<br>
<br>
<a class="button" id="design-button" href="http://test/">Design Now</a>
Here is example code:
jhg
jhhghj
<script type="text/javascript">
document.getElementById("myLink").onclick = function() {
document.getElementById("abc").href="xyz.php";
return false;
};
</script>
I took this from here
Change your button to this:
<button class="button" id="design-button" onclick="redirect()">Design Now</button>
Now instead of using a link, simply do a function that will take the inputs and change the window.location.href (or whatever method you prefer) to change the page.
redirect(obj) {
window.location.href = "http://test/?sessionid=guest&ref="+booktype.value+pagesize.value+"&projectName="+projtitle.value+"/"
}
Obviously change it to your liking :)
I recommend using jQuery.
$("#submit").on('click', function(event) {
event.preventDefault();
data = $("#link").val();
$("#frame").attr({
src: "http://"+data});
});
When the submit button is clicked, it changed the iframe url which changed the content of the iframe automatically.
I don't really understand what you are trying to ask, but try to modfiy the code above :)

How to refresh page each time you press submit button?

I'm new to Javascript and HTML.
I have the following form in HTML:
<div id="form-select">
<form id="date_form" onsubmit="return myFunction();">
<datalist id="dates">
<option value="February 7">February 7</option>
<option value="February 14">February 14</option>
<option value="February 21">February 21</option>
<option value="February 28">February 28</option>
</datalist>
<input type="text" class="input" name="data" id="date" value="" list="dates" placeholder="pick a date"><br>
<input type="submit">
</form>
</div>
Here's the javascript in a file called script.js. The js file is linked in the header as <script type="text/javascript" src="script.js" />:
function myFunction(){
var input = document.getElementById("date").value;
if(input==="February 7"){
document.getElementById('w1').innerHTML = document.getElementById('w1').innerHTML + "<h2> HEADING </h2>";
}
return false;
};
When I fill out the form and hit submit, the javascript correctly executes the function and adds "HEADING." However, when I press submit again, it adds "HEADING" a second time under the first instance of it.
How do I make it so that the page "refreshes" each time submit is pressed?
Thanks!
You can Use
window.location.reload();
In your Submit event code..
use jQuery, bind('submit', function(e){ e.preventDefault; ....; })
$('#date_form').submit(function(e){
e.preventDefault();
var input = document.getElementById("date").value;
if(input==="February 7"){
document.getElementById('w1').innerHTML = "<h2> HEADING </h2>";
}
return false;
});
Found another way around the issue. I added the statement:
document.getElementById('week').innerHTML = "";
at the beginning of each call of the function. That way, every time the user clicks submit, the div is emptied out before it is repopulated.

Get selection with Bootstrap Drop Down and go to page

I'm working with the Bootstrap drop down and I've got everything working except the final thing I need it to do. The user will select 1 of 3 options and then click 'Go!'. After clicking go it will check what the user chose and then redirect them to the correct page.
Here's what I had in JavaScript.
function gotopg() {
var s = document.getElementById('selection');
var selection = s.options[s.selectedIndex].value;
if (selection == 1) {
window.location.href = 'OptionOne.html';
}
else if (selection == 2) {
window.location.href = 'OptionTwo.html';
}
else if (selection == 3) {
window.location.href = 'OptionThree.html';
}
}
And here's the HTML
<div>
<select class="selectpicker" title='Choose your form...' id="selection" onChange="changed()" autofocus>
<option style="text-align: left;">OptionOne</option>
<option style="text-align: left;">OptionTwo</option>
<option style="text-align: left;">OptionThree</option>
</select>
<script type="text/javascript">
$(document).ready(function(e) {
$('.selectpicker').selectpicker();
});
</script>
</div>
<br>
<br>
<button id="go" onClick="gotopg()" disabled="disabled" style="font-size: 20px;">Go!</button>
This was working just fine before I added in the Bootstrap Drop Down, now nothing is happening when clicking Go!. What do I have to do to get this working with the Bootstrap Drop Down?

Categories