I have created form fields with a button.
I need the url of the button to change depending on the data entered in the Last name field. The Booking reference field does not effect the url
Example: User enters "John" in the last name field the button should have the url: http://www.john.com
Example: User enters "Henry" in the last name field the button should have the url: http://www.henry.com
<form>
<p style="margin-bottom: -10px; font-size: 12px;">*Required Fields</p><br>
<input type="text" placeholder="Last name *" name="lastname">
<input type="text" placeholder="Booking Reference *" name="ref">
Retrieve booking
</form>
You can use blur event on lastname to achieve this,
$('input[name=lastname]').on('blur', function(){
debugger
var lastName = $('input[name=lastname]').val()
//check if last name is there
if(lastName.length !== 0){
var link = 'http://www.'+ lastName +'.com';
$('.btn.btn-info').attr('href',link);
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form>
<p style="margin-bottom: -10px; font-size: 12px;">*Required Fields</p><br>
<input type="text" placeholder="Last name *" name="lastname">
<input type="text" placeholder="Booking Reference *" name="ref">
Retrieve booking
</form>
My answer in ES6 style:
https://codepen.io/powaznypowazny/pen/GvxGMY
function retrieveURL() {
const anchor = document.querySelector('.btn.btn-info');
const input = document.querySelector('input[name=lastname]');
input.addEventListener('keyup', () => {
let value = input.value.toLowerCase();
anchor.href = `http://www.${value}.com`;
});
}
document.addEventListener("DOMContentLoaded", function(event) {
retrieveURL();
});
Try this:
$(document).ready(function()
{
$('.btn btn-info').click(function() {
var value = $("input[name='lastname']");
if(value.length > 0)
{
var hrefVal = $('a').attr('href');
hrefVal.replace('example' , value);
$('a').attr('href' , hrefVal);
}
});
});
<form>
<p style="margin-bottom: -10px; font-size: 12px;">*Required Fields</p><br>
<input type="text" placeholder="Last name *" name="lastname">
<input type="text" placeholder="Booking Reference *" name="ref">
Retrieve booking
</form>
Related
I am having 6 bootstrap cards where the details of the card are id, image, content.on clicking the card I am getting the details of the card into the local storage and from that, I am extracting the ids into another array named styleIds I want these styleIds values to sent as value to the input field as onload of body
My js code:
var styles = []
var styleIds = []
function getStyle(id) {
if (styles.length > 0) {
var data = { id: id, image: $("#img_"+id).attr('src'),content: $("#cont_" + id).text() }
var x = JSON.stringify(data)
var index = styles.indexOf(x)
if (index == -1) {
styles.push(x)
}
else {
styles.splice(index, 1)
}
}
else {
var data = { id: id, image: $("#img_"+id).attr('src'),content: $("#cont_" + id).text() }
var x = JSON.stringify(data)
styles.push(x)
}
localStorage.setItem("styles", JSON.stringify(styles))
styleIds = styles.map(element => JSON.parse(element).id);
console.log(styleIds)
assample();
}
function assample() {
$("#style").val(styleIds);
console.log(styleIds)
}
function initStyles() {
var storedNames = JSON.parse(localStorage.getItem("styles") || '[]');
styleIds = storedNames.map(element => JSON.parse(element).id);
}
My form code is:
<body onload = "sample();initGoals();issample();assample();initStyles();">
<div class="form-group">
<label for="username">Username</label>
<input type="text" name="username" class="form-control" required>
</div>
<div class="form-group">
<input type="text" name="room" id="name" value=" ">
</div>
<div class="form-group" >
<input type="text" name="goal" id="goal" value=" ">
</div>
<div class="form-group" >
<input type="text" name="style" id="style" value=" ">
</div>
<div class="form-group">
<label for="email">Email</label>
<input type="text" name="email" class="form-control" required>
</div>
<div class="form-group">
<label for="password2">Password</label>
<input type="password" name="password" class="form-control" required>
</div>
<input type="submit" value="Register" class="btn btn-secondary btn-block">
</form>
The cards are on one page and the form is the another web page so in the styles page the styleIds array is getting the ids butwhen I navigate to the form page the values are getting as a value for the field in the form what is the mistake I did?
Make sure you're calling the functions in the correct order. Also, I would suggest renaming your function names so that you don't get confused.
You can change your onload to just call one function and later care about the order.
<body onload = "doSomething()">
and in the script:
function doSomething() {
sample();
initGoals();
issample();
initStyles();
assample();
}
I'm trying to create a form where the user fills out their details, the form currently doesn't send if one of the fields has no input in it because I have added in a "required" into each of the tags to create the field. I have written some JavaScript to open a popup if the form is valid but it isn't working, the form submits to my PHP database but the pop up window doesn't appear. Any thoughts? Here is my current JavaScript.
Code for the form fields -
label for="fname">First Name</label>
<input type="text" id="fname" name="firstname" placeholder="Your name..." required>
<label for="lname">Last Name</label>
<input type="text" id="lname" name="lastname" placeholder="Your last name..." required>
<label for="phonenumber">Phone Number</label>
<input type="text" id="phonenumber" name="phonenumber" placeholder="The best number to contact you on..." required>
Code to call the script -
<button onclick="myFunction()">Submit</button>
JavaScript validation
<script>
function validateForm() {
var x = document.forms["fname"].value;
var y = document.forms["lname"].value;
var p = document.forms["phonenumber"].value;
if ([x == "", y =="", p ==""]); {
alert("Name must be filled out");
return false;
}
}
function myFunction() {
if (x == "") {
return false;
}
else {
alert("Thank you for making an enquiry, a member of our team will be in contact with you soon.");
}
}
Try Code Below
<script>
function validateForm() {
var x = document.forms["Forms"]["fname"].value;
var y = document.forms["Forms"]["lname"].value;
var p = document.forms["Forms"]["phonenumber"].value;
if (x == "" && y =="" && p ==""); {
alert("Name must be filled out");
return false;
}
else
{
return true ;
}
}
<form name="Forms" onSubmit="return validateForm() "><input type="text" name="fname" /><input type="text" name="lname" /><input type="text" name="phonenumber" /></form>
or you can simply use required in every input
I'm trying to display details inputted into the form in the div on the same page, when the submit button is clicked, it doesn't display.
<script type="text/javascript">
function checkinput(){
var a,b,c,d;
a = document.getElementById("fname").value;
b = document.getElementById("lname").value;
c = document.getElementById("address").value;
d = document.getElementById("email").value;
document.getElementById('output').innerHTML = a + b + c + d ;
}
</script>
<form id = "myform" onsubmit ="return false" >
<p>Firstname : <input type="text" name="Firstname" id="fname" value=""></p>
<p>Last name : <input type="text" name="lastname" id="lname" value=""></p>
<p>Address : <input type="text" name="Address" id = "address" value=""></p>
<p>Email : <input type="email" name="Email" id = "email" value=""></p>
<button onclick = "check()">submit</button>
</form>
<div id="output" style="width: 200px; height: 200px;border: 1px solid black">
</div>
I expect details inputted in the form to display in the div element below.
Just rename the method you try to call when button is clicked.
<button onclick="checkinput()">submit</button>
To put every part on its own line, add the "" between them
document.getElementById('output').innerHTML =
a + "<br/>" + b + "<br/>" + c + "<br/>" + d;
UPD
you can set the default type of the button to the "button" as it was recommended above and in this case, you don't need to handle the "onsubmit" event for the form
<form id="myform">
<p>Firstname : <input type="text" name="Firstname" id="fname" value=""></p>
<p>Last name : <input type="text" name="lastname" id="lname" value=""></p>
<p>Address : <input type="text" name="Address" id="address" value=""></p>
<p>Email : <input type="email" name="Email" id="email" value=""></p>
<button type="button" onclick="checkinput()">submit</button>
</form>
After that, you can use different js functions depending on your purposes
// Strait forward - just get names from the array and use the values
// in any way you like
function checkinput1() {
let html = "";
for(let name of ["fname", "lname", "address", "email"]) {
html += document.getElementById(name).value + "<br/>";
}
document.getElementById('output').innerHTML = html;
}
// If you need just to concatenate values
function checkinput2() {
document.getElementById('output').innerHTML = `${document.getElementById('fname').value}
<br/>${document.getElementById('lname').value}
<br/>${document.getElementById('address').value}
<br/>${document.getElementById('email').value}`;
}
// When you want to get all values from the form inputs and don't
// care about their real names. You can also skip the empty values, so
// no empty lines will be added to the result
function checkinput3(){
let values = [];
for(let elem of document.querySelectorAll('#myform input')){
if(elem.value) values.push(elem.value);
}
document.querySelector('#output').innerHTML = values.join('<br/>');
}
I'm performing some validation checks on some inputs from the user. I was wondering how do I check that the email entered by the user contains an # symbol and a '.' as well as characters before and after the # symbol. Thanks in advance for answering.
<!DOCTYPE html>
<html>
<head>
<script language="JavaScript">
function showInput() {
var comment = document.getElementById("com").value;
var first = document.getElementById("fname").value;
var last = document.getElementById("lname").value;
var dateOfVisit = document.getElementById("date").value;
var firstError = document.getElementById('firstNameError');
var lastError = document.getElementById('lastNameError');
var displayEl = document.getElementById('displayname');
if (!first) {
firstError.setAttribute('style', 'display: block; color: red');
} else {
firstError.setAttribute('style', 'display: none;');
}
if (!last) {
lastError.setAttribute('style', 'display: block; color: red');
} else {
lastError.setAttribute('style', 'display: none;');
}
displayEl.innerHTML =
first + " " + last + " visited this on " + dateOfVisit + " and said '" + comment || 'not a thing...' + "'";
}
</script>
<title>Great Pyramid of Giza</title>
</head>
<body>
<h2>Leave A Review!</h2>
<p>Have you been to this wonder of the world? If so, leave a review.</p>
<form>
First Name:<br>
<input type = "text" name="firstname" id="fname"><br>
<span style="display: none;" id="firstNameError">First name is required!</span>
Last Name:<br>
<input type = "text" name="lastname" id="lname"><br>
<span style="display: none;" id="lastNameError">Last name is required!</span>
Email Address:<br>
<input type = "text" name="email"><br>
Date of Visit:<br>
<input type = "text" name="date" id="date"><br>
Comment:<br>
<input type = "text" name="comment" size="70" id="com"><br>
</form>
<input type = "submit" value="Submit" onclick="showInput();">
<h2>Comments:</h2>
<p><span id='displayname'></span></p>
</body>
</html>
You can create a email input and validate against that instead of using any regex...
function isEmail(email) {
var input = document.createElement('input')
input.type = 'email'
input.value = email
return input.validity.valid
}
console.log(isEmail('admin#example.com'))
console.log(isEmail('#example.com'))
But why bother??? just use <input type="email"> and skip all javascript nonsens
<form>
<input type="text" name="firstname" required autocomplete="given-name">
<input type="text" name="lastname" required autocomplete="family-name">
<input type="email" name="email" autocomplete="email">
<input type="date" min="2018-04-21" name="date">
<textarea name="comment"></textarea>
<input type="submit">
</form>
ps, use form.onsubmit instead of btn.onclick (way better)
read more about constraint validation and inputs
I created a form with three fields first_name, Last_name, city and in the fourth field, I am having an Id column which is read-only. When the user fills the first three fields in the form, before submitting it should generate an id in the fourth column but here it should use the first two alphabets that are in the fields to generate an Id
For eg. First_name = Roid, Last_name = Steve, city = California then in the fourth field it should automatically generate this id = rostca (all the first two alphabets)
How to achieve this?
Here is a JavaScript version to answer to your issue.
(function () {
populate();
})();
function populate () {
var str = "";
Array.from(document.getElementsByClassName("inputs")).forEach(function (element) {
str += element.value.substr(0, 2).toLowerCase();
});
document.getElementById("output").value = str;
}
<div>
<input type="text" class="inputs" value="Roid" oninput="populate();" />
<input type="text" class="inputs" value="Steve" oninput="populate();" />
<input type="text" class="inputs" value="California" oninput="populate();" />
<input id="output" type="text" readonly disabled />
</div>
Here is a jQuery answer to your issue.
$(function () {
populate();
$(".inputs").on("input", function() {
populate();
});
});
function populate () {
var str = "";
$(".inputs").each(function () {
str += $(this).val().substr(0, 2).toLowerCase();
});
$("#output").val(str);
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div>
<input type="text" class="inputs" value="Roid" />
<input type="text" class="inputs" value="Steve" />
<input type="text" class="inputs" value="California" />
<input id="output" type="text" readonly disabled />
</div>
Check below code,
function TextChanged(){
var first_name = document.getElementById("first_name").value;
var Last_name = document.getElementById("Last_name").value;
var city = document.getElementById("city").value;
document.getElementById("id").value = first_name.substring(0, 2) +Last_name.substring(0, 2) +city.substring(0, 2);
}
<input type="text" id="first_name" onblur="TextChanged()">
<input type="text" id="Last_name" onblur="TextChanged()">
<input type="text" id="city" onblur="TextChanged()">
<input type="text" id="id" readonly>
Check here jsbin demo, https://jsbin.com/qegazab/edit?html,js,console,output