Event will not trigger - javascript

I have a form that has multiple inputs. One input is where user can input an ID. I need to verify the ID is unique. I want to call a JavaScript function for a onchange event. However, I can't get it to trigger. I have a console.log but it never hits when I make a change in the input so I am doing something wrong.
This is the function I am trying to call on the on change
function checkUniqueID() {
console.log("here");
var $counter = 0;
var tag = document.forms["userform"]["new_id"].value;
while ($counter < $totalItems) {
}
};
<div class="six wide field">
<label for="ID">ID</label>
<input type="text" id="new" name="new_id" placeholder="ID" onchange="checkUniqueID()">
</div>
I can't even get the console.log ("here") to trigger

The onchange HTML attribute triggers when the input loses focus.
So, if you correctly have your input#new_id inside a form like this:
<form name="userform">
<div class="six wide field">
<label for="ID">ID</label>
<input type="text" id="new" name="new" placeholder="ID">
</div>
</form>
Adding an eventListener in your script file would be enough.
document.userform.new_id.onchange=function(){
alert("ID changed to: "+this.value);
};
With jQuery would be as easy as:
$("#new").change(function(){
alert("ID changed to: "+$(this).value;
}
Here is a working fiddle:
https://jsfiddle.net/edbL3kgp/

Related

JavaScript change value and data from value in a span

I need help with this. I need to make the value in the other place change all the time while user session is active. How can I get the value from a span and make other value in a data change?
Look at there!
1 <div class="pt-uea-container">
2 <span class="pt-uea-currency pt-uea-currency-before"> € </span>
3 <input type="text" class="pt-field pt-uea-custom-amount" autocomplete="off" name="pt_items[1][amount]" id="pt_uea_custom_amount_1" value="199" placeholder="" data-parsley-errors-container="#pt_uea_custom_amount_errors_1">
4 <input type="hidden" class="pt-field pt-uea-custom-amount-formatted" name="pt_items[1][amount]" value="199" data-pt-price="199">
5 <input type="hidden" name="pt_items[1][label]" value="Amount:">
6 <input type="hidden" name="pt_items[1][tax_percentage]" value="0">
7 <input type="hidden" name="pt_items[1][type]" value="open">
8 <div id="pt_uea_custom_amount_errors_1"></div>
9 <span class="form-price-value">85</span>
10 </div>
The value in row 9 needs to constantly change values in row 3 and 4 on the same session. Don't mind the value in row 6.
Let me know how I can get this done. Or maybe a different approach?
Greetings!
========
So this is what I got for now from you guys:
jQuery(document).ready(function($) {
var checkViewport = setInterval(function() {
var spanVal = $('.form-price-value').text();
$('#pt_uea_custom_amount_1').val(spanVal);
$('#pt_uea_custom_amount_formatted_1').val(spanVal);
$('#pt_uea_custom_amount_formatted_1').attr('data-pt-price', spanVal);
}, 1000);
});
This code works, but it only affects my needs when I put my mouse in pt-field pt-uea-custom-amount and add a space in it. Then it does apply to the page source. But this is not correct. The source needs to get changed too without touching that class or a space or something!
You can easily do this with the help of jQuery.
With the help of jQuery I would do like this.
Understanding what input field needs to be tracked for changes. I will give all this field a class (track-me).
In the document ready, I will look for changes for that tracked field.
On change of that field I will get the value and put in other input fields (class copy-to - or you can do whatever you like).
See an example below,
HTML
<form>
<div class="">
<input type="text" class="track-me" value=""/>
</div>
<div class="">
<input type="text" class="copy-to" value=""/>
</div>
<div class="">
<input type="text" class="copy-to" value=""/>
</div>
<div class="">
<input type="text" class="copy-to" value=""/>
</div>
<div class="">
<div class="">Please type anything in the first input box</div>
</div>
</form>
jQuery
$(document).ready(function(){
$('.track-me').change(function (){
$('.copy-to').val($(this).val())
});
});
I made comments in the above jQuery code so you can understand. Also, I have made a fiddle so you can play and have a look. In this fiddle, I am using Bootstrap4 just for the purpose of styling, you don't have to worry about that.
Link to fiddle
https://jsfiddle.net/anjanasilva/r21u4fmh/21/
I hope this helps. Feel free to ask me any questions if you have. Cheers.
This is not an ideal solution. I'm not sure there is a verified way of listening for when the innerHTML of a span element changes. This sort of stuff is usually based on user interaction, and the value of the span will be modified by your page. The best solution would be to use the same method that updates the span element to update the values of you hidden input fields.
However, I've placed an interval that will run every second, that takes the text value of the span element and gives it to the values of the 2 input fields:
function start() {
setInterval(function() {
document.getElementById("pt_uea_custom_amount_1").value = document.getElementById("price_value").innerHTML;
document.getElementById("pt_uea_custom_amount_2").value = document.getElementById("price_value").innerHTML;
}, 1000);
}
window.onload = start();
<div class="pt-uea-container">
<span class="pt-uea-currency pt-uea-currency-before"> € </span>
<input type="text" class="pt-field pt-uea-custom-amount" autocomplete="off" name="pt_items[1][amount]" id="pt_uea_custom_amount_1" value="199" placeholder="" data-parsley-errors-container="#pt_uea_custom_amount_errors_1">
<input type="hidden" class="pt-field pt-uea-custom-amount-formatted" name="pt_items[1][amount]" value="199" data-pt-price="199" id="pt_uea_custom_amount_2">
<input type="hidden" name="pt_items[1][label]" value="Amount:">
<input type="hidden" name="pt_items[1][tax_percentage]" value="0">
<input type="hidden" name="pt_items[1][type]" value="open">
<div id="pt_uea_custom_amount_errors_1"></div>
<span id="price_value" class="form-price-value">85</span>
</div>
MutationObserver should work here..
const formValuePrice = document.querySelector( '.form-price-value' );
const inputText = document.querySelector( 'input[type="text"]' );
// timer to change values
window.setInterval( () => {
formValuePrice.textContent = Math.round( Math.random() * 100 );
}, 1000 );
// mutation observer
const observer = new MutationObserver( ( mutationsList ) => {
inputText.value = formValuePrice.textContent;
} );
observer.observe( formValuePrice, { childList: true } );
https://codepen.io/anon/pen/LgWXrz?editors=1111
try this, simple using jquery, you can check in inspect element for value attribute data-pt-price
Update: you can using jquery event .on() like change, click, keyup or else to Attach an event handler function for one or more events to the selected elements,
you can read the doc here.
here the updated code
$(function() {
var spanVal = $('#price_value').text();
$('#pt_uea_custom_amount_1').val(spanVal);
$('#pt_uea_custom_amount_formatted_1').val(spanVal);
$('#pt_uea_custom_amount_formatted_1').attr('data-pt-price', spanVal);
$('#pt_uea_custom_amount_1').on('change click keyup', function() {
$('#pt_uea_custom_amount_formatted_1').val($(this).val());
$('#price_value').text($(this).val());
$('#pt_uea_custom_amount_formatted_1').attr('data-pt-price', $(this).val());
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="pt-uea-container">
<span class="pt-uea-currency pt-uea-currency-before"> € </span>
<input type="text" class="pt-field pt-uea-custom-amount" autocomplete="off" name="pt_items[1][amount]" id="pt_uea_custom_amount_1" value="199" placeholder="" data-parsley-errors-container="#pt_uea_custom_amount_errors_1">
<input type="hidden" class="pt-field pt-uea-custom-amount-formatted" name="pt_items[1][amount]" value="199" data-pt-price="199" id="pt_uea_custom_amount_2">
<input type="hidden" name="pt_items[1][label]" value="Amount:">
<input type="hidden" name="pt_items[1][tax_percentage]" value="0">
<input type="hidden" name="pt_items[1][type]" value="open">
<div id="pt_uea_custom_amount_errors_1"></div>
<span id="price_value" class="form-price-value">85</span>
</div>

OnInvalid html event triggering after Required modifier removed through JS

I have three input fields I am attempting to enforce validity on. Currently, I have them all set as required, but removing the modifier with Javascript on submit if one of them is filled out; essentially, one must fill out at least one, but not none of these fields.
Here is an example of the fields:
jQuery(function ($) {
var $inputs = $('input[name=Input1],input[name=Input2], input[name=Input3]');
$inputs.on('input', function () {
// Set the required property of the other input to false if this input is not empty.
$inputs.not(this).prop('required', $(this).val().length > 0 && $(this).val() != 0)
});
});
jQuery(function ($) {
$("#Input1, #Input2").oninvalid = (function() {
$(this).setCustomValidity("Please enter a valid Input1, Input2, or Input3")
});
});
var Input3default = document.getElementById('Input3')
if (Input3.value.length == 0) Input3.value = "0";
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="container">
<div class="input-group mb-3">
<form action="" method="get" autocomplete="off">
<div class="row" style="text-align:justify; width: 100%; display:inline">
<div class="">
<label for="text3">Input1:</label>
<input type="text" id="Input1" name="Input1" required oninvalid="this.setCustomValidity('Please enter a valid Input1, Input2, or Input3')" />
</div>
<div class="">
<label for="text4">Input2:</label>
<input type="text" id="Input2" name="Input2" required oninvalid="this.setCustomValidity('Please enter a valid Input1, Input2, or Input3')"/>
</div>
<div class="">
<label for="text5">Input3:</label>
<input type="text" id="Input3" name="Input3" required placeholder="0" pattern="[0-9]*" onsubmit="Input3default" oninvalid="this.setCustomValidity('Please enter a valid Input3')"/>
</div>
</div>
<p>
<input type="submit" value=" Submit " />
</p>
</form>
</div>
</div>
This seems to work fine if I leave it default; I have Input1 and Input2 empty by default, and Input3 has a value of "0" by default. If I enter Input1 or Input2, my submission goes through just fine. However, the problems begin if I alter Input3.
Problem 1: Any time I enter Inputs 1 and 2 but leave 3 blank, it triggers invalidity; my Input3default never seems to trigger, and it is passed blank and caught by the oninvalid tag.
Problem 2: Along with that, if I do not specify an Input2 along with my Input1 while Input3 is blank, it triggers invalidity on Input2. Using Chrome Debugger, I can see that the Required tag is removed, but my OnInvalid pop-up still comes up no matter what is remedied.
Essentially, I am trying to solve the second problem: When I remove the required html tag from my input, after invalidating another input with a Javascript-enforced default, my inputs refuse to validate on the front end.
I appreciate any advice and conjecture as to why this may be the case, and believe that the two problems are connected.
EDIT: Upon adding an = to my original oninvalid JQuery function, I removed a JS error. It appears that my Input3 default function triggers on pageload, but not on submit; I added an onsubmit function to input3, but am still receiving oninvalid events for input2.
I was able to fix this issue on my own, using the OnInput event.
The setCustomValidity function, when triggered, does not allow a submission while a CustomValidity is set. In order to fix this, I edited my inputs as so:
<input type="text" id="Input1" name="Input1" required oninvalid="this.setCustomValidity('Please enter a valid Input1, Input2, or Input3')" oninput="this.setCustomValidity('')"/>
I still have a few kinks to iron out, but this fixed my main problem in that the validity of an input was not being reset.
I'll leave this answer unaccepted at first to allow others to pitch in.

I need help showing and hiding data based on a checkbox

Alright so I have a form. In the form I have a lot of check boxes. If a person clicks on the checkbox. It shows the field below the box. If they click on the checkbox again it makes the field below the checkbox disappear and makes the field have no value.
here is the code. I have JS running the show and hide. and Html calling it.
function ShowCutSewDescription() {
var select = $('#send_item_to_cutsew');
console.log(select)
//select = parseInt(select);
if (select.attr('checked', true)) {
$('#cutsew-checked').show();
}else {
$('#cutsew-checked').hide();
}
}
<div class="form-group">
<label class="col-md-3 control-label">Sending item to Cut/Sew Manager</label>
<div class="col-md-9">
<input type="checkbox" name="send_item_to_cutsew" class="form-control input-inline input-medium" placeholder="Enter text" onchange="ShowCutSewDescription()">
</div>
Changes made
► select.attr('checked', true) to select.is(":checked")
► $('#send_item_to_cutsew') to $('[name="send_item_to_cutsew"]') since there is no element with that Id.
Working Demo
function ShowCutSewDescription() {
var select = $('[name="send_item_to_cutsew"]');
if (select.is(":checked")) {
$('#cutsew-checked').show();
} else {
$('#cutsew-checked').hide();
}
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="form-group">
<label class="col-md-3 control-label">Sending item to Cut/Sew Manager</label>
<div class="col-md-9">
<input type="checkbox" name="send_item_to_cutsew" class="form-control input-inline input-medium" placeholder="Enter text" onchange="ShowCutSewDescription()">
</div>
<div id="cutsew-checked">
Sample box
</div>
I assume this is using jQuery. If so, the selector that you have input is looking for something with an id of send_item_to_cutsew.
jQuery uses css selectors as a base, as referenced by this page: https://api.jquery.com/category/selectors/
The proper way to get the input that you want based on the name is as follows:
var select = $('[name="send_item_to_cutsew]');
or you can set the id to the above like so:
<input type="checkbox" id="send_item_to_cutsew" name="send_item_to_cutsew" class="form-control input-inline input-medium" placeholder="Enter text" onchange="ShowCutSewDescription()">

Comparing 2 inputs with jquery

hello im trying to just compare what is inside of 2 different inputs.
$(document).ready(function() {
$('#pc').keydown(function() {
if ($('#ps').val() == $('#pc').val()) {
alert("it worked ");
}
});
});
<form id="identicalForm" class="form-horizontal" action="userSignup.php" method="post">
<fieldset>
<div id="legend">
<legend class="">Register</legend>
</div>
<div class="control-group">
<label class="control-label" for="email">E-mail</label>
<div class="control-group">
<label class="control-label" for="password">Password</label>
<div class="controls">
<input id="ps" name="password" placeholder="" class="form-control input-lg" type="password">
<p class="help-block">Password should be at least 6 characters</p>
</div>
</div>
<div class="control-group ">
<label class="control-label" for="password_confirm">Password (Confirm)</label>
<div class="controls">
<input id="pc" name="password_confirm" placeholder="" class="form-control input-lg" type="password">
<p class="help-block">Please confirm password</p>
</div>
</div>
</fieldset>
</form>
This is a semi condensed version of the web page. the inclusion is at the top of the page. if i put the alert outside of the if, it will do a pop up every time i type in that input box. but if i try to compare the two input fields nothing pops up when they both have the same password entered. from what ive seen from other SO post like this, it should work! I am still a novice with js, so i may just be over thinking this entirely.
The reason it wasn't working with the keydown event is because the event is only fired when the key is down. In other words, the event was being fired before the value was updated. You would be comparing 12345 with 1234 and even though the values would be the same, it wasn't recording the last character that was pressed.
Rather than using the keydown event, use the input or keyup event:
$('#pc').on('input', function() {
if ($('#ps').val() === $('#pc').val()) {
console.log("it worked ");
}
});
The keyup event is fired when the key is up, which means that the value of the element is actually updated. Similarly, the input event will behave the same way since it will be fired when the value changes. In addition, the input event will also catch paste events (which may be useful).
Instead of keydown, which actually executes before you press the key, use either blur or keyup:
$('#pc').on('blur', function() {
if ($('#ps').val() == $('#pc').val()) {
console.log("it worked ");
}
});
Use the keyup event. Also try to use === for comparing the values as we know the values are going to be both text type and do not need an explicit conversion before comparing.
$(document).ready(function () {
$('#pc').keyup(function () {
if ($('#ps').val() === $('#pc').val()) {
alert("it worked ");
}
});
});
The keyup event is sent to an element when the user releases a key on the keyboard.
Here is a working sample

blur/focusout doesn't work

I have multiple divs with the same class-'.new-contact.clearfix.invite'. The divs contain some inputs.
I want to perform validation on the form (which its class is 'invitePartners) only when I click/enter some input in different line (each div is a different line).
I tried the following, but the event is not triggered:
$('.invite').on('blur','.new-contact.clearfix.invite', function () {
$('.invitePartners').valid()
})
Example of the div's HTML:
<div class="row">
<div class="new-contact clearfix invite">
<div class="first-name invite">
<input type="text" id="firstName1" class="signup-input firstName required" name="first[1]" placeholder="">
</div>
<div class="last-name">
<input type="text" id="lastName1" class="signup-input lastName" name="last[1]" placeholder="optional">
</div>
<input type="text" data-index="1" id="inputMail1" class="signup-input mail" name="email[1]" placeholder="e.g. example#url.com" aria-invalid="true">
<span class="common-sprite sign-up-cross first clone"></span>
</div>
</div>
</div>
Quote from JQuery on help page :
The focus and blur events are specified by the W3C to not bubble, but jQuery defines cross-browser focusin and focusout events that do bubble.
This mean that your blur event don't go up the DOM when fired from .new-contact.clearfix.invite and so cannot be catch up by .invite
$('body').on('blur','.new-contact.clearfix.invite input', function () {
$('.invitePartners').valid()
});
Try .focusout() ...
$('.new-contact.clearfix.invite').focusout(function () {
$('.invitePartners').valid();
});
It's not really clear what your elements are, you should post your HTML in your question. If you are just trying to use elements that are related to the element blurred, you may need to use something like ...
$('.invitePartners', this).valid();

Categories

Resources