I have a problem with my code, namely: If in input #search_code I introduce letter 'm' and in #insert_code input I introduce letter "M", function returns "is not ok". I tried to make uppercase inputs with CSS text-transform: uppercase; but it does not work. What can we do to make input fields case insensitive?
var search_code = document.getElementById('search_code');
var insert_code = document.getElementById('insert_code');
var result = document.getElementById('result');
var button = document.getElementById('button');
var audio = new Audio('sound.wav');
// respond to button click
button.onclick = function validate(e) {
e.preventDefault();
// show verification result:
if (search_code.value == insert_code.value) {
result.textContent = 'code ok';
result.className = "ok";
audio.play();
} else {
result.textContent = 'code is not ok';
result.className = "not-ok";
}
// clear input when wrong:
if (search_code.value !== insert_code.value) {
insert_code.value = '';
}
return false;
};
function clearField(input) {
input.value = "";
};
$(document).ready(function(){
$('#search_code').bind("cut copy paste",function(e) {
e.preventDefault();
});
});
...
<form>
<input type="text" name="search_code" onfocus="clearField(this, this.placeholder='');" onblur="this.placeholder='introdu codul'" id="search_code" placeholder="introdu codul" autocomplete="off" value=""/><br/>
<input type="" name="insert_code" onfocus="clearField(this, this.placeholder='');" onblur="this.placeholder='scaneaza codul'" id="insert_code" placeholder="scaneaza codul" autocomplete="off" value=""/><br/><br/>
<input type="submit" id="button" name="button" value="verifica COD" />
</form>
</div>
<div id="result"></div>
</div>
<script src="js/action_input.js"></script>
</body>
</html>
Convert those values to be compared to lowercase so that case sensitivity is no longer an issue.
var search_code = document.getElementById('search_code');
var insert_code = document.getElementById('insert_code');
var result = document.getElementById('result');
var button = document.getElementById('button');
var audio = new Audio('sound.wav');
// respond to button click
button.onclick = function validate(e) {
e.preventDefault();
// show verification result:
if (search_code.value.toLowerCase() == insert_code.value.toLowerCase()) {
result.textContent = 'code ok';
result.className = "ok";
audio.play();
} else {
result.textContent = 'code is not ok';
result.className = "not-ok";
}
// clear input when wrong:
if (search_code.value.toLowerCase() !== insert_code.value.toLowerCase()) {
insert_code.value = '';
}
return false;
};
function clearField(input) {
input.value = "";
};
$(document).ready(function() {
$('#search_code').bind("cut copy paste", function(e) {
e.preventDefault();
});
});
<form>
<input type="text" name="search_code" onfocus="clearField(this, this.placeholder='');" onblur="this.placeholder='introdu codul'" id="search_code" placeholder="introdu codul" autocomplete="off" value="" /><br/>
<input type="" name="insert_code" onfocus="clearField(this, this.placeholder='');" onblur="this.placeholder='scaneaza codul'" id="insert_code" placeholder="scaneaza codul" autocomplete="off" value="" /><br/><br/>
<input type="submit" id="button" name="button" value="verifica COD" />
</form>
<div id="result"></div>
You should be checking the variables for quality by first converting them into either upper or lower case. You can use String's "toLowerCase()" before comparisions.(If you need case insensitive comparision)
search_code.value.toLowerCase() == insert_code.value.toLowerCase()
Modify your condition check to as below
if (search_code.value.toLowerCase() == insert_code.value.toLowerCase()) {
That should make it run with no issues
Related
i've some trouble with this event listener. I'm tryng to add an event listener in the submit button, but it doesn't work. I don't know what I'm doing wrong!
This is my work:
const form = document.getElementById("form");
form.addEventListener('submit', (e) =>{
let valid = true;
valid=valida();
if(!valid){
e.preventDefault();
}
});
function valida() {
var nome = document.getElementById("nome");
const nomeVal = nome.value;
var cognome = document.getElementById("cognome");
const cVal = cognome.value;
let valida = true;
valida = nomeVal.length < 8 ? setError(nome, "devi inserire nome"): setSuccess(nome);
if (cVal.length < 8) {
valida = setError(cognome, "devi inserire cognome");
}
return valida;
}
function setError(input, m) {
input.className = "error"
const ciao = input.nextElementSibling;
ciao.innerText = m;
return false;
}
function setSuccess(input) {
input.className = 'success';
const error = input.nextElementSibling;
error.innerText = '';
return true;
}
<form id="form" name="registrazione" action="index.html" >
Nome: <input id="nome" name="nome" type="text"> <small></small><br>
Cognome: <input id="cognome" name="cognome" type="text"> <small></small>
<br>
<button id="button" type="submit">Submit</button>
</form>
I pasted your code into js fiddle.
There was a \u200b hidden character at the end of the 2nd line. Once I removed that it looks like it worked.
https://jsfiddle.net/mightypie/b1dmgtw2/9/
form.addEventListener('submit', (e) => {
Hi have you tried using onclick event handler?
Place the onlclick event in your submit button
<form id="form" name="registrazione" action="index.html" >
Nome: <input id="nome" name="nome" type="text"> <small></small><br>
Cognome: <input id="cognome" name="cognome" type="text"> <small></small>
<br>
<button id="button" onclick="test()" type="submit">Submit</button>
</form>
then on your js you can use the below code:
function test() {
let valid = true;
valid=valida();
if(!valid){
e.preventDefault();
}
};
I do some calculator and want user take turns input first and second value. I need stop program when user enter first value and continue when user enter second value in the same input field. User continues by pressing the "=" button in html code or "Enter".
$('#plus').on('click', function(){
var firstNum = $("#txt").val()
$("input").val('')
if (isResult === true || $("input").keypress() === 13){
var secondNum = $("#txt").val()
result = Number(firstNum)+Number(secondNum)
console.log(result)
}
<input type='text' id='txt' value='' onpaste="return false" placeholder="Enter number" />
JavaScript programs don't stop to wait for the user, they react to events that are triggered asynchronously by the user.
You can save the state of the program in a global variable between calls to the event handler.
var firstNum;
$('#plus').on('click', function() {
if (firstNum === undefined) {
firstNum = Number($("#txt").val());
} else {
var secondNum = Number($("#txt").val());
var result = firstNum + secondNum;
console.log(result);
}
$("#txt").val('');
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type='text' id='txt' value='' onpaste="return false" placeholder="Enter number" />
<button type="button" id="plus">+</button>
You can keep the second input element(and equal button) hidden when the page loads and then show the input(and equal button) when the operator is clicked by the user to make it more interactive.
You can get more information about toggling between hiding and showing an element on this astonishing website: https://www.w3schools.com/howto/howto_js_toggle_hide_show.asp
var firstNum;
var secondNum;
var first_in = document.getElementById("txt1");
var sec_in = document.getElementById("txt2");
var equal = document.getElementById("equals");
sec_in.style.display = "none";
equal.style.display = "none";
$('#plus').on('click', function() {
if (firstNum === undefined) {
firstNum = Number($("#txt1").val());
sec_in.style.display = "block";
equal.style.display = "block";
}
});
$('#equals').on('click', function() {
if (secondNum === undefined) {
secondNum = Number($("#txt2").val());
var result = firstNum + secondNum;
console.log(result);
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type='text' id='txt1' value='' onpaste="return false" placeholder="Enter first number" />
<button type="button" id="plus">+</button>
<input type='text' id='txt2' value='' onpaste="return false" placeholder="Enter second number" />
<button type="button" id="equals">=</button>
I have two inputs i want if one of them is equal to the other the button will be enabled else it's disabled.
I managed to do it in Ajax, but i need to do it in Javascript
$(':password').keyup(function() {
if($('#pass').val() == $('#pass1').val() && $('#pass').val()!=='') {
$('#go').removeAttr('disabled');
} else {
$('#go').attr('disabled', true);
}
});
This should work. It's your script "translated" to vanilla JavaScript.
document.querySelector(':password').addEventListener('keypress', function() {
if (document.querySelector('#pass').value == document.querySelector('#pass1').value && document.querySelector('#pass').value !== '') {
document.querySelector('#go').disabled = false;
} else {
document.querySelector('#go').disabled = true;
}
});
I created a JSFiddle for you, implementing that functionality in plain JS: https://jsfiddle.net/3m9g4p0h/4/
JS:
var pw1 = document.getElementById('pw1');
var pw2 = document.getElementById('pw2');
var button = document.getElementById('button');
function compare() {
button.disabled = pw1.value !== pw2.value || pw1 === '';
}
pw1.addEventListener('keyup', compare);
pw2.addEventListener('keyup', compare);
HTML:
<input type="password" id="pw1" />
<input type="password" id="pw2" />
<button id="button" disabled="true">
Click me
</button>
You are looking for form validation functionality.
There are a lot of plugins and libs for this kind of task.
but there is a simple example
function getElements(){
return {
password: document.querySelector('input[name="password"]'),
confirm: document.querySelector('input[name="passwordConfirm"]'),
button: document.querySelector('button'),
}
}
function validate(){
let els = getElements();
els.button.disabled = els.password.value !== els.confirm.value;
}
let elements = getElements();
elements.password.addEventListener('input', validate);
elements.confirm.addEventListener('input', validate);
validate();
<input name="password" type="password" placeholder="password...">
<input name="passwordConfirm" type="password" placeholder="password confirm...">
<button type="submit">submit</button>
and jQuery variant
function validate(event){
let $frm = $(event.target).closest('form');
let pas = $frm.find('input[name="password"]');
let conf = $frm.find('input[name="passwordConfirm"]');
let btn = $frm.find('button');
btn.prop('disabled', pas.val() !== conf.val());
}
let $frm = $('form');
$frm.on('input', validate);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js"></script>
<form>
<input name="password" type="password" placeholder="password...">
<input name="passwordConfirm" type="password" placeholder="password confirm...">
<button type="submit">submit</button>
</form>
Hope, you all doing well.
I am trying to validate firstname input field of a form with Javascript. For some reason, error messages doesn't display in order. Some of them override others, only just one error message is displaying, the rest is not.
I'm wondering why? Can anyone shed me some light please?
Here is my code:
// Predefined validator function to check if input is empty or not
var validator = {};
validator.isEmpty = function(input) {
// Stop execution if input isn't string
if (typeof input !== 'string') return false;
if (input.length !== 0) {
for (var i = 0; i < input.length; i++) {
if (input[i] !== " ") {
return false;
}
return true;
}
}
return true;
};
validator.isEmpty(null); // returns false
// Main part to get inputs and apply validation
window.onload = function() {
var signUp = document.getElementById("signUp");
var fName = document.getElementById("fName");
var suButton = document.getElementById("subMit");
// Submit button on the function
suButton.addEventListener('click', function(event) {
isNameValid(fName);
});
signUp.addEventListener('submit', function(event) {
event.preventDefault();
});
function isNameValid(char) {
var val = char.value;
if (validator.isEmpty(val)) {
if (val.length < 2) {
// Display a message if input length is less than 2
char.setCustomValidity("We expect your input should contain at least 2 characters, darling !");
char.style.borderColor = "red";
}
if(!isNaN(val)) {
char.setCustomValidity("Please, enter only characters");
char.style.borderColor = "red";
}
} else {
char.setCustomValidity("");
char.style.borderColor = "green";
}
}
<form id="signUp">
<input type="text" id="fName" name="firstname" placeholder="First name">
<input type="checkbox" name="result" required autofocus> Agree our conditions
<input type="submit" id='subMit' value="SUBMIT">
</form>
It took me a while but I hope following works for you. Let me know if you need help understanding anything. I felt your code was a bit complex so I simplified it.
<script>
function submitForm(){
var formValid = false;
var msg = "";
var fNameElement = document.getElementById("fName");
if(fNameElement){
var fNameValue = fNameElement.value;
if(fNameValue.length < 2){
msg = "We expect your input should contain at least 2 characters, darling !";
}
else if(!(/^[a-zA-Z]+$/.test(fNameValue))){
msg = "Please, enter only characters";
}
else{
formValid = true;
}
if(formValid){
fNameElement.style.borderColor="green";
//do something
}
else{
fNameElement.style.borderColor="red";
alert(msg); // or show it in a div
}
}
}
</script>
<form id="signUp" action="javascript:submitForm()">
<input type="text" id="fName" name="firstname" placeholder="First name">
<input type="checkbox" name="result" required autofocus> Agree our conditions
<input type="submit" id='subMit' value="SUBMIT">
</form>
Fiddle: https://jsfiddle.net/fxumcL3d/3/
Below is the code where textarea will be created automatically. But i want to disable comma in this textarea,so i am using the below javascript function.
$(document).ready(function(){
var counter = 1;
var val;
$("#addButton").click(function () {
var person = prompt("Please enter the Field name:", "");
if (person == null || person == "") {
return false;
} else {
val = person;
}
if(tabid == "menu4"){
return false;
}
//alert(tabid);
var newTextBoxDiv0 = $(document.createElement('div'))
.attr("class", 'form-group row')
.attr("id",'form1ac' + counter);
newTextBoxDiv0.after().html('<div class="col-xs-1"><input type="button" value="delete" onclick= rem(form1ac'+counter+')></div><div class="col-xs-1"><button type="button" class="btn btn" name="" id="buttonl" style="width: 170px;height:45px;background-color:#dcdcdc;color:black;">'+val+'</button><input type="hidden" name="buttonl" form="form1" value='+val+'></div><div class="col-xs-2"></div><div class="col-xs-4"><div class="form-group"><textarea form="form1" name="df" id="df" oninput = "this.value = this.value.replace(/[,]/g, "2")" ></textarea></div><input form="form1" type="hidden" name="tabid" value='+tabid+'></div>');
newTextBoxDiv0.appendTo('#'+tabid);
counter++;
});
$("#removeButton").click(function () {
if(counter==1){
alert("No more textbox to remove");
return false;
}
counter--;
$("#form1ac" + counter).remove();
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<textarea form="form1" name="df" id="df" oninput = "this.value = this.value.replace(/[,]/g, "2")" ></textarea>
The above jquery code will dynamically create new textarea with label option,which works perfectly. But i am trying to disable comma with the above mentioned javascript code which is not working perfectly.
Please help me!
If you want to prevent user to type a comma:
<textarea class="no-comma"></textarea>
And
$(function() {
$('textarea.no-comma').on('keydown', function(e) {
if (e.keyCode == 188 || e.keyCode == 110) { // thats a comma
e.preventDefault();
}
}).on('change input', function() {
var self = $(this);
self.html( self.html().replace(new RegExp(',', 'g'),'') ); // Remove all commas.
});
})
Your html has a syntax error "2")" >
Should be '2')" >
<textarea form="form1" name="df" id="df" oninput = "this.value = this.value.replace(/[,]/g, '2')" ></textarea>
In place of below code
<textarea form="form1" name="df" id="df" oninput = "this.value = this.value.replace(/[,]/g, "2")" ></textarea>
use below code
<textarea form="form1" name="df" id="df" oninput = 'this.value = this.value.replace(/[,]/g, "2")' ></textarea>