I'm trying to create an <input> that on "unfocus or deselect" asks a function if the data entered inside is valid(Like a password checker) If it is i want it to then change the colour of the inputs background depending on the validity of the response
Width of walls in meters: <input size="40" placeholder="Please enter a number between 1 and 25" type="number" onkeypress="ifTwo();" name="wallWidthInput"><br> <!-- Input Field for wallWidthInput-->
var wallWidthElem = document.getElementsByName("wallWidthInput")[0]; //Finds wallWidthInput, sets wallWidthElem
var wallWidth = parseFloat(wallWidthElem.value) //converts wallWidthElem into a float, sets wallWidth
function ifTwo(){
if (1<=wallWidth && wallWidth<=25) {} //if the wallWidth is between 1 and 25, do nothing. If not alert the user!
else{document.getElementsByName("numberOfWallsInput").style.background="red"; wallWidth=1;}}
Define two css classes as follow:
.ff {background-color:yellow;}
.noff {background-color: red;}
script is like:
$(function(){
var myinput=$("wallWidthInput");
function checkPassword(){
//check your rules here
}
myinput.on('focusout',function(){
if(!checkPassword()){
myinput.toggleClasscss("ff");
}else{myinput.toggleClass("noff");}
});
myinput.on('focus',function(){
myinput.toggleClasscss("ff"); // or any default style
});
});
If you want to solve it with plain JavaScript you could do something like this.
<script type="text/javascript">
function validateWidth(input){ //we'll get the input element as paramter
var wallWidth = parseFloat(input.value); //read the value each time
if (1<=wallWidth && wallWidth<=25){
input.style.background=""; //you'll probably want to reset the background
} else {
input.style.background="red";
input.value=1;
}
}
</script>
Width of walls in meters:
<input size="40" placeholder="Please enter a number between 1 and 25" type="number" onchange="validateWidth(this);" name="wallWidthInput"><br>
I've chosen to trigger the validation onchange, because then we validate even if someone uses the small arrows.
<script type="text/javascript">
$(document).ready(function(){
function checkPassword(){
//your logic return true or false based on condition
}
$(":input[name='pwd']").on('focusout',function(){ // When losing focus
if(!checkPassword()){
$(this).css('background',somecolorCode);
}else{$(this).css('background','#ffffff');}
});
$(":input[name='pwd']").on('focus',function(){ // When focus
$(this).css('background','#333');
});
});
</script>
Related
I'm trying to do this in HTML for now where I have a input field of type=number where I don't want the user to be able to type decimal values/special characters/alphabets at all. I also want the min=30 and max=300so if a user types 29 and clicks else where, the value in the field should change to the min which is 30. If the user types in a value greater than 300 and clicks elsewhere, then I want the value to change to 300 which is the max. I don't want to wait for the user to wait for them to click on a form button. This is what I have so far, where the error is that, the user can still type decimal, and type any value lower than 30. Very new to html/js. Feel free to help me with js implementation if you think that is easier.
<input type="number" min="30" max="300" step="1" oninput="validity.valid||(value=value.replace(/\D+/g, ''))" id="seconds" name="seconds" value="30">
<html>
<script>
function change(){
var inp = document.getElementById("box").value;
inp = Math.floor(inp);
if(inp<30){
document.getElementById("box").value = 30;
}
else if(inp>300){
document.getElementById("box").value = 300;
}
else {
document.getElementById("box").value = inp;
}
}
</script>
<BODY>
<input type= "number" onmouseout = "change()" id ="box"/>
</BODY>
</HTML>
this java script should do
use "onmouseout".
I have a form that lists a remaining quantity of a product and below it an input field that lets you put a quantity into the form to submit for purchase.
I have the remaining quantity wrapped in a span with an ID.
On keyup, I want to compare the value of the span with the input entered into the field.
If the input is greater than the value in the span, on keyup, I want to change the value of the input to 0 or the equivalent of the span ID value.
Here is my javascript I am trying to use to accomplish this:
<script>
$(document).ready(function () {
document.getElementById('one_and_done_stool_QTY_check').keyup(Qty_check);
function Qty_check(){
var QTY1check = document.getElementById('one_and_done_stool_QTY_check').value;
var QTY1remain = document.getElementById('one_and_done_stool_QTY_remain').innerHTML;
if (QTY1check.value > QTY1remain.innerHTML)
alert("NOPE");
{document.getElementById("one_and_done_stool_QTY_check").value = 0;}
};}
</script>
And here is the html:
<span id="one_and_done_stool_QTY_remain">2</span>
<input id="one_and_done_stool_QTY_check" type="text" name="one_and_done_stool">
Your main issue is in this line:
document.getElementById('one_and_done_stool_QTY_check').keyup(Qty_check);
You can rewrite:
document.getElementById('one_and_done_stool_QTY_check').onkeyup = Qty_check;
or you may use directly the input event:
document.getElementById('one_and_done_stool_QTY_check').addEventListener('input', Qty_check);
or the jQuery way:
$('#one_and_done_stool_QTY_check').on('input', Qty_check);
The snippet:
document.getElementById('one_and_done_stool_QTY_check').addEventListener('input', Qty_check);
function Qty_check(e) {
var QTY1check = +document.getElementById('one_and_done_stool_QTY_check').value;
var QTY1remain = +document.getElementById('one_and_done_stool_QTY_remain').textContent;
if (QTY1check > QTY1remain) {
console.log("NOPE");
document.getElementById("one_and_done_stool_QTY_check").value = 0;
}
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<span id="one_and_done_stool_QTY_remain">2</span>
<input id="one_and_done_stool_QTY_check" type="text" name="one_and_done_stool">
So I have a simple log in that requires a user to input values from a json file into two different text boxes ,when the user name and (in this case I have used ID as password) matches then an alert appears to say... "welcome"
After the .click function is carried out the users text still remains in the text box, how can I get both text boxes to appear blank after the .click function?
$(document).ready(function() {
//Hide alert when page loads
$("#loginalert").hide();
$("#invalid").hide();
$("#loginbtn").click(function(event){
$.getJSON('result.json', function(jd) {
var id = $('#userName').val();
var name = $('#userName2').val();
var valid = false;
for (var i=0; i<jd.user.length; i++) {
if ((jd.user[i].ID == id) && (jd.user[i].name == name)) {
valid=true;
$('#loginalert').html('<img src="' + jd.user[i].imgpath + '"><br><p> Welcome: ' + jd.user[i].name + '</p><button type="button" id="btnhide" class="btn btn-primary btn-md">Hide</button>');
//show the alert after loading the information
$("#loginalert").stop().fadeIn('slow').animate({ opacity: 1.0 }, 3000)
$('#invalid').hide();
$('#btnhide').on('click', function(e){
//console.log('here');
e.preventDefault();
$('#loginalert').hide();
});
}
}
if (!valid) {
$('#invalid').fadeIn('slow');
$('#loginalert').hide();
}
});
}); });
username 1 and #username 2 are the text boxes - is there any way to get user name 2 to display in stars ****** when the user enters the password - this question is not that necessary but if i could also get that working that would be good.
thanks guys hope someone can help :)
is there any way to get user name 2 to display in stars ****** when
the user enters the password
You can use an input box with text property set as password. But that password masking character will be . instead of *. Not exactly sure, whether it will be a different character in some browsers.
<input type="password" id="txtPassword" />
text box to appear blank after .click function
You can set the .val() property of the jQuery objects of two those two textboxes.
$('#userName, #username2').val('');
Use <input type="password"> to show typing as stars.
Clear inputs by setting their value to be empty: $('#userName').val('');
And perhaps consider breaking your code down into a couple smaller functions so it's easier to follow.
document.getElementById("#myTextbox").value="";
This should get your textbox and set the value of it to "", which is blank.
Edit: JSFiddle
Another Method:
You can also add the script directly inside the button without using/creating a function.
<input id="inputId" type="name" />
<button onclick="document.querySelector('#inputId').value='';"> Clear </button>
Using querySelector:
<input id="inputId" type="name" />
<button onclick="click()"> Clear </button>
<script>
function click() {
document.querySelector('#inputId').value="";
}
</script>
I am trying to build a form using only JavaScript and jQuery. For one of the textboxes, I need to make it display as a date. And another as American Currency.
I have seen a few really cool forms before where it already has the " / /" symbols in there, and as you type the date, it falls perfectly into the symbols so you don't have to type them. Also, I need it to display as a date in the same format (mm/dd/yyyy) when a button is clicked. In addition, somehow, I need it where if no dates were entered, it displays nothing when the button is pushed.
EDIT:
Okay, so, after looking around online, I found a better way to describe what I am looking for for the date. It is exactly the same as the HTML5
<input type="date">
However, after clicking the button, I need it to display as MM/DD/YYYY and the HTML5 only allows YYYY-MM-DD which is NOT what I want.
So, how do I build a single textbox that has the same functions (I don't need the date picker) as the HTML5 "date", but with the display formate as MM/DD/YYYY after a button is clicked?
This sort of input is not trivial. There's some finesse that you'll need to do. First the HTML:
<div id="dateInput">
<input type="number" placeholder="MM" maxlength="2"/>/<input type="number" placeholder="DD" maxlength="2"/>/<input type="number" placeholder="YYYY" maxlength="4"/>
</div>
<div id="moneyInput">
$<input type="number"/>
</div>
Now basic CSS, we'll remove the borders from the inputs and instead add them to the containers:
input{
border:none;
background:transparent;
}
div{
border:1px solid #e0e0e0;
}
Here's the hardest part, the Javascript/jQuery. The money one should work natively but the date one will take some work.
$('#dateInput').on('input', function(){
//get max length of the input
var maxLength = parseInt($(this).attr('maxlength'));
//get the current value of the input
var currentValue = $(this).val();
//if the current value is equal to the maxlength
if(maxLength == currentValue.length){
//move to next field
$(this).next().focus();
};
});
On button press gather all the values from the inputs and display
$('button').on('click', function(e){
e.preventDefault();
//set the variable to append ti
var dateDisplay = '';
//iterate over the inputs
$('#dateInput input').each(function(){
//if dateDisplay exists (will explain soon)
if(dateDisplay && $(this).val() != ''){
//append the value
dateDisplay += $(this).val() + '/';
} else {
//if the value is blank, make the variable false.
dateDisplay = false;
};
});
//now check the variable
if(dateDisplay){
//if it's all good, remove the last character (/) and display
alert(dateDisplay.slice(0,-1));
}
return false;
});
This doesn't check for validity, just handles the general UX.
I was browsing online and in other forums, and found this answer:
$('#date').keyup(function(){
if ($(this).val().length == 2){
$(this).val($(this).val() + "/");
}
else if ($(this).val().length == 5){
$(this).val($(this).val() + "/");
}
});
I've read many blogs and posts on dynamically adding fieldsets, but they all give a very complicated answer. What I require is not that complicated.
My HTML Code:
<input type="text" name="member" value="">Number of members: (max. 10)<br />
Fill Details
So, a user will enter an integer value (I'm checking the validation using javascript) in the input field. And on clicking the Fill Details link, corresponding number of input fields will appear for him to enter. I want to achieve this using javascript.
I'm not a pro in javascript. I was thinking how can I retrieve the integer filled in by the user in input field through the link and displaying corresponding number of input fields.
You could use an onclick event handler in order to get the input value for the text field. Make sure you give the field an unique id attribute so you can refer to it safely through document.getElementById():
If you want to dynamically add elements, you should have a container where to place them. For instance, a <div id="container">. Create new elements by means of document.createElement(), and use appendChild() to append each of them to the container. You might be interested in outputting a meaningful name attribute (e.g. name="member"+i for each of the dynamically generated <input>s if they are to be submitted in a form.
Notice you could also create <br/> elements with document.createElement('br'). If you want to just output some text, you can use document.createTextNode() instead.
Also, if you want to clear the container every time it is about to be populated, you could use hasChildNodes() and removeChild() together.
<html>
<head>
<script type='text/javascript'>
function addFields(){
// Generate a dynamic number of inputs
var number = document.getElementById("member").value;
// Get the element where the inputs will be added to
var container = document.getElementById("container");
// Remove every children it had before
while (container.hasChildNodes()) {
container.removeChild(container.lastChild);
}
for (i=0;i<number;i++){
// Append a node with a random text
container.appendChild(document.createTextNode("Member " + (i+1)));
// Create an <input> element, set its type and name attributes
var input = document.createElement("input");
input.type = "text";
input.name = "member" + i;
container.appendChild(input);
// Append a line break
container.appendChild(document.createElement("br"));
}
}
</script>
</head>
<body>
<input type="text" id="member" name="member" value="">Number of members: (max. 10)<br />
Fill Details
<div id="container"/>
</body>
</html>
See a working sample in this JSFiddle.
Try this JQuery code to dynamically include form, field, and delete/remove behavior:
$(document).ready(function() {
var max_fields = 10;
var wrapper = $(".container1");
var add_button = $(".add_form_field");
var x = 1;
$(add_button).click(function(e) {
e.preventDefault();
if (x < max_fields) {
x++;
$(wrapper).append('<div><input type="text" name="mytext[]"/>Delete</div>'); //add input box
} else {
alert('You Reached the limits')
}
});
$(wrapper).on("click", ".delete", function(e) {
e.preventDefault();
$(this).parent('div').remove();
x--;
})
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="container1">
<button class="add_form_field">Add New Field
<span style="font-size:16px; font-weight:bold;">+ </span>
</button>
<div><input type="text" name="mytext[]"></div>
</div>