I am having one link as 'Add more' which adds input element as many as I want. I want to call blur function on that.
Following html gets added while click on 'Add more' link:
<input required="" class="form-control js-validate-hoursToAdd timetoadd" step="0.01" name="calculations[settingIndex][hoursToAdd][calculationIndex]" type="number" value="">
Blur event works only for first element which is there in DOM by default. When I add new element, blur event doesn't get bind to the element.
Following is the javascript code.
$(document).ready(function() {
$(".timetoadd").blur(function(){
this.value = parseFloat(this.value).toFixed(2);
});
)};
It is in separate file called as backend.js. I am using webpack to minify the file and it is included in html file.
How to do that? Please help me out.
Use jQuery's on() method on a parent element with an additional selector as the second argument:
$(document).ready(function() {
$("#btnAdd").click(function() {
$('<br/><input required="" class="form-control js-validate-hoursToAdd timetoadd" step="0.01" name="calculations[settingIndex][hoursToAdd][calculationIndex]" type="number" value="">').appendTo(document.body);
});
$(document.body).on('blur', '.timetoadd', function(){
this.value = parseFloat(this.value).toFixed(2);
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<button type="button" id="btnAdd">Add more</button>
<br/><input required="" class="form-control js-validate-hoursToAdd timetoadd" step="0.01" name="calculations[settingIndex][hoursToAdd][calculationIndex]" type="number" value="">
Instead of document.body, you could also use any other parent that contains the inputs.
By adding the html attribute onblur and some javascript...
function myFunc(input) {
input.value = 0;
}
<input required="" class="form-control js-validate-hoursToAdd timetoadd" step="0.01" name="calculations[settingIndex][hoursToAdd][calculationIndex]" type="number" value="" onblur="myFunc(this)">
Here's an example I've made for you. Do this for your input. It should work fine
function GetValue(e){
alert(e.target.value);
};
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="inputgroup">
<input type="text" name="Dynamic_0" onblur="GetValue(event)">
<input type="text" name="Dynamic_1" onblur="GetValue(event)">
<input type="text" name="Dynamic_2" onblur="GetValue(event)">
</div>
// find elements
var id = $("#id > div")
var id1 = $("#id1")
var input = $("input")
var inputCopy;
var button = $("button")
// handle click and add class
button.on("click", function() {
$('<input required="" class="form-control js-validate-hoursToAdd timetoadd" step="0.01" name="calculations[settingIndex][hoursToAdd][calculationIndex]" type="number" value=""><br>').appendTo(id);
/* addMore(e.currentTarget, e.currentTarget.value);
console.log('new input', e.currentTarget); */
})
$(document.body).on("blur", '.timetoadd', function() {
this.value = parseFloat(this.value).toFixed(2);
inputCopy = input;
})
function addMore(e, value) {
inputCopy = e.clone()
id.prepend($(inputCopy));
}
body {
background: #20262E;
padding: 20px;
font-family: Helvetica;
}
#id {
background: #fff;
border-radius: 4px;
padding: 20px;
font-size: 25px;
text-align: center;
transition: all 0.2s;
margin: 0 auto;
width: 300px;
}
button {
background: #0084ff;
border: none;
border-radius: 5px;
padding: 8px 14px;
font-size: 15px;
color: #fff;
}
#id.alt {
background: #0084ff;
color: #fff;
margin-top: 40px;
width: 200px;
}
#id.alt button {
background: #fff;
color: #000;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="id">
<button>Add more</button>
<div>
<input required class="form-control js-validate-hoursToAdd timetoadd" step="0.01" name="calculations[settingIndex][hoursToAdd][calculationIndex]" type="number" value="">
</div>
</div>
JSFiddle: https://jsfiddle.net/kutec/c4pvLoua/
Related
I want to change width of a textfield when user enters more than 17 characters in that textfield using Javascript (if possible) otherwise by any other means.
I wrote a code to do the same, but it only changes width when user click outside the textfield after entering more than 17 characters. I want it to change width automatically when user enters more than 17 characters :
function widen() {
var value = nametf.value;
if (value.length > 17) {
nametf.style.width = '300px';
} else {
nametf.style.width = '200px';
}
}
#nametf {
width: 200px;
height: 20px;
padding: 5px 10px;
}
<title>TEXTFIELD TEST</title>
<form method="get" action="wwhome.php">
<input type="text" name="name1" id="nametf" onchange="widen()" value="" required>
</form>
onchange gets activated when the input looses focus, that's why it works when you click outside. On the other hand oninput will be triggered immediately when the value changes:
const nametf = document.getElementById('nametf');
function widen() {
var value = nametf.value;
if (value.length > 17) {
nametf.style.width = '300px';
} else {
nametf.style.width = '200px';
}
}
#nametf {
width: 200px;
height: 20px;
padding: 5px 10px;
}
<html>
<form method="get" action="wwhome.php">
<input type="text" name="name1" id="nametf" oninput="widen()" value="" required>
</form>
</html>
You need to pass a self-reference to the function using this. I would also change on-change to on-key-up, because on-change waits for you to move focus away from the field.
onkeyup="widen(this)"
Then you need to parameterize the function with your variable "nametf"
function widen(nametf) {
// ...
}
Example
function widen(nametf) {
var value = nametf.value;
if (value.length > 17) {
nametf.style.width = '300px';
} else {
nametf.style.width = '200px';
}
}
#nametf {
width: 200px;
height: 20px;
padding: 5px 10px;
}
<title>TEXTFIELD TEST</title>
<form method="get" action="wwhome.php">
<input type="text" name="name1" id="nametf" onkeyup="widen(this)" value="" required>
</form>
A better approach would be to use em units to expand the text are based on the current value.
initExpandingFields();
function initExpandingFields() {
Array.from(document.querySelectorAll('.expanding-field')).forEach(field => {
field.addEventListener('keyup', onFieldChange);
});
}
function onFieldChange(e) {
let field = e.target,
len = field.value.length;
field.style.width = (len * 0.667) + 'em';
}
#nametf {
width: 200px;
height: 20px;
padding: 5px 10px;
}
<title>TEXTFIELD TEST</title>
<form method="get" action="wwhome.php">
<input type="text" class="expanding-field" name="name1" id="nametf" value="" required>
</form>
Try this:
var nametf = document.getElementById("nametf");
nametf.addEventListener("input", function(){
if(nametf.value.length > 17) {
nametf.size = "30";
} else {
nametf.size = "20";
}
});
#nametf {
height: 20px;
padding: 5px 10px;
}
<title>TEXTFIELD TEST</title>
<form method="get" action="wwhome.php">
<input type="text" name="name1" id="nametf" size="20" value="" required>
</form>
While doing a task in Javascript30 I noticed that
document.querySelectorAll('input')[0].style.setProperty and document.documentElement.style.setProperty output thesame object but the former does not work when I try to set a property.
I want to know why the former does not work but the later does.
I did a console.log to view the output of both lines of code.
let controller = document.querySelectorAll(".controller input");
//console.log(document.querySelectorAll('input')[0].style.setProperty);
//console.log(document.documentElement.style.setProperty);
function handleChange() {
const suffix = this.dataset.sizing || "";
document.documentElement.style.setProperty(`--${this.name}`, this.value + suffix);
/*document.querySelectorAll('input').forEach((input) => {
input.style.setProperty(`--${this.name}`, this.value + suffix);
});*/
}
controller.forEach(input => input.addEventListener('change', handleChange));
controller.forEach(input => input.addEventListener('mousemove', handleChange));
body {
text-align: center;
color: white;
background-color: rgb(150, 200, 140);
}
:root {
--blur: 10px;
--spacing: 10px;
--color: red;
}
img {
padding: var(--spacing);
filter: blur(var(--blur));
background: var(--color);
}
<header>Playing with CSS variables and JS</header>
<div class="controller">
<label for="spacing">Spacing: </label>
<input type="range" min="10" max="200" id="spacing" name="spacing" value="10" data-sizing="px">
<label for="blur">Blur: </label>
<input type="range" min="0" max="30" id="blur" name="blur" value="10" data-sizing="px">
<label for="color">Base Color</label>
<input type="color" id="color" name="color">
</div>
<img src="https://res.cloudinary.com/dzwmmrwr2/image/upload/v1542708495/6_kmfxtt.png" alt="image" width="300" height="350">
Plunker
The Problem is that you are selecting the 'input-elements' using the querySelector, instead of the 'html-element' as you do with document.documentElement
using document.querySelectorAll('html') instead of document.querySelectorAll('input') sould solve your issue:
// Code goes here
let controller = document.querySelectorAll(".controller input");
function handleChange() {
const suffix = this.dataset.sizing || "";
document.querySelectorAll('html').forEach((input) => {
input.style.setProperty(`--${this.name}`, this.value + suffix);
});
}
controller.forEach(input => input.addEventListener('change', handleChange));
controller.forEach(input => input.addEventListener('mousemove', handleChange));
body {
text-align: center;
color: white;
background-color: rgb(150, 200, 140);
}
:root {
--blur: 10px;
--spacing: 10px;
--color: red;
}
img {
padding: var(--spacing);
filter: blur(var(--blur));
background: var(--color);
}
<header>Playing with CSS variables and JS</header>
<div class="controller">
<label for="spacing">Spacing: </label>
<input type="range" min="10" max="200" id="spacing" name="spacing" value="10" data-sizing="px">
<label for="blur">Blur: </label>
<input type="range" min="0" max="30" id="blur" name="blur" value="10" data-sizing="px">
<label for="color">Base Color</label>
<input type="color" id="color" name="color">
</div>
<img src="https://res.cloudinary.com/dzwmmrwr2/image/upload/v1542708495/6_kmfxtt.png" alt="image" width="300" height="350">
I have created a simple payment form using HTML/CSS/JS and i want to make checks of what the user gives as inputs using html patterns. But i also want to create a pop up alert using JS to confirm the form which must pop after all required inputs are filled correctly and patterns are ok.The pop up alert must also contain the name the user provided and return it.But the problem is that when i press submit button, even though the required info is not filled, the alert does come up and says "Order Completed" ....How can i make the pop up come up only after all info is given correctly?Here is my code:
<!DOCTYPE html>
<html>
<style>
body {
border:10px solid black;
margin-top: 100px;
margin-bottom: 100px;
margin-right: 150px;
margin-left: 150px;
}
p.thick {
font-weight: bold;
}
input[type=text], select {
width: 100%;
padding: 20px 20px;
margin: 8px 0;
display: inline-block;
border: 1px solid #ccc;
border-radius: 4px;
box-sizing: border-box;
}
input[type=text]:focus {
border: 3px solid #555;
}
input[type=password]:focus {
border: 3px solid #555;
}
input[type=password], select {
width: 100%;
padding: 20px 20px;
margin: 8px 0;
display: inline-block;
border: 1px solid #ccc;
border-radius: 4px;
box-sizing: border-box;
}
input[type=submit] {
width: 100%;
background-color: #4CAF50;
color: white;
padding: 14px 20px;
margin: 8px 0;
border: none;
border-radius: 4px;
cursor: pointer;
}
input[type=submit]:hover {
background-color: red;
}
div {
border-radius: 5px;
background-color:rgb(238, 238, 232);
padding: 40px;
}
</style>
<body onload="CreditCard();">
<form id="Myform">
<div class="login-page">
<div class="form">
<fieldset>
<h1>Log in </h1>
<p>Username*: <input type="text" name="Username" pattern=".{3,}" title="3 or more characters"></p>
<p>Password*: <input type="password" name="pw" pattern="(?=.*\d)(?=.*[A-Z]).{5,}"placeholder="Password must contain 1 uppercaser and 1 number and must be atleast 5 digits." title="Must contain at least one number and one uppercase letter, and at least 5 or more characters."></p>
</fieldset>
<fieldset>
<h1> Payment </h1>
<select id="paymentmethod" onchange="CreditCard();">
<option value ="Payment on pickup">Payment on pickup</option>
<option value="Bank transfer/deposit">Bank transfer/deposit</option>
<option value="Credit/Debit card">Credit/Debit card</option>
</select>
<fieldset>
<div id="credit/debit card" style="display: block;">
<select name="cardtype" class="form">
<option value="VISA">VISA</option>
<option value="MasterCard">MasterCard</option>
</select>
<br>Card Number*:<br>
<input type="text" name="cardnumber" pattern="(?=.*\d).{16,16}" title="Enter a 16-digit card number please." style="width:80%;" maxlength="20" value="" required>
<tr>
<td height="22" align="right" valign="middle">Expiry Date:</td>
<td colspan="2" align="left">
<SELECT NAME="CCExpiresMonth" >
<OPTION VALUE="01">January (01)
<OPTION VALUE="02">February (02)
<OPTION VALUE="03">March (03)
<OPTION VALUE="04"SELECTED>April (04)
<OPTION VALUE="05">May (05)
<OPTION VALUE="06">June (06)
<OPTION VALUE="07">July (07)
<OPTION VALUE="08">August (08)
<OPTION VALUE="09">September (09)
<OPTION VALUE="10">October (10)
<OPTION VALUE="11">November (11)
<OPTION VALUE="12">December (12)
</SELECT>
<SELECT NAME="CardExpiresYear">
<OPTION VALUE="04"SELECTED>2016
<OPTION VALUE="05">2017
<OPTION VALUE="06">2018
<OPTION VALUE="07">2019
<OPTION VALUE="08">2020
<OPTION VALUE="09">2021
<OPTION VALUE="10">2022
<OPTION VALUE="11">2023
<OPTION VALUE="12">2024
<OPTION VALUE="13">2025
</SELECT>
</td>
</tr>
</fieldset>
</fieldset>
<h1> Order Information </h1>
<p class="thick"> Name*: </p> <input type="text" id="customername" style="width:55% name="cardholder" value="" pattern=".{1,}" title="Please enter a name" required>
<p class="thick"> Adress*: </p> <input type="text"style="width:55;" name="cardholderadr" value="" pattern=".{3,}" title="Please enter an adress" required>
<p class="thick"> Phone </p> <input type="text"style="width:55;" pattern="(?=.*\d).{10,10}" title="Enter a 10 digit number please." name="cardholderpho" value="" >
<p class="thick"> email <input type="text" name="email" pattern="[a-z0-9._%+-]+#[a-z0-9.-]+\.[a-z]{2,3}$" title="Please enter a valid email adress" placeholder="example#email.com" >
<p class="thick"> Delivery comments </p> <input type="text" style="width:55; padding: 50px ;" name="cardholdercomm" value="" >
<p style="color:blue;"> I agree with the <a href="https://en.wikipedia.org/wiki/Terms_of_service">
*terms</a> <input type="radio" name="terms" title="Please agree to our terms." unchecked required onclick="terms();"></p>
<input type="submit" value="Submit" onclick="confirmed();">
<input type="button" onclick="reset()" value="Reset form">
</div>
</div>
</form>
<script>
function CreditCard() {
prefer = document.forms[0].paymentmethod.value;
if (prefer == "Credit/Debit card") {
document.getElementById("credit/debit card").style.visibility = "visible";
} else {
document.getElementById("credit/debit card").style.visibility = "hidden";
}
}
function paymentwithcard() {
document.getElementById("credit/debit card").style.visibility = "hidden";
}
function reset() {
document.getElementById("Myform").reset();
}
function confirmed() {
var x = document.getElementById("customername").value;
alert("Order completed.Name used:" + x);
}
function terms() {
}
</script>
</body>
</html>
Focus on the inputs and the function confirmed().
The submit method executes when you press submit.
First you have to let the submit method wait that the comfirm method can execute, after it the submit method can be executed.
To accessing the attribute in your js you can use an id.
document.getElementById('submit-form').submit(function(ev) {
ev.preventDefault(); // to stop the form from submitting
confirmed();
this.submit(); // If confirmed succeeded
});
<input id="submit-form" type="submit" value="Submit">
To prevent form from submitting you need to change `onclick attribute
<input type="submit" value="Submit" onclick="return confirmed();">
and your function must return true or false depending on your form validation.
You are listening onclick, instead, you should listen for the submit event
Don't only rely on client-side validation, it's good for a clean UX but never trust the client
HTML5 provides some validation options in the form of the required and pattern attributes
window.addEventListener('load', function () {
document.getElementById('example-submit').addEventListener('submit', function () {
alert('done');
});
});
input:invalid {border: 1px solid red;}
input:valid {border: 1px solid green;}
<form action="?" method="post">
<input type="text" id="expire-year" required pattern="20[123]\d" placeholder="YYYY" />
<input type="text" id="expire-month" required pattern="0?[1-9]|1[012]" placeholder="MM" />
<input type="text" id="expire-day" required pattern="0?[1-9]|2\d|3[01]" placeholder="DD" />
<input type="submit" id="example-submit" />
</form>
Side notes
In your code, CreditCard isn't a constructor. Consider using a cammel case name creditCard instead
Try to cut down the code in your question to the bare minimum/example case if you want good quality answers, nearly all of the HTML provided is irrelevant to the question
I didn't use a snippet because the embedded iframe here on SO doesn't let you submit forms :)
i have a span tag in javascript file like that
<input type="text" id="name" onblur="submitFormEmail()"/>
<span class="error">This is an error</span>
and here is its style in the css
.form_wrapper span.error{
visibility:hidden;
color:red;
font-size:11px;
font-style:italic;
display:block;
margin:4px 30px;
}
how can i change the visibility of the span when calling the function submitFormEmail()??
function submitFormEmail(){
}
Just
document.getElementsByClassName(".error")[0].style.visibility="visible";
To call it in your function you can do the following:
function submitFormEmail(){
document.querySelector('.error').style.visibility = 'visible';
}
Assuming there has many input elements, so the function should find out which node be match.
function submitFormEmail(obj) {
var nextSpan = obj.nextSibling;
while(nextSpan.nodeType != 1){
nextSpan = nextSpan.nextSibling;
}
nextSpan.style.visibility = 'visible';
}
.error {
visibility: hidden;
color: red;
font-size: 11px;
font-style: italic;
display: block;
margin: 4px 30px;
}
<input type="text" id="name" onblur="submitFormEmail(this)" /> <span class="error">This is an error</span> <br/>
<input type="text" id="name1" onblur="submitFormEmail(this)" /> <span class="error">This is an error</span> <br/>
<input type="text" id="name2" onblur="submitFormEmail(this)" /> <span class="error">This is an error</span>
I am trying to auto update the image to the text of the input box.
Here is the index code:
<body>
<div id="registeer">
<form method="post" action="javascript:login()">
<input type="text" name="gebruikersnaam" placeholder="Gebruikersnaam" /><br><br>
<input type="password" name="wachtwoord" placeholder="Wachtwoord" /><br><br>
<input type="submit" value="Registeer">
<form>
<br>
</div>
<div id="registeer-avatar"></div>
<script src="registeer.js"></script>
And here is the registeer.js:
$("#registeer input[type=text]").keyup(function(){
var value = $(this).val();
var background = "url(https://www.habbo.nl/habbo-imaging/avatarimage?img_format=gif&user=" + value + "&action=std&direction=3&head_direction=3&gesture=sml&size=b)";
$("#registeer-avatar").css("background", background);
});
$("#registeer input[type=text]").blur(function() {
if(!this.value) {
$("#registeer-avatar").css("background", "url(https://www.habbo.nl/habbo-imaging/avatarimage?img_format=gif&user=ulk&action=std&direction=3&head_direction=3&gesture=sml&size=b)");
}
});
So if you type in the first input for example 'hi', the image in registeer-avatar will be habbo....&user=hi, but it is not working.
Thanks for the help.
It works, but you need to size the container:
<div id="registeer-avatar"></div>
as it is now it has no "space" and when background is set, it does not show.
Try, for example, CSS:
#registeer-avatar {
border: 1px solid #eee;
min-height: 100px;
}
$("#registeer input[type=text]").keyup(function(){
var value = $(this).val();
var background = "url(https://www.habbo.nl/habbo-imaging/avatarimage?img_format=gif&user=" + value + "&action=std&direction=3&head_direction=3&gesture=sml&size=b)";
$("#registeer-avatar").css("background-image", background);
console.log(background);
});
$("#registeer input[type=text]").blur(function() {
if(!this.value) {
$("#registeer-avatar").css("background", "url(https://www.habbo.nl/habbo-imaging/avatarimage?img_format=gif&user=ulk&action=std&direction=3&head_direction=3&gesture=sml&size=b)");
}
});
#registeer-avatar {
border: 1px solid #eee;
min-height: 100px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="registeer">
<form method="post" action="javascript:login()">
<input type="text" name="gebruikersnaam" placeholder="Gebruikersnaam" /><br><br>
<input type="password" name="wachtwoord" placeholder="Wachtwoord" /><br><br>
<input type="submit" value="Registeer">
<form>
<br>
<div id="registeer-avatar"></div>