Why isn't this javascript/form working - javascript

The user is supposed to be able to enter an address in the form and the Javascript will open a new window with the directions. But when the button is pressed, nothing happens. Can someone tell me what I'm doing wrong?
Javascript:
function ShowDirections() {
var street = document.getElementById('street').value;
var city = document.getElementById('city').value;
var state = document.getElementById('state').value;
var zip = document.getElementById('zip').value;
var from = street + ', ' + city + ', ' + state + ' ' + zip;
var url = "http://maps.google.com/maps?f=d&hl=en&saddr=" + from + "&daddr=1530+Commercial+Street%2c+East+Weymouth%2c+MA+02189";
window.open(url, 820, 700);
}
HTML:
<label for="street">Address or Intersection:</label>
<input name="street" type="text" id="street" />
<label for="city">City:</label>
<input name="city" type="text" id="city" />
<label for="state">State/Province:</label>
<input name="state" type="text" maxlength="2" id="state" />
<label for="zip">Zip/Postal Code:</label>
<input name="zip" type="text" maxlength="10" id="zip" />
<input type="button" value="Get Directions" onclick="javascript:ShowDirections();" />

javascript: isn't an acceptable action for form tags. It needs to be a URL. Take it all out of the form and place a handler on the submit button (as a button) and you might be closer.

you can use onsubmit to call javascript function

Related

Combine two textbox value into other textbox in lowercase with dash

