Javascript code is not working properly - javascript

I have written a JavaScript code. In this the alert is displaying more than one time.
<input type="text" name="grouptype" id="grouptype">
<input type="hidden" id="type_id" name="type_id">
<input type="text" id="type_bal" name="type_bal" onfocus="place1(form.grouptype.id,form.type_id.id)">
function place1(x,y)
{
var place=document.getElementById(x).value;// it hold the value of grouptype
var place_id=document.getElementById(y).value;//it hold the value of type_id
if(place!="" && place_id=="") {
document.getElementById(x).focus();
alert("pl. select the livesearch data");
}
}
not only that I used a jQuery code also. The following is the code
//<!-- the following commented code is used to move tab index when we press enter-->
$("input[tabindex],select[tabindex], textarea[tabindex]").each(function () {
$(this).on("keypress", function (e) {
if (e.keyCode === 13)
{
var nextElement = $('[tabindex="' + (this.tabIndex + 1) + '"]');
if (nextElement.length) {
$('[tabindex="' + (this.tabIndex + 1) + '"]').focus();
$('[tabindex="' + (this.tabIndex + 1) + '"]').select();
e.preventDefault();
} else
$('[tabindex="1"]').focus();
}
});
});
The above code is used to move focus from one text field to another text field it is working properly when in another text field I kept a focus function named as place1 which I given in the above code is not invoking that place1 function without alert. Then i kept alert. By that the alert message it will was invoking by 3 times. why?

Related

how to stop checkbox from getting checked when confirm box cancel is clicked?