I have two text type inputs. I want to convert them into one textbox(Lowercase with dash) while typing just like below.
<input type="text" name="first">
<input type="text" name="last">
I want combine this two text box into another textbox
Example: Nikhil Patel to nikhil-patel
I am trying to combine below inputs but can't.
function conv(){
var title, author;
title = document.getElementById("title").value;
author = document.getElementById("author").value;
/*converting to LowerCase*/
title = String.toLowerCase(title);
author = String.toLowerCase(author);
var out = title + "-" + author;
document.getElementById("output").value = output;
}
<div class="form-group">
<label>Title :</label>
<input class="form-control" type="text" name="title" id="title" />
</div>
<div class="form-group">
<label>Author :</label>
<input class="form-control" type="text" name="author" id="author" />
</div>
<div class="form-group">
<label>Output :</label>
<input class="form-control" type="text" name="output" id="output"/>
</div>
Output is not printing automatically
Try This if you want like this...
var input = $('[name="first"],[name="last"]'),
input1 = $('[name="first"]'),
input2 = $('[name="last"]'),
input3 = $('[name="final"]');
input.change(function () {
input3.val(input1.val() + ' - ' + input2.val());
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<input type="text" name="first" id="1" value="">
<input type="text" name="last" id="2" value="">
<input type="text" name="final" id="3" value="" readonly>
<HTML>
<HEAD>
<SCRIPT>
function conv(){
var first, second;
first = document.getElementById("first").value;
second = document.getElementById("second").value;
/*converting to LowerCase*/
first = String.toLowerCase(first);
second = String.toLowerCase(second);
var out = first + "-" + second;
document.getElementById("out").value = out;
}
</SCRIPT>
</HEAD>
<BODY>
<input type="text" name = "first" id="first" onkeyup = 'conv()'/>
<input type="text" name = "second" id ="second" onkeyup = 'conv()'/>
<input type="text" name = "out" id="out"/>
</BODY>
</HTML>
this is just a sample with 3 text boxes where
first two boxes will be for input
and third will auto populate using the javascript
I hope it'll help you. All is did was to add extra id's.

How do i get a send button to only submit and write to its own inputField?

I'm a beginner and I'm now stuck trying to figure out two things for the below code:
How do I code so that each of the send buttons only connects to its own input field?
How do I code so that each new text input overwrites the previous?
My code:
<h1>Data input</h1>
<input type="text" placeholder="Last name" id="inputField1" name="lastName" required>
<input type="button" value="Send" id="myButton1">
<br>
<br>
<input type="text" placeholder="First name" id="inputField2" name="firstName" required>
<input type="button" value="Send" id="myButton2">
<br>
<br>
<p id="lastName">Last name</p>
<p id="firstName">First name</p>
<script>
var b1=document.getElementById("myButton1")
b1.addEventListener("click", handleClick);
var b2=document.getElementById("myButton2")
b2.addEventListener("click", handleClick);
function handleClick(){
var i=document.getElementById("inputField1");
var iValue=i.value;
var d=document.getElementById("lastName");
var oldText=d.innerText;
var newText=oldText+"\n"+iValue;
d.innerText=newText;
var k=document.getElementById("inputField2");
var kValue=k.value;
var f=document.getElementById("firstName");
var oldText=f.innerText;
var newText=oldText+"\n"+kValue;
f.innerText=newText;
}
Here is a solution that sends a 1 or a 2 to the handleClick function as a parameter depending on which button you click. It then gets the value of the input that matches the number, checks to make see if it is empty, and outputs the name to the correct paragraph if it isn't and an error message if it is. Let me know if you have any problems with it.
var b1 = document.getElementById("myButton1");
b1.addEventListener("click", () => handleClick("1"));
var b2 = document.getElementById("myButton2");
b2.addEventListener("click", () => handleClick("2"));
function handleClick(iNum){
var i = document.getElementById("inputField" + iNum);
var iValue = i.value;
var d = document.getElementById("name" + iNum);
if (iValue != "") {
var pText = (iNum == "1" ? "Last" : "First");
var newText = pText + " name: " + iValue;
d.textContent = newText;
} else {
d.textContent = "Please enter a name!";
}
}
<h1>Data input</h1>
<input type="text" placeholder="Last name" id="inputField1" name="lastName" required>
<input type="button" value="Send" id="myButton1">
<br>
<br>
<input type="text" placeholder="First name" id="inputField2" name="firstName" required>
<input type="button" value="Send" id="myButton2">
<br>
<br>
<p id="name1"></p>
<p id="name2"></p>
Not really sure what's going on here, but usually you have to access the input field via the event: event.target.value (just put event as a parameter)

How to post data to server and capture response

I'm new to web development and stucked at sending data to server. I have registration form and i want to send this data to server. I can send data from form tag using action and method attribute but it will return response in next page. So i read somewhere i have to use ajax to send data. I tried but i cannot send and capture data using script.
This is my reponse
{"success":true}
Html code
<div class="form">
<div class="formdetail">
<h3>Individual Registration</h3>
<label for="fname"> Name</label><br>
<input type="text" size="40" id="name" name="name" placeholder="Enter your name.." required><br><br>
<label for="phonenumber">Mobile Number</label>
<br/>
<input id="mobileno" size="40" name="mobileno" type="tel" size="20" maxlength="13" placeholder="Enter your mobile number..." type="number" required><br><br>
<label for="email">Email-Id</label><br>
<input type="text" size="40" id="email" name="email" placeholder="Enter your email-id..." required><br><br>
<input type="date" id="dt" onchange="mydate1();" hidden/>
<input type="text" id="ndt" name="dob" onclick="mydate();" hidden />
<input type="button" Value="Date of Birth" onclick="mydate();" />
<script>
function mydate()
{
//alert("");
document.getElementById("dt").hidden=false;
document.getElementById("dob").hidden=true;
}
function mydate1()
{
d=new Date(document.getElementById("dt").value);
dt=d.getDate();
mn=d.getMonth();
mn++;
yy=d.getFullYear();
document.getElementById("dob").value=dt+"/"+mn+"/"+yy
document.getElementById("dob").hidden=false;
document.getElementById("dt").hidden=true;
}
</script>
<br><br>
<label for="address">Address</label><br>
<input type="text" id="address" size="40" name="address" placeholder="Enter your address..." required><br><br>
<label for="country">Country</label><br>
<input type="text" id="country" size="40" name="country" placeholder="Enter your country name....." required><br><br>
<label for="State">State</label><br>
<input type="text" id="state" size="40" name="state" placeholder="Enter your state name....." required><br><br>
<label for="city">City</label><br>
<input type="text" id="city" size="40" name="city" placeholder="Enter your city name....." required><br><br>
<input type="hidden" name="category" value="Individual">
<input type="submit" value="Submit" id="someInput" onclick="ajax_post()"><br>
<p class="small">Institute Registraion</p>
</div>
</div>
</form>
<script type="text/javascript">
function ajax_post(){
var hr = new XMLHttpRequest();
var url = "https://smilestechno.000webhostapp.com/Register.php";
hr.open("POST", url, true);
hr.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
hr.onreadystatechange = function(){
if (hr.readyState == 4 && hr.status == 200) {
var resp = console.log(response);
if (resp == "true") {
}
}
hr.send("name="+ name + "&mobileno=" + mobileno + "&email=" + email + "&dob=" + dob + "&address=" + address + "&city=" + city + "&state=" + state + "&country=" + country );
document.getElementById("status").innerhtml = "processing";
}
you can not send variable in this format.
var vars = name+mobileno+email+dob+address+city+state+country;
Params must have a format like:
hr.send("fname=Henry&lname=Ford");
Code you need:
hr.send("name=" + name + "&monbileno=" + mobileno + ... );
You can use jquery to use ajax in a simple way.
Reference:
xmlhttprequest https://www.w3schools.com/xml/ajax_xmlhttprequest_send.asp
jquery ajax https://www.w3schools.com/jquery/jquery_ref_ajax.asp
Use jquery, it makes it easier. This is how it should be using just the fname and email as an example with jquery ajax:
<form name="myForm" id="myForm" action="myActionUrl" method="POST">
<input type="text" name="fname" id="fname">
<input type="email" name="email" id="email">
<input type="submit" value="Submit">
</form>
<script
src="https://code.jquery.com/jquery-3.3.1.min.js"
integrity="sha256-FgpCb/KJQlLNfOu91ta32o/NMZxltwRo8QtmkMRdAu8="
crossorigin="anonymous"></script>
<script>
$("#myForm").on("submit", function(event){
event.preventDefault(); //this prevents the form to use default submit
$.ajax({
method: "POST",
url: $(this).attr("action"), //this will use the form's action attribute
data: {fname: $("#fname").val(), email: $("#email").val()},
success: function(responseData){
//do something here with responseData
}
});
});
</script>
Please replace the "myActionUrl" part with the url/file that processes your data.
The file can be some basic php file which stores the data into some database and returns or echoes something back so that you can use it within the "responseData" on the ajax success function.
Hope this helps!
Please call function like this
onclick="ajax_post()"
not
onclick="ajax_post"
You used getElementById but selected a name attribute
have to use
getElementById('fname').value;
not
getElementById('name').value;
hey i would recommend using jquery to accomplish this task.
this isthe client script
script type="text/javascript" src='jquery.js'></script>
<!-- download the lates version -->
<script type="text/javascript">
ajax_post(){
var url = "https://smilestechno.000webhostapp.com/Register.php";
var name = $("#name").val();
var mobileno = $("#mobileno").val();
var email = $("#email").val();
var dob = $("#dob").val();
var address = $("#address").val();
var city = $("#city").val();
var state = $("#state").val();
var country = $("#country").val();
var tmp = null;
$.ajax({
'async': false,
'type': "POST",
'global': false,
'dataType': 'json',
'url':url,
'data':{name:name,mobileno:mobileno,email:email,dob:dob,address:address,city:city,state:state,country},
'success': function (data) {
tmp = data;
}
});
return tmp; // you can access server response from this tmp variable
}
Server side
<?php
//get items as post inputs
print_r($_POST[]);
echo $_POST['name'];
?>

Use crypto.js to create text form generator

I want to create form for my user with two inputs area, the form will generate encrypt text that i can use it in javascript like user inter them in input form fields.
For example i have this html code
<div class='code'>john123/52544888822</div>
i want to make this john123/52544888822 encrypted and receive orgin text in javascript function.
HTML code:
<form class='form' name='form' action="" method="">
<input class="user" type="text" name="user" value="">
<input class="password" type="text" name="password" value=""/>
<input class="button" type="button" value="get code"/>
</form>
<div class='code'></div>
Javascript code:
$('.form').change("input", function() {
var form_user = $('.user').val(),
form_password = $('.form .url').val(),
form_button = $('.form .password');
form_button.click(function() {
$('.code').html('<span>[' + form_user + '][' + form_password + ']</span>');
});
});
First of all get your code fixed:
<form class='form' name='envato-form' action="" method="">
<input class="user" type="text" name="user" value="">
<input class="code" type="text" name="code" value="">
<input class="password" type="text" name="password" value=""/>
<input class="button" type="button" value="get code"/>
</form>
<div class='code'></div>
then javascript:
$('.form').change("input", function() {
var form_user = $('.form .user').val();
var form_code = $('.form .code').val();
var form_password = $('.form .password').val();
var form_button = $('.form .button');
form_button.click(function() {
$('.code').html('<span>' + form_user + form_code + '/' + form_password + '</span>');
});
});
then crypto.js
var SHA256 = require("crypto-js/sha256");
$('.code').append('<br><span>'+SHA256($('.code .span').html())+'</span>');
All the best!

jQuery.ajax putting unwanted parameters in URL

I am using $.ajax to insert and update a database. I have a <form> on a webpage, and the $.ajax looks like this:
$('.submit-create-customer').on('click touchstart', function() {
var first_name = $('#first_name').val();
var last_name = $('#last_name').val();
var email = $('#email').val();
var confirm_email = $('#confirm_email').val();
var phone = $('#phone').val();
var address = $('#address').val();
var address_2 = $('#address_2').val();
var city = $('#city').val();
var state = $('#state').val();
var zipcode = $('#zipcode').val();
var formData = "first_name=" + first_name + "&last_name=" + last_name + "&email=" + email + "&confirm_email=" + confirm_email + "&phone=" + phone + "&address=" + address + "&address_2=" + address_2 + "&city=" + city + "&state=" + state + "&zipcode=" + zipcode;
$.ajax({ // Start the PHP submission
url : "/resources/submit.php?action=createCustomer",
type: "POST",
data : formData,
success: function(data, textStatus, jqXHR) { //data - response from server
alert('success');
},
error: function(data, textStatus, jqXHR) {
alert('failure');
}
});
});
HTML:
<form class="validate">
<div class="col-md-6">
<input class="form-control input-md validate-name" id="first_name" name="first_name" minlength="2" type="text" placeholder="First Name">
<input class="form-control input-md validate-name" id="last_name" name="last_name" minlength="2" type="text" placeholder="Last Name">
<input class="form-control input-md validate-email" id="email" name="email" minlength="2" type="text" placeholder="Email">
<input class="form-control input-md validate-email" id="confirm_email" name="confirm_email" minlength="2" type="text" placeholder="Confirm Email">
<input class="form-control input-md validate-phone" id="phone" name="phone" type="text" placeholder="Phone">
</div>
<div class="col-md-6">
<input class="form-control input-md validate-address" id="address" name="address" type="text" placeholder="Address">
<input class="form-control input-md validate-address" id="address_2" name="address_2" type="text" placeholder="Address Line 2">
<input class="form-control input-md validate-name" id="city" name="city" type="text" placeholder="City">
<select class="form-control input-md validate-select" id="state" name="state">
<option value="-1" disabled selected>State</option>
<option value="AL">Alabama</option>
<option value="AK">Alaska</option>
<option value="WI">Wisconsin</option>
<option value="WY">Wyoming</option>
</select>
<input class="form-control input-md validate-zipcode" id="zipcode" name="zipcode" type="text" placeholder="Zipcode">
</div>
<button class="btn btn-md submit-create-customer" disabled>Submit</button>
</form>
The URL returns either true or false. After I get the alert, the same webpage that I made the request from gets reloaded with a bunch of URL parameters. It looks something like this:
/customers.php?first_name=Trevor&last_name=Hutto&email=this%40that.com&confirm_email=this%40that.com&phone=1234567891&address=1234+Memory+Lane&address_2=Apt.+1131&city=New+York&state=NY&zipcode=12345
Why is this happening when I have declared the request type as POST? Also, isn't the point of AJAX to be asynchronous and make request in the background? Why is the page reloading?
My guess is that since you don't prevent the normal action from firing the browser runs your code and after that behaves the way it would normally.
Try changing:
$('.submit-create-customer').on('click touchstart', function() {
// Other code
To:
$('.submit-create-customer').on('click touchstart', function(e) {
e.preventDefault();
// Other code
Edit: Also, if this is a form, I can highly recommend the jQuery.form plugin (http://malsup.com/jquery/form/).
One more thing, if this is indeed a form, don't hook a click event to the submit button, instead hook a submit event to the actual form. This way users can submit the form in any way and it will still be handled with ajax.
I think it'd help if you showed your HTML as well.

Categories