When clicking cancel I need the checkbox to go back to unchecked. But it's getting checked . I tried everything .
function ActivateReg(bID, cID, crID) {
console.log(bID, cID, crID);
var result = confirm("Do you really sure?");
if (result) {
//$ajax({ ajax call
} else {
$("#chkbox" + bID).prop("checked", false); // not working
}
/* else
{
$("#chkbox" + bID +cID +crID).prop("checked", false); // not working
}
*/
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="checkbox" id="chkbox" onclick="ActivateReg(' + item.as + ',' + item.bs + ',' + item.cs + ')" class="listCheckbox" />
you may include autocomplete='off' in your input tag. I had same type of issue which I solved by using this attribute
Ensure that you are pointing to correct checkbox with the selector.
Your checkbox id is chkbox and you are trying to point some other elements with "#chkbox" + bID where bID is not needed I suppose.
It works fine without that bID parameter.
function ActivateReg() {
var result = confirm("Do you really sure?");
if (result) {
} else {
$("#chkbox").prop("checked", false);
}
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
<input
type="checkbox"
id="chkbox"
onclick="ActivateReg()"
class="listCheckbox"
/>

Very new to Javascript. Can't seem to get 1 function to work in my code (berekenBedrag). Needs to calculate the total

I'm struggling with the same code for days now and it's becoming frustrating.
I checked youtube, google, read in Flanagan but I can't seem to find the answer.
Now, I believe I came to the end of my code but one function I don't get to work.
I need to have 1 input text were the user puts in an amount, presses enter and the total needs to go to input text 2.
After each input, the input from text 1 needs to get emptied.
Everything works except for calculating the total in input text 2.
Thanks for reading and appreciate the help.
This is my code:
<!DOCTYPE html>
<html>
<body>
<input type="text" id="input1"><br><br>
<input type="text" id="input2">
<script>
document.getElementById("input1").addEventListener("keyup", function(e) {
if ( e.keyCode === 13) {
myFunction();
}
});
function myFunction() {
var bedrag = leesInvoer("input1");
document.getElementById("input1").value="";
document.getElementById("input2").value = berekenBedrag(bedrag).toFixed(2) +
" euro";
}
function berekenBedrag(pBedrag) {
var input = document.getElementById("input2");
pBedrag = pBedrag+input;
//This function is wrong but I don't know how to calculate the total from input 1 and 2 together.
return pBedrag;
}
function leesInvoer(invoerId) {
var invoer = document.getElementById(invoerId);
var getal = +invoer.value;
return getal;
}
</script>
</body>
</html>
Put the " euro" outside the input
Parse the number
Disable the other field from accepting input
Use "change" in case they use another input method (tab off, hit "enter" or some other way (click off) etc.
Reset the input value where you got it (I used null but that is a style choice)
document.getElementById("input1")
.addEventListener("change", function(e) {
//if (e.keyCode === 13) {
myFunction();
//}
});
function myFunction() {
var bedrag = leesInvoer("input1");
document.getElementById("input2").value = berekenBedrag(bedrag).toFixed(2);
}
function berekenBedrag(pBedrag) {
let input = document.getElementById("input2");
pBedrag = pBedrag + (input.value * 1);
return pBedrag;
}
function leesInvoer(invoerId) {
let invoer = document.getElementById(invoerId);
let getal = !isNaN(parseFloat(invoer.value)) && isFinite(invoer.value) ? parseFloat(invoer.value) : 0;
invoer.value = null;
return getal;
}
<div><input type="text" id="input1"></div>
<div>
<input type="text" id="input2" disabled><span> euro</span></div>
You can use a global variable to store the total (which starts at 0) and add the value of the input after converting to a number (using the unary plus operator) each time.
document.getElementById("input1").addEventListener("keyup", function(e) {
if (e.keyCode === 13) {
myFunction();
}
});
let total = 0;
function myFunction() {
var bedrag = +document.getElementById("input1").value;
total += bedrag;
document.getElementById("input1").value = "";
document.getElementById("input2").value = total.toFixed(2) +
" euro";
}
<input type="text" id="input1"><br><br>
<input type="text" id="input2">

Trying to clear an error prompt using JQuery

I am trying to clear an error icon on keydown.
** EDIT - adding the HTML **
<input class="validate" type="text" data-type="string" id="address" />
<input class="validate" type="text" data-type="number" id="zip" />
** END EDIT - Unsure if this will help shed some light **
Currently, the error displays using this function:
function validateFields(){
$(".validate").blur(function(){
var status = "";
var label = this.id;
var value = this.value;
if(value != ""){
status = "good";
console.log("status " + status);
}
else{
status = "error";
console.log("status " + status);
}
if(status == "good"){
label.html(label.html()+' ✅');
}
if(status == "error"){
label.html(label.html()+' ❌');
}
});
}
If status equals Error, show the error icon.
So now, I want to clear the error when the user keydowns. Here is my attempt:
function clearError(){
$(".validate").keydown(function(){
var datatype = $(this).data("type");
var label = this.id;
label.html(label.html()+' ');
});
}
Obviously, I am not having much success clearing the error using the above keydown function.
How can I make this work?
The label business with trying to keep the text inside is not very intuitive, so I added span to your label so you remove and add error symbols from the span in your functions. Additionally, you had some unnecessary code that could be removed in both functions. For example, your if statements checking status were unnecessary since you already checked if the value was empty (where you set the status), therefore you could move that code into the if statement checking for empty values.
We set each corresponding span's id to the id of the input with "Span" id="testSpan", so it can be easily accessible by the JS functions. Remember inside jQuery functions this always refers to the non-jQuery object, so you can use the JS vanilla methods on it.
This is what I could come up with:
$(".validate").blur(function () {
var id = this.id; // get id
if (this.value != "") { // check if input is empty
document.getElementById(id + "Span").innerHTML = '✅'; //set ok symbol
console.log("good");
} else {
document.getElementById(id + "Span").innerHTML = '❌'; // set error symbol
console.log("error empty text");
}
});
$(".validate").keydown(function () {
// if value is empty set error symbol, otherwise nothing (keep ok symbol)
if (this.value === "") document.getElementById(this.id + "Span").textContent = "";
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<label for="test">test<span id="testSpan"></span></label>
<input id="test" class="validate">
<label for="test2">test<span id="test2Span"></span></label>
<input id="test2" class="validate">

Parsley.js phone number validation with custom autofill

I'm working on a form using Parsley form validation and am running into one last issue before it's all good to go. This is my first time using Parsley too.
I have this bit of custom script to autofill hyphens and parentheses:
<script type="text/javascript">
$("#inf_field_Phone1").on("change keyup paste", function () {
var output;
var input = $("#inf_field_Phone1").val();
input = input.replace(/[^0-9]/g, '');
var area = input.substr(0, 3);
var pre = input.substr(3, 3);
var tel = input.substr(6, 4);
if (area.length < 3) {
output = "(" + area;
} else if (area.length == 3 && pre.length < 3) {
output = "(" + area + ")" + " " + pre;
} else if (area.length == 3 && pre.length == 3) {
output = "(" + area + ")" + " " + pre + "-" + tel;
}
$("#inf_field_Phone1").val(output);
});
</script>
When tabbing through the form fields though to double check that all works well and I get to the phone number field, the first parenthesis autofills, and then when I submit the form, Parsley accepts that as a valid phone number. Here is the HTML:
<form accept-charset="UTF-8" id='become-partner-form' method="POST" name='Form'>
<div class="col-md-6">
<input type="tel" class="form-control tc-custom-focus" id="inf_field_Phone1" name="inf_field_Phone1" placeholder="Phone*" data-parsley-trigger='change' data-parsley-required>
</div>
And this may be unrelated but just in case, here is the js that is binding Parsley to the form:
<script type="text/javascript">
$(function () {
$('#become-partner-form').parsley().on('field:validated', function() {
var ok = $('.parsley-error').length === 0;
$('.bs-callout-warning').toggleClass('invisible', ok);
})
});
</script>
Please let me know if you need a jsfiddle or anything to help out (I don't post here much!)
Any ideas on how to prevent the form submit without a full valid phone number?
First, you probably want to use the input event instead of change (useless in your case btw), keyup and paste.
Parsley uses the inputevent, so as long as your code runs before parsley's (i.e. if you bind your autofill code before Parsley), you should be ok.

How do I use onFocus, onChange, and onClick events on a <input type="text"> field

I have a homework assignment where I am supposed to use the onFocus, onChange and onClick events on each of three form fields. Each event is supposed to pass the field name to the function. The function is supposed to alert that the event has taken place and let the user know how many alerts have occurred. I have spent the last week trying to find the answer and all I have been able to consistently find is that the onFocus event is NOT to be used with text fields (that does not change my assignment though). The code I have so far is as follows:
<SCRIPT LANGUAGE="JavaScript">
<!--
var numEvents = 0;
var field1 = "";
var field2 = "";
var field3 = "";
function clickedField(fieldId) {
if (document.form1.field1.value = field1){
events=runningTotal(1);
alert("You have clicked Field 1. Alert Count = " + runningTotal(i) + ".");
}
if (document.form1.field2.value = field2){
events=runningTotal(1);
alert("You have clicked Field 2. Alert Count = " + runningTotal(i) + ".");
}
if (document.form1.field3.value = field3){
events=runningTotal(1);
alert("You have clicked Field 3. Alert Count = " + runningTotal(i) + ".");
}
}
function changedField(fieldId) {
if (document.form1.field1.value!= field1){
events=runningTotal(1);
alert("You have changed Field 1. Alert Count = " + runningTotal(i) + ".");
}
if (document.form1.field2.value!= field2){
events=runningTotal(1);
alert("You have changed Field 2. Alert Count = " + runningTotal(i) + ".");
}
if (document.form1.field3.value!= field3){
events=runningTotal(1);
alert("You have changed Field 3. Alert Count = " + runningTotal(i) + ".");
}
}
/*
function focusedField(fieldId) {
if (document.form1.field1.value = field1){
events=runningTotal(1);
alert("You have focused on Field 1. Alert Count = " + runningTotal(i) + ".");
}
else if (document.form1.field2.value = field2){
events=runningTotal(1);
alert("You have focused on Field 2. Alert Count = " + runningTotal(i) + ".");
}
else if (document.form1.field3.value = field3){
events=runningTotal(1);
alert("You have focused on Field 3. Alert Count = " + runningTotal(i) + ".");
}
}*/
function runningTotal(i){
numEvents += i;
return numEvents;
}
// -->
</SCRIPT>
I know there are several errors though not in the actual code because it is not doing what I need it to do. Before I added the . Alert Count = " + runningTotal(i) + "." and the argument to the alert it was telling me when I changed a field.
I'm not sure you need the folloing code to trigger those javascript functions
<input name="field1" id="field1" onfocus="focusedField(this.id)" onclick="clickedField(this.id)" onchange="changedField(this.id)"/>
<input name="field2" id="field2" onfocus="focusedField(this.id)" onclick="clickedField(this.id)" onchange="changedField(this.id)"/>
<input name="field3" id="field3" onfocus="focusedField(this.id)" onclick="clickedField(this.id)" onchange="changedField(this.id)"/>
if (document.form1.field1.value = field1){
Need to be
if (document.form1.field1.value == field1){
First, I don't see anywhere in your code that you assign those functions to the necessary events.
Second, I don't see anywhere that the field1, field2, and field3 vars are assigned to a value. Along with that, you are checking the value of the field, and I'm not sure why you are doing that, anyway.
And third, you have to use == to test for equivalency, not =.
first things first: your if statements need comparison operators (==) instead of assignment operators (=), after that
something like this would work:
window.onload = function(){
document.form1.field1.onclick = function(){
changedField(this);
}
}
It would send a reference to itelf to the function, where you can access its value or id etc.
It needs to be handled after window.onload to ensure the form items exist before the event is assigned.

Categories

Resources